33

I'd like to know how to maximize speed when querying for the presence of a varchar value in a column in a specific table. I don't need to know where it is, or how many occurrences there are, I just want a true/false. Of course, the column has an index.

Now, I have this:

SELECT exists (SELECT 1 FROM table WHERE column = <value> LIMIT 1);
1

2 Answers 2

33

EXISTS should normally return as soon as the subquery finds one row that satisfies its WHERE clause. So I think your query is as fast as you can make it.

I was a little surprised that LIMIT 1 seems to always speed up the query very slightly. I didn't expect that. You can see the effect with EXPLAIN ANALYZE.

EXPLAIN ANALYZE
SELECT exists (SELECT 1 FROM table WHERE column = <value> LIMIT 1);
Sign up to request clarification or add additional context in comments.

1 Comment

Can you tell me how query is commonly used for this (check if exist with max speed)
2

I have had recent success with the following in some cases:

SELECT count(1) > 0
FROM table
WHERE column = <value>

4 Comments

what do you mean "in some cases"?
@SafwanLjd Surprisingly using 'count(1) > 0' is faster in some cases and exists is faster in others. In most cases 'count(1) > 0' leads to cleaner looking code.
I guess the correct query will be: SELECT count(1) > 0 FROM table WHERE column = <value>;
In my case exist() takse 3ms to execute the query but count() takes whooping 20ms so I would suggest to go with exist(). My conf is Postgresql with 88862 rows of table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.