Skip to content

Instantly share code, notes, and snippets.

@Pigeo
Last active November 1, 2024 09:23
Show Gist options
  • 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