The PostgreSQL documentation on WITH shows the following example:
WITH regional_sales AS (
SELECT region, SUM(amount) AS total_sales
FROM orders
GROUP BY region
), top_regions AS (
SELECT region
FROM regional_sales
WHERE total_sales > (SELECT SUM(total_sales)/10 FROM regional_sales)
)
SELECT region,
product,
SUM(quantity) AS product_units,
SUM(amount) AS product_sales
FROM orders
WHERE region IN (SELECT region FROM top_regions)
GROUP BY region, product;
It also notes:
A useful property of WITH queries is that they are evaluated only once per execution of the parent query, even if they are referred to more than once by the parent query or sibling WITH queries.
I see that WITH
can be used for other things, like recursive evaluation. But in the example above, is there any important difference between using WITH
and creating temporary tables?
SELECT
inWITH
is just typing the name and rerunning. While with temporary table it would takeDROP
andCREATE
. On the other hand if you build a query and you going to reuse static data lots of times - building temporary table with indexes is definitely beneficial against CTE.TEMPORARY TABLE
withON COMMIT DROP
within a query, it's also just a matter of modifying the query and re-running, right? postgresql.org/docs/9.6/static/sql-createtable.html