3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

MysqlのソートでNULLや0を最後に並べる方法

Last updated at Posted at 2019-10-26

前置き

Mysqlでは、
シンプルにソートを行うと、
0NULLは先に並べられてしまいます。

SQL

SELECT *
FROM tests
ORDER BY
    rank ASC;
NULL->0->1~の順番になってしまう
+----+------+
| id | rank |
+----+------+
|  4 | NULL |
|  3 |    0 |
|  1 |    1 |
|  2 |    2 |
+----+------+

以下の方法で、NULLや0を最後に並べられるので、ぜひ使ってみてください!

NULL を最後に並べたい場合

SQL

SELECT *
FROM tests
ORDER BY
    rank IS NULL ASC, /* 追加 */
    rank ASC;
0->1~->NULLの順番になる
+----+------+
| id | rank |
+----+------+
|  3 |    0 |
|  1 |    1 |
|  2 |    2 |
|  4 | NULL |
+----+------+

NULL と 0 を最後に並べたい場合

SQL

SELECT *
FROM tests
ORDER BY
    rank IS NULL ASC, /* 追加 */
    rank = 0 ASC, /* 追加 */
    rank ASC;
1~->0&NULLの順番になる
+----+------+
| id | rank |
+----+------+
|  1 |    1 |
|  2 |    2 |
|  3 |    0 |
|  4 | NULL |
+----+------+
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?