I have created a table. In one field, I have a priority of that record (between 1-9).
I didn’t set priority for all the records, so for some records, it will remain null.
When displaying these records in my HTML page, I just check those priorities — if the priority exists, then I will display as it is, if it’s null, then I will display it as the lowest priority of ’10’ (just for display).
The problem occurs while sorting the table. If I try to sort(DESC) the table, it displays the 10 in the first row and later continues perfectly (1,2,….).
How to solve this?
Is it possible to display the priorities first and later continue with the null values?
There are a number of ways to solve it.
1/ Change the data so that 10 is actually in the table (rather than NULL):
2/ Modify your query to return different values for NULL:
3/ Create a view to do option 2 above automagically.
I’d tend to go for option 1 since it’s likely to be the most efficient.
SQL does not specify how NULLs are sorted (although I think it specifies they must be adjacent) – that means they could be at the beginning or end (or possibly in the middle though I’ve never seen that happen).
The reason I bring up the efficiency aspect is that per-row functions do not scale well. As the table gets bigger, you’ll find that converting NULLs into 10 every time you select will be very expensive.
It’s far better to bite the bullet and just set them to 10 in the database. This will allow the DBMS to optimize queries better. And, if you ever need to use 10 for another real priority level, just change all the current 10s to 11s (or 9999s) before you start.