Many times I have seen the issue of SELECT 1 vs SELECT * discussed in terms of performance or readability while checking for the existence of rows in the table. I ran quick 4 tests about this observed that I am getting same result when used SELECT 1 and SELECT *. I think smart readers of this blog will come up the situation when SELECT 1 and SELECT * have a different execution plan when used to find the existence of rows.
Let us see 4 tests I ran and note their result is same and their Execution Plan take the same amount of resources (50% and 50%)
You can click on the images to see larger images.
Test 1: Whole Table SELECT
USE AdventureWorks GO IF EXISTS( SELECT 1 FROM Production.Product) SELECT 'SELECT 1' GO IF EXISTS( SELECT * FROM Production.Product) SELECT 'SELECT *' GO
Test 2: Condition WHERE on Indexed Column
USE AdventureWorks GO IF EXISTS( SELECT 1 FROM Production.Product WHERE Name = 'Adjustable Race') SELECT 'SELECT 1' GO IF EXISTS( SELECT * FROM Production.Product WHERE Name = 'Adjustable Race') SELECT 'SELECT *' GO
Test 3: Using Aggregate function COUNT
USE AdventureWorks GO IF ( SELECT 1 FROM Production.Product WHERE Name = 'Adjustable Race') = 1 SELECT 'SELECT 1' GO IF ( SELECT COUNT(*) FROM Production.Product WHERE Name = 'Adjustable Race') = 1 SELECT 'SELECT *' GO
Test 4: Using COUNT with search on non-indexed Column
USE AdventureWorks GO IF ( SELECT COUNT(1) FROM Production.Product WHERE SafetyStockLevel = '800') > 1 SELECT 'SELECT 1' GO IF ( SELECT COUNT(*) FROM Production.Product WHERE SafetyStockLevel = '800') > 1 SELECT 'SELECT *' GO
Note: I have used single quotes around 800, which is numeric and I am aware of that fact. Above queries are for testing purpose only.
I have been using SELECT 1 instead of SELECT * when checking existence of rows. I would like to see what my readers have an opinion about this. Please have your opinion and make your comment here.
Reference: Pinal Dave (https://blog.sqlauthority.com)