How to sort a particular value at the end in MySQL?


For this, you can use ORDER BY. Let us create a table −

mysql> create table demo57
−> (
−> id int not null auto_increment primary key,
−> full_name varchar(20)
−> );
Query OK, 0 rows affected (1.60 sec)

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

mysql> insert into demo57(full_name) values('John Smith');
Query OK, 1 row affected (0.24 sec)

mysql> insert into demo57(full_name) values('David Miller');
Query OK, 1 row affected (0.13 sec)

mysql> insert into demo57(full_name) values('Not Known');
Query OK, 1 row affected (0.13 sec)

mysql> insert into demo57(full_name) values('Chris Brown');
Query OK, 1 row affected (0.31 sec)

Display records from the table using select statement −

mysql> select *from demo57;

This will produce the following output −

+----+--------------+
| id | full_name    |
+----+--------------+
|  1 | John Smith   |
|  2 | David Miller |
|  3 | Not Known    |
|  4 | Chris Brown  |
+----+--------------+
4 rows in set (0.00 sec)

Following is the query to sort a specific value at the end.

mysql> select *from demo57
−> order by(full_name="Not Known"),full_name desc;

This will produce the following output −

+----+--------------+
| id | full_name    |
+----+--------------+
|  1 | John Smith   |
|  2 | David Miller |
|  4 | Chris Brown  |
|  3 | Not Known    |
+----+--------------+
4 rows in set (0.00 sec)

Updated on: 20-Nov-2020

84 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements