Last active
June 10, 2020 14:07
-
-
Save DMeechan/43a35a553f74ba81424aef3470eb73f4 to your computer and use it in GitHub Desktop.
How to get unique values from list using only SQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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