From: Shantanu Shekhar <shekharshan@yahoo.com>
To: pgsql-general@lists.postgresql.org <pgsql-general@lists.postgresql.org>
Subject: Range search on primary key does not use index scan
Date: Thu, 24 Dec 2020 01:08:54 +0000 (UTC)
Message-ID: <1366951904.2544671.1608772134019@mail.yahoo.com> (raw)
References: <1366951904.2544671.1608772134019.ref@mail.yahoo.com>
I am trying to understand how Postgres uses index and ran into a surprising behavior if someone can help me with. I have a table like so:
CREATE TABLE testschema.employees ( employee_id integer not null, first_name varchar(1000) not null, last_name varchar(1000) not null, date_of_birth date not null, phone_number varchar(1000) not null, constraint employees_pk primary key (employee_id) );
At the moment I have ZERO rows in the table. I verified that employees_pk creates an index of type 'btree(employee_id). After that I ran explain on two queries:
(1) Here I am searching for employee_id '123' and as expected the plan shows it will do an b-tree traversal on employees_pk index.
testdb# explain select first_name, last_name from testschema.employees where employee_id = 123; QUERY PLAN ═════════════════════════════════════════════════════════════════════════════════ Index Scan using employees_pk on employees (cost=0.14..8.16 rows=1 width=1032) Index Cond: (employee_id = 123)(2 rows)
(2) Here I am searching for employee_id < 123. I was expecting the plan would use the index on employees_pk to find all leaf nodes where employee_id < 123 and then issue read of table blocks for each of the matching entries in the index leaf. But looks like the query plan has decided on using full table scan instead and not using the index. Any ideas why is this happening?
testdb# explain select first_name, last_name from testschema.employees where employee_id < 123; QUERY PLAN ══════════════════════════════════════════════════════════════ Seq Scan on employees (cost=0.00..10.62 rows=17 width=1032) Filter: (employee_id < 123)(2 rows)
Any help will be greatly appreciated.
Thanks,
Shantanu
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 from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-general@postgresql.org
Cc: shekharshan@yahoo.com
Subject: Re: Range search on primary key does not use index scan
In-Reply-To: <1366951904.2544671.1608772134019@mail.yahoo.com>
References: <1366951904.2544671.1608772134019.ref@mail.yahoo.com> <1366951904.2544671.1608772134019@mail.yahoo.com>
* 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