Re: Suboptimal query plan fixed by replacing OR with UNION - Mailing list pgsql-general

From Jasen Betts
Subject Re: Suboptimal query plan fixed by replacing OR with UNION
Date
Msg-id jt5fdi$9us$1@reversiblemaps.ath.cx
Whole thread Raw
In response to Suboptimal query plan fixed by replacing OR with UNION  (Steven Schlansker <steven@likeness.com>)
Responses Re: Suboptimal query plan fixed by replacing OR with UNION  (Steven Schlansker <steven@likeness.com>)
List pgsql-general
I note you've decided to rewrite this query as a union

> SELECT * FROM account
>   WHERE user_id in
>     (SELECT user_id FROM account
>       WHERE id =
ANY('{00000000-02f6-379d-c000-000000026810,00000000-0320-b467-c000-000000026810,00000000-000d-cefb-c000-000000026810}'))
>   OR
>     id =
ANY('{00000000-02f6-379d-c000-000000026810,00000000-0320-b467-c000-000000026810,00000000-000d-cefb-c000-000000026810}');

I notice both arrays (used with = ANY) have the exact same content,

if this is always true you can use a CTE here for the ID=ANY(...)
query and reference the CTE on both sides of the union.

WITH i as (
 SELECT * FROM account WHERE id =
ANY('{00000000-02f6-379d-c000-000000026810,00000000-0320-b467-c000-000000026810,00000000-000d-cefb-c000-000000026810}')
)
SELECT
 * from i
UNION DISTINCT
SELECT
 account.* from account join i on i.user_id = account.userid ;

--
⚂⚃ 100% natural

pgsql-general by date:

Previous
From: Keith Fiske
Date:
Subject: Issue with extension updates to pg_extension table
Next
From: Craig Ringer
Date:
Subject: Re: [PERFORM] The need for clustered indexes to boost TPC-V performance