Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order by null first, then order by other variable

Tags:

mysql

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.

like image 792
Johan Avatar asked Aug 28 '09 15:08

Johan


People also ask

How are NULL values sorted in a regular ORDER BY clause?

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.

When data is sorted in descending order are NULL values listed first or 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.

How do I order one thing and another in SQL?

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.

When multiple orders are used in ORDER BY clause?

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).


1 Answers

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 :

  • number null ; id=1
  • number null ; id=2
  • number null ; id=5
  • number null ; id=8
  • number not null ; id=3
  • number not null ; id=4
  • number not null ; id=7
  • number not null ; id=10
  • number not null ; id=12
like image 111
Pascal MARTIN Avatar answered Sep 29 '22 12:09

Pascal MARTIN