Different ways to check if a row exists in a MySQL table
This article highlights different ways to check if a row exists in a MySQL table. We will use the EXISTS
and NOT EXISTS
operators.
We can also use these two operators with IF()
the function to get a meaningful message if a row (a record) is found.
Different ways to check if a row exists in a MySQL table
We can use the following method to check if a row exists in a MySQL table.
We should have a table to use all the methods mentioned above.
For this purpose, we created a person
table named with ID
and NAME
attributes (columns). You can also create and populate it with some data using the following query.
Create the table:
/*
create a table named `person`.
Here, the schema (database)
name is `ms20`
*/
CREATE TABLE `ms20`.`person` (
`ID` INT NOT NULL AUTO_INCREMENT,
`NAME` VARCHAR(45) NOT NULL,
PRIMARY KEY (`ID`));
Populate the table (insert data):
/*
populate the table with some data. Here,
we are only inserting the names because
ID is auto increment, and we don't need to
insert that.
*/
INSERT INTO ms20.person (NAME) VALUES
('Mehvish'),
('Thomas'),
('John'),
('Daniel');
/*
The following query can be used if we want to insert
a custom ID rather than the auto-incremented one
*/
INSERT INTO ms20.person (ID, NAME) VALUES (6,'Sara');
Display table:
SELECT * FROM ms20.person;
Output:
Check if a row (record) exists in a MySQL table using EXISTS
the operator
Sample code:
SELECT EXISTS (
SELECT NAME FROM ms20.person
WHERE ID = 6) as OUTPUT;
Output (if record found):
OUTPUT
1
Sample code:
SELECT EXISTS (
SELECT NAME FROM ms20.person
WHERE ID = 7) as OUTPUT;
Output (if no record found):
OUTPUT
0
EXISTS
The operator checks if a record exists in a table (satisfies the specified condition). It is used in conjunction with another subquery which may or may not satisfy the condition.
EXISTS
The operator returns
if the subquery finds at least one record true
. true
and are represented by and , false
respectively .1
0
We can EXISTS
use the clause with other MySQL commands including SELECT
, INSERT
, UPDATE
, DELETE
. In addition, further processing is EXISTS
terminated by the clause once a row that satisfies the specified condition is successfully found.
This technique helps improve the performance of queries, especially when we are searching in a table containing thousands of records.
Use NOT EXISTS
the operator to check if a row(record) does not exist in a MySQL table
Sample code:
SELECT NOT EXISTS (
SELECT NAME FROM ms20.person WHERE ID = 7)
As RESULT;
Output (if no record found):
RESULT
1
Sample code:
SELECT NOT EXISTS (
SELECT NAME FROM ms20.person WHERE ID = 6)
As RESULT;
Output (if record found):
RESULT
0
NOT EXISTS
The operator EXISTS
is the opposite of the operator and returns if the table does not contain a row with the given condition true
( 1
denoted by ). If the record is found in the table, it NOT EXISTS
returns false
, 0
denoted by .
We can use the operator in MySQL 8.0.19 or later NOT EXISTS
. It can also be used with in a subquery TABLE
, for example SELECT c1 FROM t1 WHERE EXISTS(TABLE t2);
.
Use the EXISTS
/ NOT EXISTS
operator and IF()
the function to check if a row exists in a MySQL table
Example code (with EXISTS
operator):
SELECT IF ( EXISTS
( SELECT NAME FROM ms20.person WHERE ID = 7) ,
"FOUND", "NOT FOUND");
Output:
NOT FOUND
This approach is easier to use
than the hard-to-remember Boolean ( 1
or ).0
If there is a record with 7 person
in the table , the above query returns . Otherwise, we will get .ID
"FOUND"
"NOT FOUND"
Here, you might be wondering which part of the query will be executed first. In that case, you can look at the following screenshot to understand the order of execution of the queries given above.
Similarly, we can use NOT EXISTS
with IF()
the function as shown below, if the record is not found in the specified table, we will get YES
; otherwise, 否
.
Example code (using NOT EXISTS
the operator):
SELECT IF ( NOT EXISTS
( SELECT NAME FROM ms20.person WHERE ID = 7) ,
"YES", "NO");
Output:
YES
Remember that we can use SELECT column
, SELECT someConstant
, , SELECT *
or anything else in the subquery. The output will be the same because MySQL ignores SELECT
the _list ( SELECT
which is present because of the _clause).
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
How to select from multiple tables in MySQL
Publish Date:2025/04/25 Views:57 Category:MySQL
-
This article explains how to use MySQL to query from multiple tables in one script SELECT . Let's demonstrate a situation: SELECT name , price, details, type , FROM food, food_order WHERE breakfast.id = 'breakfast_id' Now, let's imagine FRO
Creating a table from CSV in MySQL
Publish Date:2025/04/25 Views:114 Category:MySQL
-
In this article, we aim to understand how to create a table from CSV in MySQL database. Businesses and organizations must quickly generate tables from large amounts of data. These organizations typically have large CSV files with large amou
Creating a Temporary Table in MySQL
Publish Date:2025/04/25 Views:183 Category:MySQL
-
In this article, we aim to explore different ways to create temporary tables in MySQL. One of the main features of temporary tables is that it helps in storing temporary data. This feature is enabled in MySQL 3.23 and later versions. These
Truncate all tables in Mysql
Publish Date:2025/04/25 Views:89 Category:MySQL
-
Today I will show you how to truncate all tables in Mysql. It is used when you want to delete the entire table TRUNCATE TABLE . TRUNCATE It is a type of DML statement, which means it cannot be rolled back once it is committed. There are two
Get column names in MySQL
Publish Date:2025/04/25 Views:109 Category:MySQL
-
In this article, we aim to explore how to get the column names of a specific table in MySQL database. Often, when working with data in MySQL, we tend to forget the column names of a particular table in the database and the data types of dif
Get the version in MySQL
Publish Date:2025/04/24 Views:170 Category:MySQL
-
In this article, we will learn how to get the current version of MySQL on Windows systems. It is necessary for businesses to maintain versions of different tools and software used to run their business in order to keep systems compatible. T
Full Join in MySQL
Publish Date:2025/04/24 Views:71 Category:MySQL
-
This article aims to explore how to perform a full join or full outer join in MySQL. Full outer join is used to merge or combine the entire data from two separate tables. For example, suppose we have two tables named student_id and student_
Grouping by month in MySQL
Publish Date:2025/04/24 Views:166 Category:MySQL
-
In this article, we will learn how to group values by month in MySQL database. Businesses and organizations have to find user or customer data based on purchase or usage trends over a few months. If a particular business achieves its
Enabling the slow query log in MySQL
Publish Date:2025/04/24 Views:177 Category:MySQL
-
Today, we will enable MySQL in MySQL using MySQL shell on Windows and Ubuntu 20.04 slow_query_log . For this tutorial, we are using MySQL version 8.0 and Ubuntu 20.04. MySQL slow_query_log MySQL slow_query_log contains SQL statements that t