Technical Article

Script to sort by columns that may include NULLs

,

If you sort by in ASC order by column that may include NULLs and empty strings ( if type is varchar), the records with nulls will always appear before any others.
This script will show how to chagne this pattern and move all records with NULLs to the bottom of your recordset

/*
Script to sort by columns that may include NULLs and/or empty strings


Replace NULL values with either string of "zzzzzz" or 999999( put as many as you think is sufficient enough to make it a last record and to be in a datatype range)

*/--For a varchar type of the field3:

SELECT field1, field2 FROM table 
order by isnull(nullif(field3,''),'zzz') asc



--For a numeric type of the field3:

SELECT field1, field2 FROM table 
order by isnull(field3,9999999) asc

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating