92 points · by justinclift · 2y ago · 115 comments
SELECT * FROM TABLE FOO WHERE ORGANIZATION_ID = 10 ORDER BY CREATED_AT LIMIT 10 OFFSET 0;
Postgres sorts by created_at using an index, but uses the filter on organization_id. This organization has a million rows... without the order, the query runs in ms. In order, in seconds/minutes.
Sometimes the plan changes if you change the query offset!
For organization 10, the plane is goood, for organization 11, the plane is bad...
Change stats, add more stats, fill the void. that doesn't solve anything. The solution is to use a calc on order by , but in the end you need to create an index using Organization_id and created_at to really fix it.
I did the same test on SQLServer and SQLite, they executed the query correctly, using the correct index. I've never created an index to fix a bad plan in SQLServer, and I've used SqlServer a lot more than Postgres.
And I use a Pass database, it's impossible to install extensions...
I'm going to test this extension locally, if it works I'll convince the company to use it (by changing the database provider)
In addition to what I described there, the way you described it, it sounds like you don't have a single index that covers both columns. That may also help if I understood right.
Yes. But other databases (SQLlite, etc.) select the correct index, without the need to create an index with both columns.
create unlogged table foo (id int primary key generated by default as identity, organization_id int default floor(random()*10), created_at timestamptz default timestamp '2010-01-01' + random()*(timestamp '2020-01-01' - timestamp '2010-01-01'));
create index on foo (created_at);
create index on foo (organization_id);
alter table foo add column updated_at timestamptz null default '2010-01-01 00:00:00'::timestamp without time zone + random() * ('2020-01-01 00:00:00'::timestamp without time zone - '2010-01-01 00:00:00'::timestamp without time zone);
create index on foo (updated_at);
insert into foo (id) select generate_series(1, 1e8);
cluster foo using foo_created_at_idx;
vacuum analyze;
explain analyze select * from foo where organization_id = 1 order by updated_at limit 10;
QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=0.57..169.50 rows=10 width=24) (actual time=0.088..0.242 rows=10 loops=1)
-> Index Scan using foo_updated_at_idx on foo (cost=0.57..173267047.88 rows=10256672 width=24) (actual time=0.086..0.237 rows=10 loops=1)
Filter: (organization_id = 1)
Rows Removed by Filter: 73
Planning Time: 0.168 ms
Execution Time: 0.269 ms Limit (cost=0.42..3.26 rows=10 width=24) (actual time=0.013..0.024 rows=10 loops=1)
-> Index Scan using foo_organization_id_updated_at_idx on foo (cost=0.42..2011.50 rows=7063 width=24) (actual time=0.012..0.023 rows=10 loops=1)
Index Cond: (organization_id = 1)
Planning Time: 0.154 ms
Execution Time: 0.033 ms
Now the plan is using Index Cond, not filter. -- 1e7 entries for organization_id = 10 distributed evenly over the 10
-- years after '2020-01-01 00:00:00' as requested
insert into foo (
organization_id,
created_at,
updated_at)
select
10, --9 was the previous max organization_id so presumably 10 is OK rather than 11
generate_series('2020-01-01 00:00:00'::timestamp, '2020-01-01 00:00:00'::timestamp + interval '10 years', (interval '10 years')/1e7),
generate_series('2020-01-01 00:00:00'::timestamp, '2020-01-01 00:00:00'::timestamp + interval '10 years', (interval '10 years')/1e7);
cluster foo using foo_created_at_idx; --should be a no-op but why not
vacuum analyze; --same thing
create index on foo (updated_at) where organization_id = 10; --stats will be highly-skewed so we had better fix that
explain analyze select * from foo where organization_id = 10 order by updated_at limit 10;
QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=0.43..23.35 rows=10 width=57) (actual time=0.073..0.079 rows=10 loops=1)
-> Index Scan using foo_updated_at_idx1 on foo (cost=0.43..23495662.12 rows=10254706 width=57) (actual time=0.071..0.075 rows=10 loops=1)
Planning Time: 0.185 ms
Execution Time: 0.101 ms
BTW, SQLite was no better at solving this riddle. It also failed miserably in its query plan until I created the same partial index.What are the current values of `random_page_cost` and `seq_page_cost`?
SHOW seq_page_cost;
SHOW random_page_cost;
The default is typically 4, and in practice with modern disks you should use a lower value closer to 1.I have many other problems with the planner, this is the most absurd due to the simplicity of the query.
The optimizer simply assumes the matching rows are "uniformly" distributed, because limit is costed as linear approximation of the startup/total cost of the input node. For example, consider this made up query plan
Limit (cost=0.0..100.0 rows=10)
-> Index scan (cost=0.0...10000000.0 rows=1000000)
Filter: dept_id=10
The table may have many more rows - say, 100x more. But the optimizer assumes the rows with (dept_id=10) are distributed in the index, so it can scan the first 1/100000 if the index to get the 10 rows the limits needs. So it assumes the cost is 10*(0+10000000)/1000000.But chances are the dept_id=10 rows happen to be at the very end of the index, so the planner actually needs to scan almost the whole index, making the cost wildly incorrect.
You can verify this by looking how far the dept_id rows are in "order by created_id" results. If there are many other rows before the 10 rows you need, it's likely this.
Sadly, the optimizer is not smart enough to realize there's this risk. I agree it's an annoying robustness issue, but I don't have a good idea how to mitigate it ... I wonder what the other databases do.
Partial indexes can be really useful there, as well as order by (id+0). But it's a total hack.
I can run EXPLAIN and paste it here, but it's just one of the problems with the planner (in a very basic query), I have many other problems with it.
On the other hand, I've never had any other serious problems with Postgres. It's a very good database.
Might as well, could turn up something useful. :)
that's probably because for 11, there will be more results (say 10k), and optimizer decided that it is faster to scan already sorted index with filter, than sort 10k rows.
Logic of optimizer is usually reasonable, my problem with it is that it relies on cost config parameters, which I think by default are inadequate for modern servers, it is not clear how to set it correctly, and actual optimizer rules are not documented, but one need to look at PgSQL code to understand them.
I agree. My problem is that SQLite, an embedded database, seems to have a better Planner/Optimizer than Postgres.
Is the development of Planner/Optimizer abandoned?
> my problem with it is that it relies on cost config parameters
And I don't have access to change it, as it's a PASS database...
Postgres doesn’t automatically create indexes - I bet the others have some implicit index on organization_id, created_at. Otherwise they would be giving bad results in other cases. I don’t see why you can’t just make that index in postgres.
I did
> Postgres doesn’t automatically create indexes
Both fields have indexes (created manually). Postgres is incorrectly choosing the index in order by column, not the index in the where clause.
[1] https://github.com/babelfish-for-postgresql/babelfish-for-po...
- db will generate new plans as necessary when row counts and values change. Putting in hints makes the plan rigid likely leading to headaches down the line.
- as new Postgres comes out, it's planner will do a better job. Again forcing specific plan might force the planner into optimization that no longer is optimal.
In my experience developers almost never comeback to a query with hints to double check if hints are really needed.
Famously oracle has query hints that don't do nothing no more, that are ignored, but oracle can't remove them from query language because that would break too many existing queries.
I like Postgres stance that if query planner doesn't do a good job, then dba should first update table/column statistics, and if things are truly bad, submit but to Postgres so the query optimizer can be updated itself.
Saying all that, hints support through an extension to Postgres is a good compromise. Postgres developers don't need to bother with hints, its a third party feature. And dba/users, if they really need hints, now they have them.
That’s a very unhelpful stance when I’m having an incident in production because PG decided to use a stupid query plan. Waiting months - years for a bugfix (which might not even be backported to my PG version) is not a solution.
I agree that hints are a very dangerous thing, but they’re invaluable as an emergency measure
Before using a hint or rewriting a query to force a specific plan, I try and push the team to do these things:
1. Run `vacuum analyze` and tune the auto vacuum settings. This fixes issues surprisingly often. 2. Increase statistics on the table. 3. Tweak planner settings globally or just for the query. Stuff like `set local join_collapse_limit=1` can fix a bad plan. This is pretty similar to hinting, so not a huge argument that this is better beyond not requiring an extension.
Is this a more common occurrence that I just have not encountered before?
> - db will generate new plans as necessary when row counts and values change. Putting in hints makes the plan rigid likely leading to headaches down the line.
> - as new Postgres comes out, it's planner will do a better job. Again forcing specific plan might force the planner into optimization that no longer is optimal.
It depends what is your priority. Most production environments want to favor predictability over raw performance. I'd rather trade 10% performance degradation in average for a consistent query performance.
Even if statistics or new versions could come with 10% better plans, I prefer that my query's performance is predictable and does not experience high p90s or even worse that you risk experiencing plan flips that turn your 0.2s 10K/qps query into a 40s query.
It would be very interesting if there was some sort of system that ensured query plans don't change "randomly" but if it noticed that a new plan was expected to be better on most queries it would surface this in some interface that you could then test and approve.
Maybe it could also support gradual rollout, try this on 1% of queries first, then if it does improve performance it can be fully approved.
It would be extra cool if this was automatic. New plans could slowly be slowly rolled out by the DB and rolled back if they aren't actually better.
Many of the issues people run into with the Postgres query planner/optimizer are side effects of architectural peculiarities with no straightforward fix. Some of these issues, such as the limitations of Postgres statistics collection, have been unaddressed for decades because they are extremely difficult to address without major architectural surgery that will have its own side effects.
In my opinion, Postgres either needs to allow people to disable/bypass the query planner with hints or whatever, or commit to the difficult and unpleasant work of fixing the architecture so that these issues no longer occur. This persistent state of affairs of neither fixing the core problems nor allowing a mechanism to work around them is not user friendly. I like and use Postgres but this aspect of the project is quite broken.
The alternative is to put a disclaimer in the Postgres documentation that it should not be used for certain types of common workloads or large data models; many of these issues don't show up in force until databases become quite large.
This is a chronic source of pain in large-scale Postgres installations.
The way I see it the issues we have in query planning/optimization are largely independent of the overall architecture. It's simply a consequence of relying on statistics too much. But there's always going to be inaccuracies, because the whole point of stats is that it's a compact/lossy approximation of the data. No matter how much more statistics we might collect there will always be some details missing, until the statistics are way too large to be practical.
There are discussions about considering how "risky" a given plan is - some plan shapes may be more problematic, but I don't think anyone submitted any patch so far. But even with that would not be a perfect solution - no approach relying solely on a priori information can be.
IMHO the only way forward is to work on making the plans more robust to this kind of mistakes. But that's very hard too.
The "make it work work perfectly from just statistics" can come later, when time is more flexible. Probably on an identical non-production copy of the environment, if that shows the same performance characteristics. ;)
What's needed, then, is a benchmark suite that tests if those hints still give a better performance than a hintless query
It is certainly a bad practice, but on very particular occasions it is invaluable.
Your data model might contain obvious mistakes. Statistics can be out of date too, if e.g. a table was bulk loaded and never analyzed. `ANALYZE tablename` done. Sometimes removing unused indexes can improve things. TLDR; it's always something that you need to tune in your own database. When in doubt, the query planner is right and you are wrong. Good engineering means having the intellectual curiosity to exhaust these possibility before resorting to hints.
Hints are an extreme measure. You're basically saying that you know better than the query planner, for now until eternity, and you choose to optimize by hand. That may be the case but it requires detailed knowledge of your table and access patterns. The vast majority of misbehaving query plans just need updated statistics or a better index.
Finding out what went wrong in the query plan by looking at optimizer traces is a lot of work. I did so recently and the trace alone was 317MB.
Statistics collection is a weak spot in Postgres and query optimization relies on that information to do its job.
Nope, you just have to know it's fixing a real problem today.
Having a query regress in performance below a KPI would be worse than not taking advantage of a further optimization in the future, due to out of date hint.
> Good engineering means having the intellectual curiosity to exhaust these possibility before resorting to hints
Why is that better?
Luckily we don't have to rely on such grandiose claims. Just try it out. If you find a query that you can tune better than the planner for your data set, then it's a better outcome.
While it's great that "good engineering" exists, it often requires a bunch more time and effort than people have for the task right then.
Being inflexible and always demanding that time is taken is an extremely poor approach, and often doesn't lead to a good quality result.
Instead it often leads to the inflexible thing being retired and a more flexible alternative being used from then on.
Absolutely.
A query planner does not analyze the complete and precise solution space, none of them do. The query planner will be extremely wrong sometimes. The only logical solution is to provide a mechanism to guide the planner towards the correct solution.
I've worked with DB2, Oracle and MS SQL Server over the last 3 decades and the story is always the same, the planner is not perfect.
Yes I do know better what data is going to be in the database I am managing that some heuristic mechanism.
Still super useful when you have no other options though.
INSERT INTO tbl1 VALUES ($1, $2) \bind 'first value' 'second value' \g
https://www.postgresql.org/docs/current/app-psql.html#APP-PS...For older versions, you can do:
\set v_x 'first value'
\set v_y 'second value'
INSERT INTO tbl1 VALUES (:'v_x', :'v_y');
\set v_x 'next value'
INSERT INTO tbl1 VALUES (:'v_x', :'v_y');Isn't this what PREPARE and EXECUTE does?
The planner wasn’t particularly sophisticated in those days, nor was the data volume crushing.
But in the end, we would take all of our queries, and check their plans. We would pad the db with data until the combination of data and statistics and the planner all did what we wanted.
Once we were happy with the statistics and the results we’d reset the database with “empty” data for the customer, and never touch the statistics again.
We were mostly trying to eliminate table scans on simple queries and joins, and influencing index selection.
Beyond those resources, here are a few useful things I've learned: 1. `explain (analyze, buffers)` is useful. It will tell you about hot vs cold data. One caveat: it doesn't deduplicate the buffer hits, so 1M buffer hits could be only a few thousand unique pages. But I still find it useful especially when comparing query plans. 2. pg_buffercache. Knowing what's in the buffer allows you to optimize the long tail of queries that perform buffer reads. Sometimes rebuilding an index on an unrelated table can create space in the buffer for the data the query needs. 3. Try using dedicated covering partial indexes for high traffic queries. An index-only scan is super cheap and with the right include and where condition you can make it small and efficient.
The tips above are especially useful in Aurora, where the shared buffers are huge (there's no page cache so it's the only caching layer).
[0] https://stackoverflow.com/questions/6593765/how-to-use-index...
[1] https://stackoverflow.com/questions/309786/how-do-i-force-po... - and https://www.2ndquadrant.com/en/blog/hinting_at_postgresql/ says why Postgres devs think this is a bad feature
First because “we get bugs fixed quickly” is true but not true enough (my own experience: https://www.postgresql.org/message-id/17540-7aa1855ad5ec18b4... has not been fixed since reported 1.5y ago)
Second because all the knobs available to tune the query planner (listed in your last link) are obscure and require deep understanding of Postgres internals to make sense of them, which means that only a fraction of people understand them whereas query plans are more pedestrian. They’re also often database-scoped or session-scoped rather than query-scoped, it’s a huge risk of making things worse rather than better.
I can't find it here
https://github.com/ossc-db/pg_hint_plan/blob/master/docs/hin...
Because, the mssql WITH(INDEX()) is simple and intuitive. This hint table stuff seems complicated, and it's unclear to me if they can do the simple thing
(Note: WITH(INDEX()) is different than specifying whether you will do SeqScan or IndexScan. it's, like, in SQL we can give a name to an index or to a constraint, and one may want to be able to do IndexScan, yes, but with a specific named index)
I don't just not agree, I truly don't understand how they can take that position knowing the nature of the problem.
"The problem"=optimizing over a large space in limited time without complete info. It will never be perfect, there will always be exceptions.
The GitHub repo's wording is broken english currently though which is (probably?) worse.
Glad to see it executed