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?
1 Answer
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.
EXISTS()But I would not worry about pre-mature optimization in general.SELECT TOP 1 x WHERE y