From: Andrew Gierth <andrew@tao11.riddles.org.uk>
To: Ivan Voras <ivoras@gmail.com>
Cc: postgres performance list <pgsql-performance@postgresql.org>
Subject: Re: Optimising a two column OR check
Date: Sat, 12 Oct 2019 16:16:50 +0100
Message-ID: <87a7a6xamw.fsf@news-spur.riddles.org.uk> (raw)
In-Reply-To: <CAF-QHFXQduEoX=ADZh2QYECLdcM1zOuY6=K0cE_DBjhdH3v+WA@mail.gmail.com>
References: <CAF-QHFXQduEoX=ADZh2QYECLdcM1zOuY6=K0cE_DBjhdH3v+WA@mail.gmail.com>
>>>>> "Ivan" == Ivan Voras <ivoras@gmail.com> writes:
Ivan> Hello,
Ivan> There's a "users" table with the following structure:
Ivan> CREATE TABLE "user" (
Ivan> id SERIAL PRIMARY KEY,
Ivan> -- other fields
Ivan> );
Ivan> and there's a "friends" table with the following structure:
Ivan> CREATE TABLE friend (
Ivan> user1_id INTEGER NOT NULL REFERENCES "user"(id),
Ivan> user2_id INTEGER NOT NULL REFERENCES "user"(id),
Ivan> -- other fields
Ivan> CHECK (user1_id < user2_id),
Ivan> PRIMARY KEY (user1_id, user2_id)
Ivan> );
Ivan> And I'm running this query:
Ivan> SELECT user1_id,user2_id FROM friend WHERE user1_id=42 OR user2_id=42;
To get friends of user 42:
SELECT user1_id FROM friend WHERE user2_id=42
UNION ALL
SELECT user2_id FROM friend WHERE user1_id=42;
assuming you create the (user2_id,user1_id) index, this should get you
an Append of two index-only scans. We can use UNION ALL here rather than
UNION because the table constraints ensure there are no duplicates.
--
Andrew (irc:RhodiumToad)
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: pgsql-performance@postgresql.org
Cc: andrew@tao11.riddles.org.uk, ivoras@gmail.com
Subject: Re: Optimising a two column OR check
In-Reply-To: <87a7a6xamw.fsf@news-spur.riddles.org.uk>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox