Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL order by two columns and order results again

My table has two columns which I need to sort by:

content title

Only some rows have data in the content column but all have some in the title column. I need to sort these rows so that those with data in the content column are first. I can do this by:

ORDER BY content DESC, title ASC

However, those top rows returned because of their content column also need to be sorted alphabetically by their title (not by their content which I assume is happening).

Ideas? Thanks.

Update:

Should have noted that title is a VARCHAR and content is TEXT. So arbitary text. content column is empty if no content, not NULL.

So for example:

`title`     `content`
title a
title b      this has content
title c      so does this
title d

The order would be:

title c
title b
title a
title d
like image 565
Ashley Avatar asked Nov 17 '11 16:11

Ashley


People also ask

Can we use ORDER BY for 2 columns?

You can also ORDER BY two or more columns, which creates a nested sort . The default is still ascending, and the column that is listed first in the ORDER BY clause takes precedence. The following query and Figure 3 and the corresponding query results show nested sorts.

Can we have 2 ORDER BY in mysql?

Using with multiple columnsDefine your multiple column names in ORDER BY clause separated by a comma (,). You can also specify your sorting order ASC or DESC . In the above query, I am ordering the emp_salary table by age in Ascending order and salary by descending order.

How does ORDER BY work with multiple columns?

Syntax: SELECT * FROM table_name ORDER BY column_name; For Multiple column order, add the name of the column by which you'd like to sort records first. The column that is entered at first place will get sorted first and likewise.

Can you arrange the result set of an SQL query on multiple columns?

Can you arrange the result set of an SQL query on multiple columns? If you specify multiple columns, the result set is sorted by the first column and then that sorted result set is sorted by the second column, and so on.


1 Answers

If I understand what you need, try this:

SELECT * FROM your_table
ORDER BY
  CASE
    WHEN content IS NULL THEN 1
    ELSE 0
  END
  ,content,title
like image 176
Marco Avatar answered Sep 20 '22 12:09

Marco