-1

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?

6
  • look up EXISTS() But I would not worry about pre-mature optimization in general. Commented Feb 1, 2016 at 16:48
  • or SELECT TOP 1 x WHERE y Commented Feb 1, 2016 at 16:53
  • 1
    This is a very fundamental question. That being the case, I've heard good things about the book, Teach Yourself SQL in 10 Minutes. Commented Feb 1, 2016 at 17:05
  • Levka, did you try my solution? Commented Feb 5, 2016 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) Commented Feb 7, 2016 at 10:15

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.