0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PostgreSQLでSELECTする時はORDER BYを付けよう

Posted at

PostgreSQLに慣れるため基本的なクエリをいくつか実行していたときのこと。
SELECTを実行したときの結果と、SELECT DISTINCTを実行したときの結果で、表示順が違いました。

実行環境

❯ psql --version
psql (PostgreSQL) 14.15 (Homebrew)

SELECT実行結果

sample_sql_crud=# SELECT  first_name, last_name, sex, enrolled_at FROM users;
 first_name | last_name | sex | enrolled_at 
------------+-----------+-----+-------------
 James      | Smith     |   1 | 2019-10-01
 Robert     | Johnson   |   1 | 2019-10-01
 Linda      | Brown     |   2 | 2019-12-01
 William    | Miller    |   1 | 2019-12-01
 Elizabeth  | Taylor    |   2 | 2020-02-01
 Maria      | Davis     |   2 | 2020-02-01
 Richard    | Jones     |   1 | 2020-04-01
 Jennipher  | Moore     |   2 | 2020-04-01
 Richard    | Jones     |   1 | 2020-04-01
(9 rows)

SELECT DISTINCT実行結果

sample_sql_crud=# SELECT DISTINCT first_name, last_name, sex, enrolled_at FROM users;
 first_name | last_name | sex | enrolled_at 
------------+-----------+-----+-------------
 James      | Smith     |   1 | 2019-10-01
 Jennipher  | Moore     |   2 | 2020-04-01
 Robert     | Johnson   |   1 | 2019-10-01
 Elizabeth  | Taylor    |   2 | 2020-02-01
 Richard    | Jones     |   1 | 2020-04-01
 William    | Miller    |   1 | 2019-12-01
 Linda      | Brown     |   2 | 2019-12-01
 Maria      | Davis     |   2 | 2020-02-01
(8 rows)

この結果を見て疑問が湧いてきました。

  • なぜDISTINCTをすると表示順序が変わるのだろう?
  • そもそもSELECTでは表示順序は毎回同じなのだろうか?

公式ドキュメントを見よう!

疑問が湧いたら公式ドキュメントを見よう!
ということで見てみました。
https://www.postgresql.org/docs/14/sql-select.html#SQL-ORDERBY

If the ORDER BY clause is specified, the returned rows are sorted in the specified order. If ORDER BY is not given, the rows are returned in whatever order the system finds fastest to produce. (See ORDER BY Clause below.)

ORDER BY 句がない場合は、システムが最速で生成できると判断した順序で表示する。としか書かれていません。
SELECTを複数回実行するとき、各回において表示順の一貫性は保証されないようです。
また、SELECT DISTINCTの結果がSELECTの結果と違う順序で表示されるのは、2つのクエリが内部的に異なるプロセスで計算されているため、最速で生成できる順序も異なるからだと思われます。

結論: SELECTでは表示順は保証されない

結論としては、PostgreSQLのSELECTでは表示順は保証されない/表示順を保証したければORDER BYを付ける必要があるということでした。

PostgreSQLの公式ドキュメントは比較的読みやすくてありがたいです!

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?