Skip to content

Instantly share code, notes, and snippets.

@mauleyzaola
Forked from Pigeo/uuid_bytea_casts.sql
Created June 29, 2023 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mauleyzaola/726736312c014f55f85f1cf93d125db6 to your computer and use it in GitHub Desktop.
Save mauleyzaola/726736312c014f55f85f1cf93d125db6 to your computer and use it in GitHub Desktop.
Cast UUID into BYTEA (and vice versa) in PostgreSQL
-- UUID to BYTEA:
SELECT DECODE(REPLACE(CAST(uuid_field AS TEXT),'-',''), 'hex') FROM table;
-- BYTEA to UUID:
SELECT CAST(ENCODE(bytea_field, 'hex') AS UUID) FROM table;
-- BONUS --
-- UUID to base64 string (for nicer urls):
SELECT ENCODE(DECODE(REPLACE(CAST(uuid_field AS TEXT),'-',''), 'hex'), 'base64') FROM table;
-- base64 to UUID:
SELECT CAST(ENCODE(DECODE(base64_field, 'base64'), 'hex') AS UUID) FROM table;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment