Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql - sort by most completed row

Tags:

sorting

mysql

I am working with sort syntax for mysql db and i would like to sort the rows by completion of columns. I hope example will describe the issue:

id |t1 | t2 | t3 | t4
----------------------
 1 | a |  b |  c | d
 2 |   |  e |    |
 3 | f |  g |    |
 4 | h |  i | j  |

this is my row/column structure. As you can see, some of the fields are empty. I'd like to sort the table so the imput would look like this

id |t1 | t2 | t3 | t4
----------------------
 1 | a |  b |  c | d
 4 | h |  i | j  |
 3 | f |  g |    |
 2 |   |  e |    |

It's been sorted by number of filled (non-empty) fields. The easiest way to do this is to sort with such a query:

SELECT id, t1, t2, t3, t4 FROM table ORDER BY t1 DESC, t2 DESC, t3 DESC, t4 DESC

It works good in most of cases but look what will happen if my table looks like this:

id |t1 | t2 | t3 | t4
----------------------
 1 |   |  b |  c | d
 2 |   |  z |    |

After sorting:

id |t1 | t2 | t3 | t4
----------------------
 2 |   |  z |    |
 1 |   |  b |  c | d

Why? Because sort order is descending, and t1 column is empty (so it's ignored), and the next column is t2. It is also sorted descending ignoring rest of the columns (if they are empty).

I found similiar problem solved (i guess - not checked yet) here but the solution looks nasty. Do you have other ideas to sort the table by number of non-empty columns?

like image 433
Kalreg Avatar asked Mar 25 '26 07:03

Kalreg


1 Answers

You should sum the results of IS NULL or IS NOT NULL for all of the relevant columns and use that as a primary sort to solve your basic problem, then impose whatever secondary sort you want.

It's unclear to me how you want to sort two rows with the same number of non-null column values, but I'll guess that you want to sort them ascending, left to right, in which case this should work for you:

(UPDATE: as eggyal pointed out, by "empty" you mean the empty string, not NULL. See updated query below):

SELECT id, t1, t2, t3, t4 
FROM table 
ORDER BY ((t1 = '') + (t2 = '') + (t3 = '') + (t4 = '')) ASC, 
t1 DESC, t2 DESC, t3 DESC, t4 DESC
like image 194
Ike Walker Avatar answered Mar 26 '26 20:03

Ike Walker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!