LoginSignup
28
18

More than 3 years have passed since last update.

【SQL】COUNT(*)とCOUNT(カラム名)の違い

Last updated at Posted at 2019-12-31

はじめに

COUNT句に*を指定した場合とカラム名を指定した場合の挙動の違いが理解できていなかったため、この記事を書くことで理解を深める。

この記事の対象者

COUNT(*)COUNT(カラム名)の違いを知らない人

結論

  • COUNT(*)はNULL値かどうかに関係なく、取得された行の数を返す
  • COUNT(カラム名)はNULL値でない値の行数を返す

実験

実際に挙動を確認する。

  • 実行環境
# mysql --version
mysql  Ver 8.0.18 for Linux on x86_64 (MySQL Community Server - GPL)
  • テーブル
CREATE TABLE shohin (
    id INTEGER NOT NULL PRIMARY KEY
,   name VARCHAR(20)
,   price INTEGER
);
  • レコード
+----+--------+-------+
| id | name   | price |
+----+--------+-------+
|  1 | apple  |   100 |
|  2 | banana |   120 |
|  3 | grape  |   140 |
|  4 | melon  |  NULL |
|  5 | kiwi   |   120 |
+----+--------+-------+

COUNT(*)の場合

select count(*) from shohin;
+----------+
| count(*) |
+----------+
|        5 |
+----------+

COUNT(カラム名)の場合

select count(price) from shohin;
+----------+
| count(*) |
+----------+
|        4 |
+----------+

まとめ

SQLのCOUNT句を実際に実行することで理解を深めた。

参考

・MySQL COUNT句 リファレンス
https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_count

28
18
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
28
18