How to check if value exists with MySQL SELECT 1?


Use SELECT 1 for this as in the below syntax −

select 1 from yourTableName where yourColumnName=yourValue;

If the above returns 1, that means value exists in the MySQL database. Let us first see an example and create a table −

mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(40),
   StudentAge int
);
Query OK, 0 rows affected (0.46 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(StudentName,StudentAge) values('Chris',21);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(StudentName,StudentAge) values('David',20);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(StudentName,StudentAge) values('Bob',22);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(StudentName,StudentAge) values('Tom',19);
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
|        1 | Chris        |         21 |
|        2 | David        |         20 |
|        3 | Bob          |         22 |
|        4 | Tom          |         19 |
+-----------+-------------+------------+
4 rows in set (0.00 sec)

Let us now check if value exists in MySQL database −

mysql> select 1 from DemoTable where StudentName='Bob';

This will produce the following output −

+---+
| 1 |
+---+
| 1 |
+---+
1 row in set (0.00 sec)
raja
Published on 07-Oct-2019 15:35:43
Advertisements