Numbers in SELECT statements
I encountered sql queries like 'SELECT 1 FROM TABLE_NAME'
or 'SELECT 2 FROM TABLE_NAME'
while debugging a program. I am curious as to what the numbers in t开发者_C百科he queries do and what result set does it return.
Thanks
It will return a single column with the number as value, with n rows, n being the number of rows returned from the select.
This is usefull in cases such as
SELECT *
FROM YourTable yt
WHERE EXISTS(
SELECT 1
FROM SomeOtherTable sot
WHERE yt.ID = sot.ID
)
Also, good article at SELECT 1 vs SELECT * – An Interesting Observation
Select 1 from your_table --> On execution , you get the value 1 for every row in your_table.
'Select *' and 'Select 1 or 2' have the same performance when executing without an EXIST condition. My personal choice is using 'Select 1 or 2' when there are conditions to check for existing rows as it is slightly faster, for eg. when querying with VIEWS or temp tables having millions of rows and lot many columns.
精彩评论