Building and Using Temporary Tables in SQL, Explained

UPI Study › Courses › Database Programming › Free lessons › Lesson 9.10 Free with a free account

Building and Using Temporary Tables in SQL

Database Programming · Chapter 9: Subqueries, Views, and IndexesSection 9.10 · lesson 58 of 7610 min · free with a free account

← Working with Schema Objects in PracticeNext lesson: Altering Table Structures with SQL Commands →

A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

In this lesson

Stage intermediate results in session-scoped tables and reuse them safely.

  • Create and query a temporary table within a single database connection
  • Explain the scope and lifetime of temporary tables in SQLite, MySQL and SQL Server
  • Compare SQL Server local temporary tables, global temporary tables and table variables
  • Choose between a temporary table and a CTE for staged work

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,268 words). Read along, or search it.

Opening Problem

Two Reports From One Saved Result

Sofia Alvarez, Lantern Books' sales associate, needs two customer reports from the same order totals. Leo Park, the developer, wants to avoid repeating a complex join. Can they save the intermediate result, inspect it, and reuse it without turning it into a permanent business table? A temporary table gives that work a defined scope and lifetime. The connection matters as much as the name.

Sample Database

Shop Data for Scratch Work

Our examples use Lantern Books, a fictional campus bookstore. This disposable database starts with the shared course data. Customers and products hold people and inventory. Prices and quantities are illustrative, and each lesson resets its own copy. Orders link to customers, while order items link orders to products. Foreign key checks are enabled for this connection. Save the setup file, then run it against a fresh shop database. Successful creation prints no rows here. Later commands reopen that database file. These examples use the real SQLite shell, and server dialect differences will be labeled.

Temporary Table

Create, Fill and Read in One Connection

A temporary table is a real table for intermediate work. SQLite uses temp or temporary, and this example defines columns and a primary key explicitly. Create, insert, and select run in the same shell connection. The table can also support updates, deletes, and indexes during that connection. Scope means where a name can be used; lifetime means how long the object exists. A temporary name is not automatically available to another connection. Run the complete file in one shell invocation. Its final select reads the rows before that connection exits. Both scratch totals appear. They are illustrative values from our canonical orders, and the scratch object disappears when this SQLite connection closes.

Connection Scope

A New Connection Sees No Scratch Table

This command opens a fresh SQLite connection to the same shop file. The permanent database remains, but the previous connection's temporary schema does not come along. A connection pool or tool that reconnects between steps can create the same surprise. Keep all dependent temporary-table work in the connection that owns it. MySQL temporary tables also belong to one session. Reusing the same name in separate sessions does not make the temporary rows shared. Run this catalog inspection in the new connection. Counting the object avoids relying on an invented missing-table diagnostic. Zero scratch objects are visible. The absence follows connection lifetime, rather than a deletion of our permanent orders.

Server Forms

MySQL TEMPORARY, Hash Tables and Table Variables

MySQL create temporary table can copy a table's structure with like, without copying its rows. It requires the create temporary tables privilege. A temporary name can hide a permanent MySQL table with the same name. Use a clear scratch prefix, and remember temporary creation avoids an implicit commit without becoming rollback-undoable DDL. SQL Server stores temporary objects in tempdb. One hash marks a local temporary table; two hashes mark a global table visible to other sessions. A table variable starts with at and is local to its declaring batch, procedure, or function. These are non-run server listings, not SQLite syntax. A local table created inside a procedure ends with that procedure, while nested procedures can use it. Global lifetime also depends on creator termination and active references.

Table Variables

Rollback, Statistics and Batch Lifetime

A SQL Server local temporary table can outlast a batch separator while its session remains open. A table variable ends with its batch; go separates client-submitted batches. Rollback undoes transactional row changes in a hash temporary table. Changes to a table variable are not undone in the same way, so swapping the structures can change correctness. Table variables lack column statistics, and cannot be altered after declaration. Modern deferred compilation improves estimates, and supported inline indexes mean constraints are not their only index option. Temporary tables provide fuller statistics and indexing for demanding staged work. There is no universal row-count cutoff; measure the actual workload and compatibility level. SQL Server temporary tables do not enforce foreign keys. Treat validation and ownership deliberately, instead of assuming the temporary label supplies every permanent-table guarantee.

Staging

Saving One Total per Customer

Staging saves a step's result for later statements. This single-connection script joins orders, lines, and products, then groups one spending total per ordering customer. These totals use the current catalog prices, which are illustrative. Historical accounting would need the prices actually charged on each order line. Create table as select copies result values, not the source tables' general indexes and constraints. Define required rules separately when they matter. Run the whole script once, and follow its outputs in stages. All temporary-table uses happen before this connection ends. Five ordering customers are staged. Dara has no orders, so this intermediate result has no row for her.

