Query non-empty values of a row first in ascending order and then display NULL values

MySQLMySQLi Database

For this, use ORDER BY ISNULL(). Let us first create a table −

mysql> create table DemoTable669
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentScore int
);
Query OK, 0 rows affected (0.55 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable669(StudentScore) values(45) ;
Query OK, 1 row affected (0.80 sec)
mysql> insert into DemoTable669(StudentScore) values(null);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable669(StudentScore) values(89);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable669(StudentScore) values(null);
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable669;

This will produce the following output −

+-----------+--------------+
| StudentId | StudentScore |
+-----------+--------------+
| 1         | 45           |
| 2         | NULL         |
| 3         | 89           |
| 4         | NULL         |
+-----------+--------------+
4 rows in set (0.00 sec)

Following is the query to display non-empty values in ascending order. The null values would be displayed afterwards −

mysql> select *from DemoTable669
ORDER BY ISNULL(StudentScore),StudentScore;

This will produce the following output −

+-----------+--------------+
| StudentId | StudentScore |
+-----------+--------------+
| 1         | 45           |  
| 3         | 89           |
| 2         | NULL         |
| 4         | NULL         |
+-----------+--------------+
4 rows in set (0.00 sec)
raja
Published on 21-Jan-2020 12:19:53
Advertisements