
- Learn MySQL
- MySQL - Home
- MySQL - Introduction
- MySQL - Installation
- MySQL - Administration
- MySQL - PHP Syntax
- MySQL - Connection
- MySQL - Create Database
- MySQL - Drop Database
- MySQL - Select Database
- MySQL - Data Types
- MySQL - Create Tables
- MySQL - Drop Tables
- MySQL - Insert Query
- MySQL - Select Query
- MySQL - Where Clause
- MySQL - Update Query
- MySQL - Delete Query
- MySQL - Like Clause
- MySQL - Sorting Results
- MySQL - Using Join
- MySQL - NULL Values
- MySQL - Regexps
- MySQL - Transactions
- MySQL - Alter Command
- MySQL - Indexes
- MySQL - Temporary Tables
- MySQL - Clone Tables
- MySQL - Database Info
- MySQL - Using Sequences
- MySQL - Handling Duplicates
- MySQL - SQL Injection
- MySQL - Database Export
- MySQL - Database Import
Implement CASE statement with WHEN clause to check for the existence of a record in MySQL
Let us first create a table −
mysql> create table DemoTable ( UserId int, UserName varchar(100) ); Query OK, 0 rows affected (0.57 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(100,'Chris'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(101,'Robert'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(102,'David'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(103,'Mike'); Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------+----------+ | UserId | UserName | +--------+----------+ | 100 | Chris | | 101 | Robert | | 102 | David | | 103 | Mike | +--------+----------+ 4 rows in set (0.00 sec)
Following is the query for CASE WHEN −
mysql> select case when exists(select * from DemoTable where UserId=102) then 'Present' else 'Not Present' end as Result;
This will produce the following output −
+---------+ | Result | +---------+ | Present | +---------+ 1 row in set (0.02 sec)
- Related Articles
- Implement MySQL CASE statement with WHEN clause
- Perform count with CASE WHEN statement in MySQL?
- Can we use WHERE clause inside MySQL CASE statement?
- How can we test for the existence of any record in MySQL subquery?
- Implement specific record ordering with MySQL
- Expression in CASE WHEN Clause doesn't work in MySQL query?
- How to implement switch-case statement in Kotlin?
- How to implement MySQL CASE with OR condition?
- Get the returned record set order in MySQL IN clause?
- Check for the existence of a key in Java IdentityHashMap
- Check for the existence of a value in Java IdentityHashMap
- MySQL case statement inside a select statement?
- How to add a where clause in a MySQL Insert statement?
- How to implement WHILE LOOP with IF STATEMENT MySQL?
- MySQL ORDER BY with CASE WHEN

Advertisements