We'll be discussing the following two cases as sorting NULL values in either of the cases might not be straightforward:. You can follow our guide and examples to discover how to achieve these and avoid unexpected results. For this article, we'll be using the following MySQL database table:. A number 3 is lower than a number 5. A text abc is lower then a text klmn. There seem to be nothing special about it, except only a few subjects - one of them is sorting NULL values.
Is NULL lower or greater then a number 3, a text klmn and a date ? For example when sorted in ascending order, NULLs come first. What if you want to change the default NULL priority? Yes, there are some real life scenarios when you need that. An example?
Here it is. Imagine a banking system that takes care of credit cards, their limits etc. There is a table with each credit card and its monthly limit:. We can be sure that no paintings in our table are from the future. We could use any number above to accomplish this.
In most cases, you can easily change this default behavior. Back to articles list Articles Cookbook. Find out! Today, in the first post of the SQL patterns series, we will consider the match by null pattern. It's inevitable that some data in the database has no value. Now, you want to sort the results from employee table by the commission column. However, this column is nullable so we will need to specify whether NULL values sort last or first.
The above queries sort the results for nullable column commission. If you would like to sort non-NULL values in ascending and descending order and place the NULL values either first or last, you can use sub-queries with case expression.
0コメント