12
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SQL再入門 #5 - ORDER BY句

Posted at

ORDER BY - 順番に取得

特定のカラムのデータを順番に取得したいときがあるとします。
そんなときORDER BYを使うと、検索結果が確認したい順番で返ってきます。

DESC

  • DESCはDescendingの略で、降順で取得できます

例)オンラインショップで直近の購入履歴から確認したい時(注文履歴テーブルをordersとする)

SELECT *
FROM orders
ORDER BY created_at DESC;

 ↓

+----+--------+--------+---------------------+---------------------+
| id | name   | price  | created_at          | updated_at          |
+----+--------+--------+---------------------+---------------------+
|  3 | coat   | 12,800 | 2026-01-07 11:55:44 | 2026-01-07 11:55:44 |
|  2 | shirt  |  2,300 | 2025-10-16 14:15:20 | 2025-10-16 14:15:20 |
|  1 | pants  |  4,500 | 2025-08-05 10:00:00 | 2025-08-05 10:00:00 |
+----+--------+--------+---------------------+---------------------+

ASC

  • ASCはAscendingの略で、データを昇順で取得できます

例)「ORDER BY + name + ASC」で、学校でいう出席番号順にユーザーのデータが返ってきます。

SELECT *
FROM users
ORDER BY name ASC;

 ↓

+----+--------+-----+--------+----------------------+
| id | name   | age | gender | email                |
+----+--------+-----+--------+----------------------+
|  5 | Hanako |  22 | female | hanako@example.com   |
|  7 | Kana   |  29 | female | kana@example.com     |
|  6 | Sota   |  37 | male   | sota@example.com     |
|  4 | Sho    |  15 | male   | sho@example.com      |
|  1 | Taro   |  28 | male   | taro@example.com     |
|  2 | Yuko   |  27 | female | yuko@example.com     |
|  3 | Yuta   |  33 | male   | yuta@example.com     |
+----+--------+-----+--------+----------------------+

ORDER BY句のデフォルトはASCなので、昇順検索の場合は、

SELECT *
FROM users
ORDER BY name

のようにASCを省略しても昇順検索できます!

12
2
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
12
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?