How to efficiently check if a table is empty?

You are looking for an indication if the table is empty. For that SQL has the EXISTS keyword.
If you are doing this inside a stored procedure use this pattern:

IF(NOT EXISTS(SELECT 1 FROM dbo.MyTable))
BEGIN
  RAISERROR('MyError',16,10);
END;

IF you get the indicator back to act accordingly inside the app, use this pattern:

SELECT CASE WHEN EXISTS(SELECT 1 FROM dbo.MyTable) THEN 0 ELSE 1 END AS IsEmpty;

While most of the other responses will produce the desired result too, they seem to obscure the intent.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)