this is my code for now:
SELECT id, number
FROM Media
WHERE user = 10
ORDER BY id, number
but I want it to look like:
SELECT id, number
FROM Media
WHERE user = 10
ORDER BY while(number IS NULL), id
What I want to do is to have all number
that are NULL
on the top of the result, but as soon number
is not NULL
, sort by id
Is that possible?
I use mysql.
If you specify the ORDER BY clause, NULL values by default are ordered as less than values that are not NULL. Using the ASC order, a NULL value comes before any non-NULL value; using DESC order, the NULL comes last.
If you sort a column with NULL values in ascending order, the NULLs will come first. Alternatively, if you add a DESC keyword to get a descending order, NULLs will appear last.
The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.
If you want to select records from a table but would like to see them sorted according to two columns, you can do so with ORDER BY. This clause comes at the end of your SQL query. After the ORDER BY keyword, add the name of the column by which you'd like to sort records first (in our example, salary).
what about something like this :
SELECT id, number
FROM Media
WHERE user = 10
ORDER BY (case when number is null then 0 else 1 end), id
If number is NULL, the first order by criteria will be 0 ; else 1
Which means every line will number NULL will come before the others ones
And note that ids will be sorted too, anyway.
You'll get something like this :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With