Skip to content

Instantly share code, notes, and snippets.

@DMeechan
Last active June 10, 2020 14:07
Show Gist options
  • Save DMeechan/43a35a553f74ba81424aef3470eb73f4 to your computer and use it in GitHub Desktop.
Save DMeechan/43a35a553f74ba81424aef3470eb73f4 to your computer and use it in GitHub Desktop.
How to get unique values from list using only SQL
-- Postgres lets you create a 'constant table' that can be used in a query without actually persisting it
-- Source: https://www.postgresql.org/docs/current/queries-values.html
-- There's a couple ways we can use it:
WITH ages (id) AS (VALUES (13), (21), (32), (32), (78), (78))
SELECT DISTINCT id from ages;
SELECT DISTINCT id
FROM (VALUES (13), (21), (32), (32), (78), (78)) ages (id);
-- Or with more columns:
WITH users (id, name, age) AS (VALUES
(1, 'Adam', 13),
(2, 'Bertha', 21),
(3, 'Charlie', 32),
(4, 'Dabar', 32),
(5, 'Erin', 78),
(6, 'Flo', 78)
)
SELECT * FROM users;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment