1
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でhaving句のalias

Last updated at Posted at 2022-11-12

MySQLで使えたはずのhaving句のaliasが使えない

PostgreSQLでは、having句でselect内でのaliasを使うことができない。

MySQLでは動くが、PostgreSQLでは動かない
SELECT
    status,
    count(*) AS status_count
FROM
    Users
GROUP BY status
HAVING status_count > 10;

PostgreSQLでは、実行順番でSELECT句よりも先にHAVING句が評価される。
そのため、PostgreSQLでは、以下のように書く必要がある。

SELECT
    status,
    count(*) AS status_count
FROM
    "Users"
GROUP BY status
HAVING count(*) > 10;

同じcount(*)が、2回書かれていて気になる。
count(*)の部分が、もっと複雑な計算式や条件分岐になった時に、冗長になる可能性がある。

綺麗に書けそう

WITH user_status_counts as (
    SELECT
        status,
        count(*) AS status_count
    FROM
        "Users"
    GROUP BY status
)
SELECT * from user_status_counts usc WHERE usc.status_count > 10;

WITHを使うことで、count(*)の部分が1回で済みそう。

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