Reusing the Stage

Spending Tiers Without Repeating the Join

The tier report left joins all customers to the staged totals. Coalesce displays zero for Dara, and case assigns a None tier when no staged row exists. Asha and Chen meet our illustrative high-spending boundary. Ben, Elena, and Farid are regular, while Dara remains in the report despite having no orders. The expensive join was saved as data. This report reads that saved result, rather than repeating the three-table join.

Second Reuse

Customers Above the Staged Average

The final query reuses the same staged totals to find customers above the ordering customers' average. SQLite allows the temporary table both outside and inside this subquery. The average is 34.6. Asha's 69.5 and Chen's 38 qualify; the other staged totals fall below that average. MySQL cannot reopen the same temporary table twice in one query. There, save the average to a session variable first, or restructure the calculation with a CTE.

Creation Recipes

SELECT INTO, CREATE AS and CTEs

MySQL can create and fill a temporary table as select. SQL Server commonly uses select into a hash name, as these non-run alternatives show. Both can define columns first, then use insert into followed by select. A table variable must be declared first, and cannot be a select-into target. A CTE lasts for one statement, while staged rows can serve several later statements. The staged rows are a snapshot; source changes do not automatically refresh them. MySQL 8 and later supports CTEs, which can be referenced more than once. A named expression does not promise that its calculation is physically cached. Prefer a CTE for readable single-statement work. Consider a temporary table for repeated statements, intermediate inspection, or explicit indexing of the saved result.

Quick Check

A Copied Price After a Base Change

A fresh script copies Pen Set's price into a temporary table, then changes the base price. The final query reads the temporary copy in the same connection. Which price appears: ninety-nine, six, or an error? Pause, and predict. Six appears. Creating the temporary table copied the earlier value, and changing products does not refresh that saved row. Run the script, and the saved price remains six. The connection stays open through the final query, so the temporary table is still available. Ninety-nine would describe the changed base row. A missing-table error would require losing the connection, or removing the temporary object before reading it.

Rollback Check

One Row Survives the Rollback

Another SQLite connection creates a temporary table and inserts a row, before starting an explicit transaction. It adds another row, then rolls back. How many rows remain: zero, two, or one? Pause, and predict. One row remains. The earlier insert completed before the transaction, while the later insert belongs to the rolled-back transaction. The run confirms one. SQLite's temporary row changes are transactional here, so temporary does not mean immune to rollback. Zero would undo the earlier completed statement too. Two would keep the transactional insert, confusing this behavior with SQL Server table-variable behavior.

Key Takeaways

Scope, Lifetime and Snapshot Behavior

Sofia's reports can share one saved intermediate result. Build it, inspect it, and reuse it while its owning connection remains open. Choose a temporary table, table variable, or CTE by scope, lifetime, transactional behavior, and optimizer needs. Remember that staged rows are a snapshot. A new connection does not inherit local temporary objects, even when it opens the same permanent database.

About Database Programming at UPI Study

Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Building and Using Temporary Tables in SQL

What is a temporary table in SQL?
A temporary table is a real table for intermediate work that belongs to one connection or session and is removed automatically when that session ends, if not sooner. CREATE TEMPORARY TABLE in MySQL, CREATE TEMP TABLE in SQLite and CREATE TABLE #stage in SQL Server create one. It supports inserts, updates, deletes and indexes, but a local temporary table is invisible to other connections.
What is the difference between #temp and ##temp tables in SQL Server?
A single hash, as in #stage, creates a local temporary table visible only to the session that created it, while two hashes, as in ##stage, create a global temporary table that other sessions can use. Both live in tempdb. A local table created inside a stored procedure is dropped when that procedure ends, though procedures it calls can use it. A global table lasts until its creator disconnects and other references end.
What is the difference between a temporary table and a table variable in SQL Server?
A table variable, declared with DECLARE @t TABLE, lasts only for its batch, procedure or function, while a #temp table can outlast a GO separator within its session. Rolling back a transaction undoes row changes in a #temp table but not in a table variable. Table variables also lack column statistics and cannot be altered after declaration, so #temp tables often suit larger staged work.
Should you use a temporary table or a CTE?
Use a CTE for readable work inside one statement, and a temporary table when several later statements need the same intermediate rows or you want to inspect or index them. A CTE lasts for one statement and is not guaranteed to be cached. A temporary table holds a snapshot, so later changes to the source tables do not refresh it. MySQL also cannot refer to one temporary table twice in the same query.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Database Programming.

76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Database Programming
3 credits · NCCRS
Enroll →