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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Database Programming.
Lesson complete
Earn the 3 college credits for Database Programming
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Altering Table Structures with SQL Commands →← 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 →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every credit course with PRO →
Why take it here
Why students take Database Programming with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
What is the difference between #temp and ##temp tables in SQL Server?
What is the difference between a temporary table and a table variable in SQL Server?
Should you use a temporary table or a CTE?
About the Database Programming course
How many college credits is Database Programming?
How much does Database Programming cost and what is included?
Which universities accept UPI Study credits?
How long does Database Programming take?
How are the exams done?
How do my credits reach my college?
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
3 credits · NCCRSEnroll →