Created
January 13, 2015 17:56
-
-
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.
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
| 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