I want to know if a table contains at least one entry that meets specific conditions. I don't want to go over all entries but to stop at first one. Is there a generic way to do this in sql?
Asked
Active
Viewed 39 times
-1
-
look up `EXISTS()` But I would not worry about pre-mature optimization in general. – Hogan Feb 01 '16 at 16:48
-
or `SELECT TOP 1 x WHERE y` – mikeyq6 Feb 01 '16 at 16:53
-
1This is a very fundamental question. That being the case, I've heard good things about the book, Teach Yourself SQL in 10 Minutes. – Dan Bracuk Feb 01 '16 at 17:05
-
Levka, did you try my solution? – Andrew Feb 05 '16 at 17:09
-
I did, but as it appears sql still goes over the whole table( I tried it on tables with different sizes and the procedure times where different) – Strelnikov Lev Feb 07 '16 at 10:15
-
But that's how it's done. It may take different times depending on the table structure, the indexes and the condition you are using! Check this answer if you want to read more about this: http://stackoverflow.com/questions/424212/performance-of-sql-exists-usage-variants – Andrew Feb 10 '16 at 19:53
1 Answers
1
I think a research would have given you the answer much more quickly, but anyway here is what I use:
IF EXISTS (SELECT NULL FROM Table WHERE Field = @value)
BEGIN
PRINT 'Exists!'
END
ELSE
BEGIN
PRINT 'Does not exist!'
END
Bear in mind that when using EXISTS
, it doesn't matter what fields you select, whether they are from the table, constants or even NULL values as in this case.

Andrew
- 7,602
- 2
- 34
- 42