Skip to content

Instantly share code, notes, and snippets.

@KamilLelonek
Created June 13, 2014 15:08
Show Gist options
  • Save KamilLelonek/812ae6e0bcfbb108bc6f to your computer and use it in GitHub Desktop.
Save KamilLelonek/812ae6e0bcfbb108bc6f to your computer and use it in GitHub Desktop.
Example of WITH common table expression in PostreSQL
-- DOCUMENTATION: http://www.postgresql.org/docs/9.3/static/queries-with.html
/*
WITH - defines auxilary stetments for larger query. Also called as 'Common Table Expressions' (CTE).
It can create temporary tables just for one query.
It is a basic CRUD statement atatched to another CRUD query.
*/
-- SYNTAX:
WITH [RECURSIVE] cte_name[(*arguments)] AS ( /* sql query */ ),
another_cte_name[(*arguments)] AS ( /* another sql query */ )
/*
RECURSIVE modifier allows to call CTE itself what is not possible in 'regular' SQL.
It actually behaves like iteration with passing arguments its own input.
What is worth to mention is that one CTE can use other CTE already defined before it.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment