Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

sql - Improve this query

do you know if there is a way to improve this query?

The database where this query runs is very large, and it could take a lot of time to return the result.

We have indexes on field_1, field_2 and state

We are using Postgres

SELECT id
FROM a
WHERE 
(field_1 = 999 OR field_2 = 876) AND state IN ('finished', 'closed')
ORDER BY created_at desc

One suggestion that I get is to split this query in two and then remove the "OR".

Another suggestion is to add some "pagination"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is going to be quite hard to optimize as written. If you phrase this as:

SELECT id
FROM ((SELECT a.*
       FROM a
       WHERE field_1 = 999 AND state IN ('finished', 'closed')
      ) UNION ALL
      (SELECT a.*
       FROM a
       WHERE field_2 = 876 AND state IN ('finished', 'closed') and field_1 <> 999
      )
     ) a
ORDER BY created_at desc;

Then Postgres can use different indexes for each subquery:

  • (field_1, state)
  • (field_2, state, field_1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...