runtime
64 / 88

lesson 64 Database engineering · advanced

CTEs, CTAS & temporary tables

Choose between named queries, created tables and temporary results.

the idea

A CTE names an expression for one statement. A view persists a definition. CREATE TEMP TABLE ... AS SELECT materializes an intermediate result for the connection. SQL Server uses SELECT ... INTO #temp; that syntax is not SQLite. CTAS does not carry over source constraints.

tables in this lesson

The challenges use this data. Each column shows its type underneath; → marks a link to another table.

orders6 columns · 12 rows
idinteger · keycustomer_idintegerproduct_idintegerquantityintegerstatustextordered_attext
101112paid2025-01-01
102231paid2025-01-02
103121paid2025-01-05
104352pending2025-01-08
105445paid2025-02-01

showing 5 of 12 rows

products4 columns · 6 rows
idinteger · keynametextcategorytextpricereal
1NotebookStationery12
2Desk lampHome45
3KeyboardTech80
4Pen setStationery8
5HeadphonesTech120

showing 5 of 6 rows

example

The idea in one query. Press Run to see what it returns; running examples never affects your progress.

example.sql
CREATE TEMP TABLE customer_units AS
SELECT customer_id,SUM(quantity) AS units
FROM orders
GROUP BY customer_id;
SELECT customer_id,units
FROM customer_units
WHERE units>3;

Watch for: SQL Server CTEs do not materialize by default. SQLite can choose different CTE strategies; neither promises a universal speed-up.

build it step by step

Each step changes one thing. Run them in order and watch the result change.

  1. Compute units you will materialize. CTAS and TEMP tables store a query result. Build the customer_units shape in your head before writing CREATE TEMP TABLE.

    step-1.sql
    SELECT customer_id, SUM(quantity) AS units
    FROM orders
    GROUP BY customer_id
    ORDER BY customer_id;
  2. Materialize with CTAS. CREATE TEMP TABLE … AS SELECT stores the result for later queries in the same session.

    step-2.sql
    CREATE TEMP TABLE customer_units AS
    SELECT customer_id,SUM(quantity) AS units
    FROM orders
    GROUP BY customer_id;
    SELECT customer_id,units
    FROM customer_units
    WHERE units>3;

challenge 1

Materialize a TEMP table customer_units with customer_id and total quantity as units. Return customer_id and units for units >3.

Return customer_idunitsany row ordertable changes are checked too

challenge-1.sql
 
To master this lesson, solve both challenges without hints and pass the concept check. 3 of 3 to go.