Advanced SQL tutorial pdf, Check if data exists, Check if record exists in table for tables - MSDN - Microsoft, check if table has records, Define below transformation in DFD?, Difference between Cached Report and Snapshot Report, Download SQL Questions, Download SQL Server Interview Question in PDF, Download SQL SERVER Interview questions, Download SQL Server Interview questions and answers, download sql server interview questions and answers pdf, download sql server interview questions by Pawan Khowal, download sql server interview questions by Pawan Kumar, download sql server interview questions by Pawan Kumar Khowal, Download T-SQL Interview Questions, Free Download SQL SERVER Interview questions, How to check if a specific record exists in a table in SQL, How to make connection with a FTP server?, How to show "No Data Found" Message to end user?, SQL, sql - Fastest way to determine if record exists, SQL Common Interview Questions, SQL Common Interview Questions and answers, SQL FAQ, SQL FAQs, SQL Interview Q & A, SQL Interview Questions, SQL Queries asked in interviews, SQL Questions, sql server - check if data exist in a table if yes do this else, SQL Server - General Interview Questions and Answers, SQL Server developer Interview questions and answers, SQL Server developer Interview questions with answers, SQL SERVER Indexes, SQL SERVER Interview questions, SQL SERVER Interview questions & Answers, SQL Server Interview questions and answers, SQL Server Interview Questions and Answers - Free PDF, sql server interview questions and answers for net developers, SQL SERVER Tips, SQL Server | Best way to check if data exists in a table ?, SQL SERVER- IF EXISTS(Select null from table) vs IF EXISTS(Select 1 from table), SQL Tips & Tricks, SQL Tips and Tricks, SQL Tricks, T-SQL Server Interview Questions
SQL Server – Never use Count(*) in If Exists() for data existence in a Table. Why?
Why? Simple because it doesn’t work.
In this post I will explain you the same. First let me just create a sample table and insert some data into it.
-- CREATE TABLE testCounts ( ID INT ) GO --
Now we have not inserted any rows means table is empty. now let me just run the code for you.
-- --Bad Method If EXISTS (SELECT COUNT(*) FROM dbo.testCounts) BEGIN PRINT 1 END ELSE BEGIN PRINT 0 END --
Now if you execute the above code you will always get 1, the number of rows doesn’t matter. Even we have 0 rows it is giving us 1. Folks always use below approach to check data existence in a table.(For details please refer – https://msbiskills.com/2015/09/16/sql-server-best-way-to-check-if-data-exists-in-a-table/)
-- If EXISTS (SELECT TOP 1 1 FROM dbo.testCounts) BEGIN PRINT 1 END --
Above query will give excellent execution plan. I hope now things are more clear. That’s all folks; I hope you’ve enjoyed the article and I’ll see you soon with more articles.
Pawan Kumar Khowal