Order By Null Fields, Order By Blank Fields

If you are looking for the query which will return you the values in the order of null or blank fields first and others next or vice versa, like if there is a table which includes the address of the people, but it contains blank or null values as well, and you have to make them order in ascending or descending order, like the blank or null fields come first and the others next, or the filled fields come first and the blank / null next, then the following queries may help:

Order By Null Fields

To make your results where you want to adjust the null fields first and others next or vice versa, try the following queries, where tbl_test is the table name, while the field name which contains the null and filled values is address:

Order By Null Fields In Ascending Order

SELECT *, IF(address IS NULL, 0, 1) AS status 
FROM tbl_test
ORDER BY status

or

SELECT *, address IS NULL AS status 
FROM tbl_test
ORDER BY status DESC

Order By Null Fields In Descending Order

SELECT *, IF(address IS NULL, 0, 1) AS status 
FROM tbl_test
ORDER BY status DESC

or

SELECT *, address IS NULL AS status 
FROM tbl_test
ORDER BY status

Order By Blank Fields

To make your results where you want to adjust the blank fields first and others next or vice versa, try the following query, where tbl_test is the table name, while the field name which contains blank and filled values is address:

Order By Null Fields In Ascending Order

SELECT *, IF(address = '',0,1) AS status 
FROM tbl_test
ORDER BY status

Order By Null Fields In Descending Order

SELECT *, IF(address = '',0,1) AS status
FROM tbl_test
ORDER BY status DESC
Uncategorised

Leave a Reply

Your email address will not be published. Required fields are marked *