In this comprehensive guide, we’ll dive deep into creating and using temporary tables in SQL.
Temporary tables, as the name suggests, are transient data structures that exist only for the duration of a database session or a specific transaction. They function much like regular tables but with a crucial difference: they’re automatically dropped when the session ends or when they’re no longer needed.
The syntax for creating temporary tables varies slightly depending on the database management system you’re using. We’ll cover the most common approaches across popular DBMS platforms.
In SQL Server, you have two options for creating temporary tables:
#
prefix for local temporary tables:CREATE TABLE #TempEmployees (
EmployeeID INT,
FirstName NVARCHAR(50),
LastName NVARCHAR(50),
Department NVARCHAR(50)
);
##
prefix for global temporary tables:CREATE TABLE ##GlobalTempProducts (
ProductID INT,
ProductName NVARCHAR(100),
UnitPrice DECIMAL(10, 2)
);
Local temp tables are visible only to the current session, while global temp tables are accessible across multiple sessions.
In MySQL and PostgreSQL, you use the TEMPORARY
keyword:
CREATE TEMPORARY TABLE TempOrders (
OrderID INT,
CustomerID INT,
OrderDate DATE,
TotalAmount DECIMAL(10, 2)
);
Oracle uses the GLOBAL TEMPORARY
keywords for creating temp tables:
CREATE GLOBAL TEMPORARY TABLE TempInventory (
ItemID INT,
ItemName VARCHAR2(100),
Quantity INT,
LastUpdated DATE
) ON COMMIT PRESERVE ROWS;
The ON COMMIT PRESERVE ROWS
clause ensures that data persists across transactions within the same session.
Once you’ve created a temporary table, you can populate it using various methods:
INSERT INTO #TempEmployees (EmployeeID, FirstName, LastName, Department)
VALUES (1, 'John', 'Doe', 'IT'),
(2, 'Jane', 'Smith', 'HR');
SELECT CustomerID, CompanyName, ContactName
INTO #TempCustomers
FROM Customers
WHERE Country = 'USA';
INSERT INTO TempOrders (OrderID, CustomerID, OrderDate, TotalAmount)
SELECT OrderID, CustomerID, OrderDate, SUM(UnitPrice * Quantity) AS TotalAmount
FROM Orders
JOIN OrderDetails ON Orders.OrderID = OrderDetails.OrderID
GROUP BY OrderID, CustomerID, OrderDate;
Temp Tables in SQL with a Rapid Database Builder
While understanding SQL and executing efficient queries isn’t too difficult, using temporary tables (temp tables) in SQL can require a deeper understanding, especially when working with large datasets or optimizing query performance for complex data manipulations.
This is where rapid database builders like Five come into play. Five provides a MySQL database for your application and generates an automatic UI, making it easier to interact with your data.
With Five, you can create interactive forms, tables, dynamic charts, comprehensive PDF reports, and dashboards that are automatically generated based on your database schema.
Five also enables you to write custom JavaScript and TypeScript functions, providing you with the flexibility to implement complex business logic.
Once your application is ready, Five makes deployment easy with just a few clicks, allowing you to deploy your MySQL-based application to a secure, scalable cloud infrastructure.
This lets you focus on developing, while Five handles the complexities of cloud deployment and infrastructure management.
If you’re serious about using SQL efficiently, give Five a try.
Let’s explore some real-world scenarios where temporary tables shine:
When dealing with multiple joins that slow down your queries, you can break them into smaller, more manageable parts using temp tables:
-- Step 1: Create and populate a temp table with intermediate results
CREATE TEMPORARY TABLE TempSales AS
SELECT ProductID, SUM(Quantity) AS TotalSold
FROM OrderDetails
GROUP BY ProductID;
-- Step 2: Join the temp table with other tables for the final result
SELECT p.ProductName, t.TotalSold, s.QuantityInStock
FROM Products p
JOIN TempSales t ON p.ProductID = t.ProductID
JOIN Stock s ON p.ProductID = s.ProductID
WHERE t.TotalSold > s.QuantityInStock;
In data analysis or reporting scenarios, you might need to perform multiple transformations on your data:
-- Step 1: Create a temp table with initial sales data
CREATE TEMPORARY TABLE TempMonthlySales AS
SELECT
DATE_TRUNC('month', OrderDate) AS Month,
SUM(TotalAmount) AS MonthlySales
FROM Orders
GROUP BY DATE_TRUNC('month', OrderDate);
-- Step 2: Calculate moving averages
SELECT
Month,
MonthlySales,
AVG(MonthlySales) OVER (ORDER BY Month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS MovingAverage
FROM TempMonthlySales
ORDER BY Month;
Temporary tables can significantly enhance the performance of stored procedures that process large datasets:
CREATE PROCEDURE CalculateCustomerMetrics
AS
BEGIN
-- Create a temp table to store intermediate results
CREATE TABLE #CustomerMetrics (
CustomerID INT,
TotalOrders INT,
TotalSpent DECIMAL(10, 2),
AvgOrderValue DECIMAL(10, 2)
);
-- Populate the temp table
INSERT INTO #CustomerMetrics (CustomerID, TotalOrders, TotalSpent)
SELECT CustomerID, COUNT(*) AS TotalOrders, SUM(TotalAmount) AS TotalSpent
FROM Orders
GROUP BY CustomerID;
-- Update with average order value
UPDATE #CustomerMetrics
SET AvgOrderValue = TotalSpent / TotalOrders;
-- Return final results
SELECT * FROM #CustomerMetrics ORDER BY TotalSpent DESC;
END;
To make the most of temporary tables in your SQL workflows, keep these best practices in mind:
The creation and use of temporary tables in SQL is a valuable skill that can enhance your database programming toolkit. By using temp tables effectively, you can simplify complex queries, improve performance, and write more maintainable code.