7

What are effective ways of writing faster queries specifically in Postgres? Please do not include generally good database practices (eg use indexes or normalization). I'm looking for hints like derived tables work faster than subqueries or using python string functions seems faster than the pgsql string functions. Ideally, this list would include real-world examples and advice.

Thanks.

3 Answers 3

8

The only unbreakable rule I have found so far is that there are no unbreakable rules.

Sometimes subquery is faster, sometimes join is faster. Sometimes you want plpgsql, sometimes you want some other pl/*.

The most usually adequate advises:

  1. Make sure you vacuum and analyze (turn on autovacuum)
  2. use explain analyze and learn to read its output well
  3. play with the database. try to do things weird way. usually - it doesn't help. but sometimes it does, and you learn new tricks.
Sign up to request clarification or add additional context in comments.

Comments

7

Make sure to vacuum periodically. The current autovacuum system does a pretty good job of this in most cases, but it can still be helpful to run a full manual vacuum periodically (in our case this happens approximately once per year).

Indexes are only used reliably if stats are available for the table. Make sure that a vacuum --analyze is run after any major changes to a table (tons of inserts/deletes) to insure that indexes are selected properly.

The default Postgres configuration is optimized for a system with relatively modest resources and slow disks. If your system has faster disks (possibly), a faster CPU (probably), or a lot more RAM (almost certainly), then make sure to tune the various parameters based upon that. The main thing is to increase buffer sizes, but if you have extremely fast disks (especially SSDs), it would be a good idea to lower the cost estimates for seek times as well.

I've also had a few experiences with slightly slow joins in fairly complex queries, but these are much more difficult to generalize. Just generally it helps to be more explicit with the query than what may be required in a db with a more sophisticated query optimizer (eg, Oracle or DB2).

1 Comment

Yes I've noticed auto vacuum really doesn't not work too well with systems that have large data loads daily. We at least "analyze" daily.
1

Checkout all links on this page, since you are doing the actual tuning it's best that you know what all the options mean and when does any of them apply to your configuration.

https://wiki.postgresql.org/wiki/Performance_Optimization

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.