Remove specific fields/ rows and show other records in MySQL?


For this, use CASE WHEN statement in MySQL. Let us create a table −

mysql> create table demo47
−> (
−> first_name varchar(20),
−> last_name varchar(20)
−> );
Query OK, 0 rows affected (1.57 sec)

Insert some records into the table with the help of insert command −

mysql> insert into demo47 values('John','Smith');
Query OK, 1 row affected (0.18 sec)

mysql> insert into demo47 values('David','Miller');
Query OK, 1 row affected (0.11 sec)

mysql> insert into demo47 values('John','Doe');
Query OK, 1 row affected (0.12 sec)

mysql> insert into demo47 values('Chris','Brown');
Query OK, 1 row affected (0.12 sec)

Display records from the table using select statement −

mysql> select *from demo47;

This will produce the following output −

+------------+-----------+
| first_name | last_name |
+------------+-----------+
| John       | Smith     |
| David      | Miller    |
| John       | Doe       |
| Chris      | Brown     |
+------------+-----------+
4 rows in set (0.00 sec)

Following is the query to remove specific fields/ rows and display other records in MySQL.

mysql> select case when first_name= 'John' then last_name else first_name end Result
−> from demo47
−> where 'John' in (first_name,last_name);

This will produce the following output −

+--------+
| Result |
+--------+
| Smith  |
| Doe    |
+--------+
2 rows in set (0.00 sec)

Updated on: 19-Nov-2020

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements