Temporary table in SQL

 1.What is temporary table in SQL and What is difference between Temp table and view ?

           A temporary table is a base table that is not stored in the database, but instead exists only while the database session in which it was created is active. It would automatically deleted when the last connection to the query window that created the table is terminated. We can use Temporary Tables to store and process intermediate results.

 

View

Temporary table

A view exists only for a single query. Each time you use the name of a view, its table is recreated from existing data.

A temporary table exists for the entire database session in which it was created

A view is automatically populated with the data retrieved by the query that defines it

You must add data to a temporary table with SQL INSERT commands

Only views that meet the criteria for view updatability can be used for data modifications.

 

Because the contents of a view are generated each time the view’s name is used, a view’s data are always current.

The data in a temporary table reflect the state of the database at the time the table was loaded with data. If the data from which the temporary table was loaded are modified after the temporary table has received its data, then the contents of the temporary table may be out of sync with other parts of the database.

If you are going to use data only once during a database session, then a view will perform better than a temporary table because you don’t need to create a structure for it. However, if you are going to be using the data repeatedly during a session, then a temporary table provides better performance because it needs to be created only once. Using a view repeatedly takes more time, but provides continuously updated data; using a temporary table repeatedly saves time, but  table’s data may be out of date.


SQL Server uses the TempDB database for working storage of temporary tables and temporary stored procedures. Temporary stored procedures and tables can be created by users, applications, or the system to support query requests.

Comments