This article is half-done without your Comment! *** Please share your thoughts via Comment ***
In this post, I am sharing an interesting SQL Server Interview Question which may ask in the interview of SQL Server Database Developer.
As a database developer, we are executing COUNT(*) many times to check the total number of table records. But have you ever check the execution plan of your COUNT(*) statement?
If your answer is No, then you should check below demonstration.
If your answer is Yes, then don’t be surprised by checking below demonstration because COUNT(*) statement first uses a lightweight index of a table. If an index does not present, it will do a Table Scan.
Create a table with sample data:
1 2 3 4 5 |
CREATE TABLE tbl_Count (ID1 INT IDENTITY, ID2 SMALLINT DEFAULT 1, Name CHAR(500) DEFAULT 'dbrnd.com') INSERT INTO tbl_Count DEFAULT VALUES; GO 10000 |
Check query execution plan of COUNT statement:
It performed Table scan because didn’t find any indexes on a table.
1 |
SELECT COUNT(1) FROM tbl_Count |
Now create an index on NAME column:
1 2 |
CREATE NONCLUSTERED INDEX idx_tbl_Count_Name ON tbl_Count (Name) GO |
Check query execution plan of COUNT statement:
You can find Index scan for idx_tbl_Count_Name.
1 |
SELECT COUNT(1) FROM tbl_Count |
Now create an index on ID2 column:
1 2 |
CREATE NONCLUSTERED INDEX idx_tbl_Count_ID2 ON tbl_Count (ID2) GO |
Check query execution plan of COUNT statement:
You can find Index scan for idx_tbl_Count_ID2 (smallint) because it lightweight than idx_tbl_Count_Name (char).
1 |
SELECT COUNT(1) FROM tbl_Count |
Leave a Reply