Tier 3 · Intermediate

Temp Tables and CREATE TABLE AS SELECT in SQL

By Owen Middleton · Updated September 2026 · Examples run on PostgreSQL 17

What is CREATE TABLE AS in SQL?

CREATE TEMP TABLE ... AS SELECT runs a query and stores the result as a table you can reference repeatedly in the same session.

A CTE names a subquery within a single statement. The moment that statement finishes, the result is gone. A temp table is different: the result persists for the rest of your session, and you can query it as many times as you like with separate SELECT statements — without re-running the original computation each time.

How do you create a temp table from a query?

You're building a multi-step analysis. Step one is an expensive aggregation across a large orders table. Steps two and three both need that aggregated data. With a CTE, you'd have to include the aggregation inside every query that needs it. With a temp table, you run it once and store the result:

CREATE TEMP TABLE monthly_revenue AS
SELECT
  DATE_TRUNC('month', ordered_at) AS month,
  status,
  SUM(total_amount) AS revenue
FROM orders
GROUP BY 1, 2;

Now monthly_revenue is a real table in your session. Query it as many times as you need:

SELECT status, AVG(revenue) FROM monthly_revenue GROUP BY status;
SELECT month,  SUM(revenue) FROM monthly_revenue GROUP BY month;

The aggregation ran once. Both queries read from the stored result.

How long does a temp table last in PostgreSQL?

When your session ends, PostgreSQL drops the temp table automatically. You don't need to clean it up. And the table is invisible to other sessions — even if two analysts create a temp table with the same name, each gets a private copy in their own session. There is no naming conflict.

You can also add indexes to a temp table after creating it, which a CTE cannot have. For large intermediate results that get queried repeatedly with WHERE filters, an index can meaningfully speed up the downstream queries.

Should you use a temp table or a CTE?

When should you use a CTE instead? When the intermediate result is only needed once, inside a single query. When you need it across multiple queries or statements in the same session, a temp table is the right tool.

What happens to a temp table when a transaction rolls back?

The one thing that trips people up: a temp table created inside a transaction is dropped if the transaction rolls back.

If your session runs BEGIN, creates a temp table, then hits an error that triggers a ROLLBACK, the temp table disappears along with everything else in that transaction. If you're building a multi-step pipeline with temp tables, be aware of your transaction boundaries.

Check your understanding

You create a temp table in one session. Can a second concurrent session query that same temp table?

Practice CREATE TABLE AS in SQL

Practice · easy ecommerce · Brightlane

Brightlane's reporting pipeline materializes an order-status summary into a temp table to avoid rerunning the aggregation for every downstream report. The query that populates the temp table needs to return the order count and combined order amount for each status value.

Write a query to return the status, order count, and total amount for each status value.

Assumptions:

  • The orders table has one row per order with a status and a total_amount.
  • Each unique status value should appear once in the result.
  • For each status, the order count is the number of orders carrying that status. The total amount is the combined total_amount across those orders.

Output:

  • One row per status, with columns status, order_count, and status_total.
Schema · ecommerce5 tables? = nullable
categories
idinteger
nametext
parent_id?integer
products
idinteger
nametext
category_id?integer
pricenumeric
stock_qtyinteger
attributes?jsonb
order_items
idinteger
order_id?integer
product_id?integer
quantityinteger
unit_pricenumeric
customers
idinteger
nametext
emailtext
city?text
countrytext
created_attimestamptz
is_activeboolean
orders
idinteger
customer_id?integer
ordered_attimestamptz
statustext
total_amountnumeric

Run previews · Check grades

Write a query, then run it to see results here.

Worked solution

The full breakdown walks through the shape, each clause, why this approach beats the alternatives, and the trap to avoid.

See the full worked solution

9 CREATE TABLE AS practice problems

Start learning to practice all 9 CREATE TABLE AS problems, with instant grading and mastery tracking.

Common questions about CREATE TABLE AS

Do you have to drop a temp table when you finish?

No. PostgreSQL removes it when the session ends, so cleanup is automatic. Dropping it yourself is still useful mid-session when you want to rebuild it with a different shape, because creating over an existing name fails.

Can you index a temp table?

Yes, which is one of the things a CTE cannot offer. When a large intermediate result is queried repeatedly with the same filter, an index on that column can make the difference between a quick answer and a slow one.

Is a temp table visible to the rest of the session?

Yes, to every later statement until the session ends, which is exactly what separates it from a CTE. The result is computed once and read as many times as you like, instead of being rebuilt inside each query that needs it.

How you actually get good at SQL

Reading explains SQL. Writing it, over and over with instant feedback, is what makes you fluent.

That's the whole SQLMaxx loop: 600+ real problems, instant AI feedback, mastery you can actually see, and spaced review that won't let you forget.

A stack of SQL practice problem cards, the top card showing an employees table.
615 problems · 66 concepts

Real problems. Not toy examples.

615 hand-built problems spanning all 66 concepts, from basic SELECTs to window functions, built on real schemas and real business questions, the kind you'll actually get asked on the job. Enough reps to make SQL automatic.

A retro computer showing a SQL query marked correct with a green checkmark.
Instant AI feedback

Write a query. Know if it's right in one second.

No copying an answer and hoping it clicked. The AI grader checks your real query against real data, catches exactly what's wrong, and explains the fix in plain English, like a senior analyst reading over your shoulder on every problem.

A circular mastery progress dial filling from blue to green, the SQLMaxx diamond at its center.
Mastery tracking

Stop guessing whether you actually know it.

SQLMaxx tracks every concept and shows you what you've mastered and what's still shaky. Your skills fill in one concept at a time, so 'I think I get joins' becomes something you can prove.

A SQL query editor circled by a blue return arrow with a clock, scheduled to come back for review.
Spaced review

Learn it once. Keep it for good.

Most of what you learn this week fades by next week. So when a concept comes due for review, SQLMaxx hands you a fresh problem to solve from a blank editor, not a flashcard to re-read. A research-backed spaced-repetition algorithm (FSRS) times each return for right before you'd forget, so your SQL is still there months later, when the interview or the job actually needs it.