HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlCritical

What's the point of WHERE 1=2 for SELECT INTO table query

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
thewhatpointintowherequeryforselecttable

Problem

If we want to create a new table from an existing one in SQL Server we can do the following

SELECT * into Table2
from Table1
WHERE 1=2


Whats the point of where clause? I tried it without the where clause and it ran fine. I've seen this where clause in many examples on internet but not the reason why it is required.

Solution

The reason you put the WHERE 1=2 clause in that SELECT INTO query is to create a field-copy of the existing table with no data.

If you did this:

select *
into Table2
from Table1


Table2 would be an exact duplicate of Table1, including the data rows. But if you don't want the data contained in Table1, and you just want the table structure, you put a WHERE clause to filter out all of the data.

BOL SELECT INTO Reference quote:


SELECT…INTO creates a new table in the default filegroup and inserts the resulting rows from the query into it.

If your WHERE clause has no resulting rows, none will be inserted into the new table: Therefore, you end up with the duplicate schema of the original table with no data (which would be the desired result in this case).

The same effect can be achieved with TOP (0), for example:

select top (0) *
into Table2
from Table1;


Note: The SELECT INTO will not duplicate the source table's indexes, constraints, triggers, or partition schema.

Code Snippets

select *
into Table2
from Table1
select top (0) *
into Table2
from Table1;

Context

StackExchange Database Administrators Q#16520, answer score: 55

Revisions (0)

No revisions yet.