How to Check If Value Exists in a MySQL Table
We can easily check if a value exists in a MySQL table using SELECT EXISTS.
1. Using SELECT EXISTS
We can combine SELECT EXISTS with SELECT 1 to achieve this.
SELECT EXISTS(SELECT 1 FROM table WHERE condition = value)
SELECT 1will return1for every row that satisfies the condition, otherwise it will not return anything.SELECT EXISTSwill return1or0depending on the existence of any record (this is useful if we explicitly need a0for rows that do not satisfy a condition).
We could technically run SELECT EXISTS(SELECT * ...), but it has been proven not to affect performance.
From the MySQL documentation:
Traditionally, an
EXISTSsubquery starts withSELECT *, but it could begin withSELECT 5orSELECT column1or anything at all. MySQL ignores theSELECTlist in such a subquery, so it makes no difference.
2. Using SELECT EXISTS with LIMIT 1
Adding a LIMIT clause will allow the query engine to halt after finding a single row.
SELECT EXISTS(SELECT 1 FROM table WHERE condition = value LIMIT 1)
To avoid a long column name, we can add an alias (e.g.
AS 'does_exist') to our query.