The Wayback Machine - https://web.archive.org/web/20241009153040/https://www.geeksforgeeks.org/what-is-temporary-table-in-sql/
Open In App

What is Temporary Table in SQL?

Last Updated : 03 Sep, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Temporary Tables are most likely as Permanent Tables. Temporary Tables are Created in TempDB and are automatically deleted as soon as the last connection is terminated. Temporary Tables helps us to store and process intermediate results. Temporary tables are very useful when we need to store temporary data. The Syntax to create a Temporary Table is given below:

To Create Temporary Table:

CREATE TABLE #EmpDetails (id INT, name VARCHAR(25))  

To Insert Values Into Temporary Table:

INSERT INTO #EmpDetails VALUES (01, 'Lalit'), (02, 'Atharva') 

To Select Values from Temporary Table:

SELECT * FROM #EmpDetails 

Result:

id name
1 Lalit
2 Atharva

There are 2 types of Temporary Tables: Local Temporary Table, and Global Temporary Table. These are explained as following below.

  1. Local Temporary Table:
    A Local Temp Table is available only for the session that has created it. It is automatically dropped (deleted) when the connection that has created it, is closed. To create Local Temporary Table Single “#” is used as the prefix of a table name.

    Also, the user can drop this temporary table by using the “DROP TABLE #EmpDetails” query. There will be Random Numbers are appended to the Name of Table Name. If the Temporary Table is created inside the stored procedure, it get dropped automatically upon the completion of stored procedure execution.

    Example:

    CREATE PROCEDURE ProcTemp 
    AS
    BEGIN
    CREATE TABLE #EmpDetails
    INSERT INTO #EmpDetails VALUES ( 01, 'Lalit'), ( 02, 'Atharva')
    SELECT * FROM #EmpDetails
    END
    EXECUTE ProcTemp 
  2. Global Temporary Table:
    To create a Global Temporary Table, add the “##” symbol before the table name.

    Example:

    CREATE TABLE ##EmpDetails (id INT, name VARCHAR(25)) 

    Global Temporary Tables are visible to all connections and Dropped when the last connection referencing the table is closed. Global Table Name must have an Unique Table Name. There will be no random Numbers suffixed at the end of the Table Name.


Previous Article
Next Article

Similar Reads

