Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Order by field, placing empty cells at end

Tags:

sorting

mysql

I have a MySQL table which contains a number of products. What I want to do is sort the table by one particular column (most of the values begin with numbers for example: 1st, 2nd), etc. However, since some records do not have a value for this column, when I try to sort, the table automatically puts empty rows FIRST.

I am looking for a way to sort the row ASCENDING, but only insert blank records at the end of the sorted records, if that makes sense?

Any help would be most gratefully received!

like image 375
BenM Avatar asked Apr 28 '11 22:04

BenM


People also ask

How do I sort by NULLs last in SQL?

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.

When data is sorted in descending order are NULL values listed first or last?

Specifying the order of NULL values In a descending sort, DESC NULLS FIRST specifies that rows with a NULL value in the sort key column precede non-NULL rows in the sorted result set. The NULLS LAST keywords instruct the database server to put NULL values last in the sorted query results.

How do I order descending in MySQL?

The MySQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How do you sort data without using ORDER BY clause in MySQL?

Use stored procedure to produce sorted list in one text return value. Write own SQL proxy client replacing -- HIDDEN MESSAGE with ORDER BY . (I admit, this is not exactly SQL solution). Create an Indexed (Materialized) View on the table sorted by DEPARTMENT_ID that would be solely used by this query.


2 Answers

select * from table order by if(field = '' or field is null,1,0),field 
like image 61
Nicola Cossu Avatar answered Oct 21 '22 16:10

Nicola Cossu


This is one of the most effective method

ASC Order

SELECT * FROM user ORDER BY name IS NULL, name ASC 

Expected Result:

+----+--------+------------+ | id |  name  | date_login | +----+--------+------------+ |  3 |  david | 2016-12-24 | |  2 |  john  | NULL       | |  4 |  zayne | 2017-03-02 | |  1 |  NULL  | 2017-03-12 | 

DESC Order

SELECT * FROM user ORDER BY name IS NULL, name DESC 

Expected Result:

+----+--------+------------+ | id |  name  | date_login | +----+--------+------------+ |  4 |  zayne | 2017-03-02 | |  2 |  john  | NULL       | |  3 |  david | 2016-12-24 | |  1 |  NULL  | 2017-03-12 | 
like image 37
Ahmad Vaqas Khan Avatar answered Oct 21 '22 16:10

Ahmad Vaqas Khan