We just came across this in an old production stored proc (there is a lot more going on in here, but this is in one leg of its logic). Why would someone ever select top 0 rows from a table? Is this some sort of SQL hack or trick I am not familiar with?
It will return the top number of rows in the result set based on top_value. For example, TOP(10) would return the top 10 rows from the full result set. Optional.
SELECT 0 FROM table does not return any column values of the table but rather a constant for every row of table - e.g. if you have the following table TABLE id | name | age 0 | John | 12 1 | Jack | 22 2 | Martin | 42.
Its a way of getting an empty set; for example to create a new empty table with the same columns as an existing one;
SELECT TOP 0 * INTO new_table FROM old_table
Or to act a as source for column names
Or as a way to return column details but no data to a client layer
Or as a query to check connectivity
Its the same as;
SELECT * FROM table WHERE 0=1
To name columns in a UNION ALL
Be sure to read Alex K.'s answer as well. He has a lot of reasons that I have used as well. This was just the most obvious one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With