Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to test if a row exists in a MySQL table

I'm trying to find out if a row exists in a table. Using MySQL, is it better to do a query like this:

SELECT COUNT(*) AS total FROM table1 WHERE ... 

and check to see if the total is non-zero or is it better to do a query like this:

SELECT * FROM table1 WHERE ... LIMIT 1 

and check to see if any rows were returned?

In both queries, the WHERE clause uses an index.

like image 246
Bernard Chen Avatar asked Nov 04 '09 20:11

Bernard Chen


People also ask

How do you check if a row exists in a table MySQL?

To test whether a row exists in a MySQL table or not, use exists condition. The exists condition can be used with subquery. It returns true when row exists in the table, otherwise false is returned. True is represented in the form of 1 and false is represented as 0.

How do I find a row in MySQL?

MySQL SELECT statement is used to retrieve rows from one or more tables. The statement can also include UNION statements and subqueries. SELECT statement is used to fetch rows or records from one or more tables.

How do you check if data not exists in a table SQL?

SQL NOT EXISTS in a subquery NOT EXISTS is used with a subquery in the WHERE clause to check if the result of the subquery returns TRUE or FALSE. The Boolean value is then used to narrow down the rows from the outer select statement.


1 Answers

You could also try EXISTS:

SELECT EXISTS(SELECT * FROM table1 WHERE ...) 

and per the documentation, you can SELECT anything.

Traditionally, an EXISTS subquery starts with SELECT *, but it could begin with SELECT 5 or SELECT column1 or anything at all. MySQL ignores the SELECT list in such a subquery, so it makes no difference.

like image 153
Chris Thompson Avatar answered Sep 19 '22 05:09

Chris Thompson