Skip to content

Instantly share code, notes, and snippets.

@Pigeo
Last active September 22, 2023 07:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Pigeo/5606f9f7826c3f5f5d2a945ca9f4dcf5 to your computer and use it in GitHub Desktop.
Save Pigeo/5606f9f7826c3f5f5d2a945ca9f4dcf5 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