SQL | Declare Local Temporary Table
In SQL, local temporary tables are designed to store intermediate results or data that is needed only for a short period during a session or procedure. They are an essential feature for managing temporary data within the scope of a particular database operation. In this article, We will learn about Declare Local Temporary Table in SQL in detail by
4 min read
Select into and temporary tables in MS SQL Server
In SQL Server, the SELECT INTO TEMP TABLE statement is used to select data from one or more source tables and insert it into a temporary table. Temporary tables are extremely useful when dealing with intermediate results, or when working with subsets of data within a session without modifying or affecting the original tables. In this article, We wi
4 min read
How to Select All Records from One Table That Do Not Exist in Another Table in SQL?
We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries. In this let us see How to select All Records from One Table That Do Not Exist in Another Table step-by-step. Creating a Database Use the below command to create a database named Geeks
2 min read
SQL Query to Filter a Table using Another Table
In this article, we will see, how to filter a table using another table. We can perform the function by using a subquery in place of the condition in WHERE Clause. A query inside another query is called subquery. It can also be called a nested query. One SQL code can have one or more than one nested query. Syntax: SELECT * FROM table_name WHERE col
2 min read
Difference between Structured Query Language (SQL) and Transact-SQL (T-SQL)
Structured Query Language (SQL): Structured Query Language (SQL) has a specific design motive for defining, accessing and changement of data. It is considered as non-procedural, In that case the important elements and its results are first specified without taking care of the how they are computed. It is implemented over the database which is drive
2 min read
Configure SQL Jobs in SQL Server using T-SQL
In this article, we will learn how to configure SQL jobs in SQL Server using T-SQL. Also, we will discuss the parameters of SQL jobs in SQL Server using T-SQL in detail. Let's discuss it one by one. Introduction :SQL Server Agent is a component used for database task automation. For Example, If we need to perform index maintenance on Production ser
7 min read
SQL vs NO SQL vs NEW SQL
SQL stands for Structured Query Language. Which is based on relational algebra and schema is fixed in this which means data is stored in the form of columns and tables. SQL follows ACID properties which means Atomicity, Consistency, Isolation, and Durability are maintained. There are three types of languages present in SQL : Data Definition Languag
2 min read
Removing Duplicate Rows (Based on Values from Multiple Columns) From SQL Table
In SQL, some rows contain duplicate entries in multiple columns(>1). For deleting such rows, we need to use the DELETE keyword along with self-joining the table with itself. The same is illustrated below. For this article, we will be using the Microsoft SQL Server as our database. Step 1: Create a Database. For this use the below command to crea
3 min read
SQL | Checking Existing Constraints on a Table using Data Dictionaries
Prerequisite: SQL-Constraints In SQL Server the data dictionary is a set of database tables used to store information about a database's definition. One can use these data dictionaries to check the constraints on an already existing table and to change them(if possible). USER_CONSTRAINTS Data Dictionary: This data dictionary contains information ab
2 min read
SQL Query to Display Last 5 Records from Employee Table
Summary : Here we will be learning how to retrieve last 5 rows from a database table with the help of SQL queries. The Different Approaches we are going to explore are : With the help of LIMIT clause in descending order.With the help of Relational operator and COUNT function.With the help of Prepared Statement and LIMIT clause. Creating Database :
4 min read
SQL | Query to select NAME from table using different options
Let us consider the following table named "Geeks" : G_ID FIRSTNAME LASTNAME DEPARTMENT 1 Mohan Arora DBA 2 Nisha Verma Admin 3 Vishal Gupta DBA 4 Amita Singh Writer 5 Vishal Diwan Admin 6 Vinod Diwan Review 7 Sheetal Kumar Review 8 Geeta Chauhan Admin 9 Mona Mishra Writer SQL query to write “FIRSTNAME” from Geeks table using the alias name as NAME.
2 min read
Table operations in MS SQL Server
In a relational database, the data is stored in the form of tables and each table is referred to as a relation. A table can store a maximum of 1000 rows. Tables are a preferred choice as: Tables are arranged in an organized manner. We can segregate the data according to our preferences in the form of rows and columns.Data retrieval and manipulation
2 min read
How to find first value from any table in SQL Server
We could use FIRST_VALUE() in SQL Server to find the first value from any table. FIRST_VALUE() function used in SQL server is a type of window function that results in the first value in an ordered partition of the given data set. Syntax : SELECT *, FROM tablename; FIRST_VALUE ( scalar_value ) OVER ( [PARTITION BY partition_value ] ORDER BY sort_va
2 min read
How to find last value from any table in SQL Server
We could use LAST_VALUE() in SQL Server to find the last value from any table. LAST_VALUE() function used in SQL server is a type of window function that results the last value in an ordered partition of the given data set. Syntax : SELECT *, FROM tablename LAST_VALUE ( scalar_value ) OVER ( [PARTITION BY partition_expression ] ORDER BY sort_expres
2 min read
Extract domain of Email from table in SQL Server
Introduction : As a DBA, you might come across a request where you need to extract the domain of the email address, the email address that is stored in the database table. In case you want to count the most used domain names from email addresses in any given table, you can count the number of extracted domains from Email in SQL Server as shown belo
3 min read
Capturing INSERT Timestamp in Table SQL Server
While inserting data in tables, sometimes we need to capture insert timestamp in the table. There is a very simple way that we could use to capture the timestamp of the inserted rows in the table. Capture the timestamp of the inserted rows in the table with DEFAULT constraint in SQL Server. Use DEFAULT constraint while creating the table: Syntax: C
2 min read
SQL Query to Display Last 50% Records from Employee Table
Here, we are going to see how to display the last 50% of records from an Employee Table in MySQL and MS SQL server's databases. For the purpose of demonstration, we will be creating an Employee table in a database called "geeks". Creating a Database : Use the below SQL statement to create a database called geeks: CREATE DATABASE geeks;Using Databas
2 min read
SQL Query to Display First 50% Records from Employee Table
Here, we are going to see how to display the first 50% of records from an Employee Table in MS SQL server's databases. For the purpose of the demonstration, we will be creating an Employee table in a database called "geeks". Creating a Database : Use the below SQL statement to create a database called geeks: CREATE DATABASE geeks;Using Database :US
2 min read
SQL Query to Find Shortest & Longest String From a Column of a Table
Here, we are going to see how to find the shortest and longest string from a column of a table in a database with the help of SQL queries. We will first create a database "geeks", then we create a table "friends" with "firstName", "lastName", "age" columns. Then will perform our SQL query on this table to retrieve the shortest and longest string in
3 min read
SQL Query to Display Nth Record from Employee Table
Here. we are going to see how to retrieve and display Nth records from a Microsoft SQL Server's database table using an SQL query. We will first create a database called "geeks" and then create "Employee" table in this database and will execute our query on that table. Creating a Database : Use the below SQL statement to create a database called ge
2 min read
How to Compare Rows and Columns in the Same Table in SQL
In this article, we are going to see how we can compare the rows and columns of the same table in SQL. We will be taking a few examples to see how we can do this in different ways. To create the database: Syntax : CREATE database_name;CREATE Shopping To use this database: Syntax : USE database_name;USE Shopping Creating Table for making queries: Sy
2 min read
SQL Query to Select all Records From Employee Table Where Name is Not Specified
Here, we are going to see how to find the names of the persons other than a person with a particular name SQL. In this article, we will be making use of the MSSQL Server as our database. For example, if the employee name is Pradeep you need to show the table of employees excluding that employee with the name Pradeep. So let us execute this query in
2 min read
SQL- Lock Table
SQL Server is a versatile database and it is the most used Relational Database that is used across many software industries. In this article, let us see about the SQL Lock table in SQL Server by taking some practical examples. As it is meeting Atomicity(A), Consistency(C), Isolation(I), and Durability(D) requirements it is called a relational datab
6 min read
SQL Query to Find the Number of Columns in a Table
SQL stands for a structure query language, which is used in the database to retrieve data, update and modify data in relational databases like MySql, Oracle, etc. And a query is a question or request for data from the database, that is if we ask someone any question then the question is the query. Similarly when we want any data from the database t
4 min read
How to Check if a Column Exists in a SQL Server Table?
In this article, we will look at how to check if a particular column exists in a database table or not. For checking the existence of a column we need to create the table first. So, let us create a table with some columns and data. Creating table: Syntax: CREATE TABLE table_name ( column1 datatype, column2 datatype, column3 datatype, ....);Using th
2 min read
SQL Query to Create Table With a Primary Key
A primary key uniquely identifies each row table. It must contain unique and non-NULL values. A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called composite keys. To create a Primary key in the table, we have to use a keyword; "PRIMARY KEY ( )" Query:
2 min read
How to Append Two Tables and Put the Result in a Table in SQL?
Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, SQL Server, PostGre, etc. In this article, we will learn how to append two tables and store the result into a new table using UNION, UNION ALL. UNION: Syntax: SELECT column_one, column
2 min read
SQL Query to Get the Latest Record from the Table
Getting the latest record from the table is a simple task, you do not have a need to get advanced knowledge of SQL. In this article, we will discuss the simplest and easier methods to get the latest record from the Table. You might want to get the latest record from the table with all the columns or you might want only a specific number of columns.
3 min read
How to Create a Table With Multiple Foreign Keys in SQL?
When a non-prime attribute column in one table references the primary key and has the same column as the column of the table which is prime attribute is called a foreign key. It lays the relation between the two tables which majorly helps in the normalization of the tables. A table can have multiple foreign keys based on the requirement. In this ar
2 min read
How to Remove the First Characters of a Specific Column in a Table in SQL?
Here we will see, how to remove the first characters of a specific column in a table in SQL. We can do this task using the String function. String functions are used to perform an operation on an input string and return an output string. There are various string functions like LEN(for SQL server), SUBSTR, LTRIM, TRIM, etc. To perform the required f
3 min read
Article Tags :