Which is better in below cases.
1.
IF EXISTS(SELECT * FROM Table WHERE ID = 3)
BEGIN
-------
END
Vs
2.
IF EXISTS(SELECT 1 FROM Table WHERE ID = 3)
BEGIN
-------
END
Or both are same?
Select * from any table will fetch and display all the column in that table, while Select 1 from any table will display one row with 1 without any column name.
If you are pulling all the columns then select * is not different than select with column names.. SELECT by Column names is faster because you are only pulling in the columns needed rather than every column.
Difference between Select * and Select 1: Select * means it selects all the columns in that table as well as total number of rows exist in that table. Where as Select 1 means "1" is treated as a new column with data 1 for that column and as many rows exist for that table.
The statement 'select 1' from any table name means that it returns only 1. For example, If any table has 4 records then it will return 1 four times.
EXISTS
will check if any record exists in a set. so if you are making a SELECT from 1 million records or you are making a SELECT from 1 record(let say using TOP 1), they will have same result and same performance and even same execution plan.(why?) Because exists will not waits until 1 million record scan complete(or 1 record scan complete). Whenever it finds a record in a set, it will be return the result as TRUE(There is no matter in this case you are using * or column name both will have same performance result).
USE pubs
GO
IF EXISTS(SELECT * FROM dbo.titleauthor)
PRINT 'a'
IF EXISTS(SELECT TOP 1 * FROM dbo.titleauthor)
PRINT 'b'
below is the execution plan for these queries(as I have Screen size problem, I have cropped it's image)
But this scenario and performance and even execution plan will be completly change, when you are using queries as follow(I do not know why should use this query!):
USE pubs
GO
IF EXISTS(SELECT * FROM dbo.titleauthor)
PRINT 'a'
IF EXISTS(SELECT 1 )
PRINT 'b'
in this scenario, as SQL Server does not need to perform any scan operation in second query, then the execution plan will be changed as follow:
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