Skip to content

Instantly share code, notes, and snippets.

@JohnArchieMckown
Created January 13, 2015 17:56
Show Gist options
  • Save JohnArchieMckown/a0329631f3f860ffddd9 to your computer and use it in GitHub Desktop.
Save JohnArchieMckown/a0329631f3f860ffddd9 to your computer and use it in GitHub Desktop.
An example of a CTE in SQL which will either SELECT a column from a table, or insert a new column into that table.
WITH sel AS (
SELECT id FROM hometowns WHERE name = 'Portland'
),
ins AS (
INSERT INTO hometowns(name)
SELECT 'Portland'
WHERE NOT EXISTS (SELECT 1 FROM sel)
RETURNING id
)
INSERT INTO users(name, hometown_id)
VALUES ('Robert', SELECT id FROM ins UNION ALL SELECT id FROM sel);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment