50

I need to save select query output into temporary table. Then I need to make another select query against this temporary table. Does anybody know how to do it?

I need to make this on SQL Server.

3 Answers 3

65
select *
into #TempTable
from SomeTale

select *
from #TempTable
6
  • 10
    The # in front of #TempTable indicates it's a temp table. Dec 8, 2010 at 19:31
  • 2
    When this table would be dismissed?
    – Johnny_D
    Aug 22, 2013 at 13:58
  • 11
    #TempTable lasts within the session that creates it. Once the session is closed, it's gone. Also it can only be accessed within the same session. No other sessions can see and access it. There is another type of temp table ##TempTable (notice ##) which has a global scope. It can be seen and accessed from other sessions, therefore ##TempTable is unique (no one can create another with the same name). Server restarts, ##TempTable is gone. Aug 23, 2013 at 18:03
  • 2
    Each session can create its own #TempTable without running into name clashing. Aug 23, 2013 at 18:18
  • like this but better I think is sql select * into temp temptable from sometable; select * from temptable;
    – Raj
    Jan 12, 2017 at 22:05
45

You can also do the following:

CREATE TABLE #TEMPTABLE
(
    Column1 type1,
    Column2 type2,
    Column3 type3
)

INSERT INTO #TEMPTABLE
SELECT ...

SELECT *
FROM #TEMPTABLE ...

DROP TABLE #TEMPTABLE
3
  • 3
    Can you please clarify, is this temporary table really located on HDD, or it's just a runtime projection? And what would happen if I don't delete this temporary table?
    – Johnny_D
    Aug 23, 2013 at 5:38
  • 4
    The table is in a temp database and is only visible to the connection that created it. Once that connection is gone or the stored procedure finishes, the temp table goes away. Oct 18, 2013 at 20:22
  • You don't even need to mention CREATE TABLE command, all you can do is run simple SELECT query and at end type INTO #TempTable and whatever fields you've selected goes into #TempTable creating columns and types automatically
    – rac3b3nn0n
    Oct 17, 2022 at 20:48
2

In Sqlite:

CREATE TABLE T AS
SELECT * FROM ...;
-- Use temporary table `T`
DROP TABLE T;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.