0
0

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 1 year has passed since last update.

PostgreSQL 空の行に対してGROUP BYをした場合の関数の返しについて

Last updated at Posted at 2023-04-25

1行もヒットしない条件の中GROUP BYをしたところ、空の結果が返され
その結果Null PointExceptionが発生してしまった。

CREATE TABLE users_table (
  id SERIAL PRIMARY KEY,
  name VARCHAR(20)
)


INSERT INTO users_table (name) VALUES ('BOB'),('KEN'), (NULL)

上記のデータに

    SQL① 1行もヒットしない条件に対してGROUP BYをする。
SELECT count(name) AS count FROM users_table WHERE name = 'JOB' GROUP BY name

count
row0

とすると空の結果が返される

SQL② GROUP BYをしない。
SELECT count(name) AS count FROM users_table WHERE name = 'JOB' 

count |
1     | row1

GROUP BYすることによってかえってくる結果が変わるらしい。

SQL①はGROUP BYをしているが’JOB’が存在しないためグループ化する対象がないため、結果として何も返されない。

②はそもそもGROUP化をしていないため、テーブル全体が単一のグループとして扱われて、nameが'JOB'である行の数をカウントされているため0が返される。

GROUP BYを使用する際には気を付けます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?