Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under what conditions would SELECT by PRIMARY KEY be slow?

Chasing down some DB performance issues in a fairly typical EclipseLink/JPA application.

I am seeing frequent queries that are taking 25-100ms. These are simple queries, just selecting all columns from a table where its primary key is equal to a value. They shouldn't be slow.

I'm looking at the query time in the postgres log, using the log_min_duration_statement so this should eliminate any network or application overhead.

This query is not slow, but it is used very often.

Why would selecting * by primary key be slow? Is this specific to postgres or is it a generic DB issue? How can I speed this up? In general? For postgres?

Sample query from the pg log:

2010-07-28 08:19:08 PDT - LOG:  duration: 61.405 ms  statement: EXECUTE <unnamed>  [PREPARE:  SELECT coded_ele
ment_key, code_system, code_system_label, description, label, code, concept_key, alternate_code_key FROM coded
_element WHERE (coded_element_key = $1)]

Table has around 3.5 million rows.

I have also run EXPLAIN and EXPLAIN ANALYZE on this query, its only doing an index scan.

like image 906
Freiheit Avatar asked Jul 28 '10 16:07

Freiheit


People also ask

What is the condition of primary key?

A primary key's main features are: It must contain a unique value for each row of data. It cannot contain null values. Every row must have a primary key value.

Does primary key affect performance?

By itself, a primary key does not have a direct affect on performance. But indirectly, it does. This is because when you add a primary key to a table, SQL Server creates a unique index (clustered by default) that is used to enforce entity integrity.

Do primary keys make queries faster?

Having a primary key per se will not speed up queries. Primary key constraints are usually accompanied by a unique index.


1 Answers

Select * makes your database work harder, and as a general rule, is a bad practice. There are tons of questions/answers on stackoverflow talking about that.

have you tried replacing * with the field names?

like image 59
dave Avatar answered Oct 28 '22 13:10

dave