Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: How to find if there is at least one record matching a condition

In one of my database tables, I want to know if there is atleast one record corresponding to a condition.

The query i wrote is Count(*) from table where (condition) And in my program, i can check whether the result is a non-zero value. It works fine.

How can we optimize this? I dont want to wait till it finds the total count of records matching the condition.

like image 547
Dhanesh Avatar asked Sep 22 '13 10:09

Dhanesh


People also ask

Which SQL keyword checks whether a query returns at least one row?

The SQL EXISTS condition is used in combination with a subquery and is considered to be met, if the subquery returns at least one row. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

Which Return rows when there is at least one match in both tables?

INNER JOIN − returns rows when there is a match in both tables. LEFT JOIN − returns all rows from the left table, even if there are no matches in the right table.

How do I count matching rows in SQL?

The SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause. It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows.

How do you find the least value in SQL?

The MIN() function returns the smallest value of the selected column. The MAX() function returns the largest value of the selected column.


1 Answers

SQL has exists which can be used for this. This will return 1 if the query returns a result, and 0 otherwise.

Select Case When Exists (<query>) Then 1 Else 0 End as X
like image 127
Laurence Avatar answered Sep 25 '22 19:09

Laurence