Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better select 1 vs select * to check the existence of record?

Tags:

sql-server

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?

like image 980
Raj Avatar asked Nov 07 '14 09:11

Raj


People also ask

What is the difference between select * and select 1?

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.

Is select * faster than select column?

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.

What is the difference between select and select * in SQL?

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.

Why do we use select 1?

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.


1 Answers

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) enter image description hereenter image description here

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: enter image description hereenter image description here

like image 137
Vahid Farahmandian Avatar answered Oct 13 '22 13:10

Vahid Farahmandian