Syntax error Display the result with not null value first and then with null value in MySQL

Display the result with not null value first and then with null value in MySQL



Let us first create a table −

mysql> create table DemoTable1357
    -> (
    -> StudentName varchar(40),
    -> StudentCountryName varchar(30)
    -> );
Query OK, 0 rows affected (0.49 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1357 values('Chris','US');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1357 values('David',NULL);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1357 values('David','AUS');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1357 values('Carol',NULL);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1357 values('Mike','UK');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1357;

This will produce the following output −

+-------------+--------------------+
| StudentName | StudentCountryName |
+-------------+--------------------+
| Chris       | US                 |
| David       | NULL               |
| David       | AUS                |
| Carol       | NULL               |
| Mike        | UK                 |
+-------------+--------------------+
5 rows in set (0.00 sec)

Following is the query to display the result with not null value first and then with null value −

mysql> select * from DemoTable1357
    -> order by (StudentCountryName IS NULL),StudentName;

This will produce the following output −

+-------------+--------------------+
| StudentName | StudentCountryName |
+-------------+--------------------+
| Chris       | US                 |
| David       | AUS                |
| Mike        | UK                 |
| Carol       | NULL               |
| David       | NULL               |
+-------------+--------------------+
5 rows in set (0.00 sec)
Updated on: 2019-11-05T10:18:06+05:30

359 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements