Re: [PERFORM] OLAP/reporting queries fall into nested loops over seq scans or other horrible planner choices
Gunther wrote: > > Bad choices are almost always caused by bad estimates. > > Granted, there is no way that estimates can ever be perfect. > > ... > > Looking deeper, I would say that wrongly chosen nested loop joins > > often come from an underestimate that is close to zero. > > PostgreSQL already clamps row count estimates to 1, that is, it will > > choose an estimate of 1 whenever it thinks fewer rows will be returned. > > > > Perhaps using a higher clamp like 2 would get rid of many of your > > problems, but it is a difficult gamble as it will also prevent some > > nested loop joins that would have been the best solution. > > Wow, that is very interesting! Are you saying that if PgSQL can't know > what the cardinality is, it assumes a default of 1? That would be very > slanted a guess. I would think a couple of hundred would be more > appropriate, or 10% of the average of the base tables for which it does > have statistics. I would wonder if changing 1 to 2 would make much > difference, as Seq Search over 1 to 10 tuples should generally be better > than any other approach, as long as the 1-10 tuples are already readily > available. No, it is not like that. When PostgreSQL cannot come up with a "real" estimate, it uses default selectivity estimates. See include/utils/selfuncs.h: /* * Note: the default selectivity estimates are not chosen entirely at random. * We want them to be small enough to ensure that indexscans will be used if * available, for typical table densities of ~100 tuples/page. Thus, for * example, 0.01 is not quite small enough, since that makes it appear that * nearly all pages will be hit anyway. Also, since we sometimes estimate * eqsel as 1/num_distinct, we probably want DEFAULT_NUM_DISTINCT to equal * 1/DEFAULT_EQ_SEL. */ /* default selectivity estimate for equalities such as "A = b" */ #define DEFAULT_EQ_SEL 0.005 /* default selectivity estimate for inequalities such as "A < b" */ #define DEFAULT_INEQ_SEL 0. /* default selectivity estimate for range inequalities "A > b AND A < c" */ #define DEFAULT_RANGE_INEQ_SEL 0.005 /* default selectivity estimate for pattern-match operators such as LIKE */ #define DEFAULT_MATCH_SEL 0.005 /* default number of distinct values in a table */ #define DEFAULT_NUM_DISTINCT 200 /* default selectivity estimate for boolean and null test nodes */ #define DEFAULT_UNK_SEL 0.005 #define DEFAULT_NOT_UNK_SEL (1.0 - DEFAULT_UNK_SEL) Those selectivity estimates are factors, not absolute numbers. The clamp to 1 happens when, after applying all selectivity factors, the result is less than 1, precisely to keep the optimizer from choosing a plan that would become very expensive if a branch is executed *at all*. > > Finally, even though the official line of PostgreSQL is to *not* have > > query hints, and for a number of good reasons, this is far from being > > an unanimous decision. The scales may tip at some point, though I > > personally hope that this point is not too close. > > I am glad to hear that hints are not completely ruled out by the > development team. Definitely Oracle hints are painful and should not be > replicated as is. Butmay be I can nudge your (and others') personal > tastes with the following. Didn't work for me. Your hints look just like what Oracle does. There have been better proposals that aim at fixing the selectivity estimates, e.g. "multiply your estimate for this join by three". > In my Aqua > Data Studio, if I put the set statement before the select statement, the > combined statement doesn't return any results. May be I am doing > something wrong. If there is a way, then I would ave what I need. Check the SQL statements that are generated by your Aqua Data Studio! Yours, Laurenz Albe -- Sent via pgsql-performance mailing list (pgsql-performance@postgresql.org) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-performance
Re: [PERFORM] OLAP/reporting queries fall into nested loops over seq scans or other horrible planner choices
Thanks you for your thoughtful reply, Laurenz (funny that the people interested in this topic are named Laurent and Laurenz :) PostgreSQL doesn't have a way to tell if a query is an OLAP query running against a star schema or a regular OLTP query, it will treat both in the same fashion. right, of course, and I would not want to go down that road. There OLAP vs. OLTP are not just two cut and dry options, and neither is "star schema" but one way in which to lay out a simple data model. The real world is always more complex than such cut and dry choices However, it is not true that PostgreSQL "perfers nested loops". Sometimes a nested loop join is the only sane and efficient way to process a query ... of course, it's not preferring NLs deliberately, but it happens awfully often (and not just with PgSQL, same problems I have had with Oracle over the years). Bad choices are almost always caused by bad estimates. Granted, there is no way that estimates can ever be perfect. ... Looking deeper, I would say that wrongly chosen nested loop joins often come from an underestimate that is close to zero. PostgreSQL already clamps row count estimates to 1, that is, it will choose an estimate of 1 whenever it thinks fewer rows will be returned. Perhaps using a higher clamp like 2 would get rid of many of your problems, but it is a difficult gamble as it will also prevent some nested loop joins that would have been the best solution. Wow, that is very interesting! Are you saying that if PgSQL can't know what the cardinality is, it assumes a default of 1? That would be very slanted a guess. I would think a couple of hundred would be more appropriate, or 10% of the average of the base tables for which it does have statistics. I would wonder if changing 1 to 2 would make much difference, as Seq Search over 1 to 10 tuples should generally be better than any other approach, as long as the 1-10 tuples are already readily available. Finally, even though the official line of PostgreSQL is to *not* have query hints, and for a number of good reasons, this is far from being an unanimous decision. The scales may tip at some point, though I personally hope that this point is not too close. I am glad to hear that hints are not completely ruled out by the development team. Definitely Oracle hints are painful and should not be replicated as is. Butmay be I can nudge your (and others') personal tastes with the following. You suggested this: One pragmatic solution would be to wrap every query that you know to be an OLAP query with BEGIN; SET LOCAL enable_nestloop=off; SELECT ... COMMIT; I would also like to put the set enable_nestloop = false statement into a combined statement, but when I do it in a transaction like you showed, it would not work for a normal PreparedStatement just expecting a ResultSet, or at least I haven't been able to make that work. In my Aqua Data Studio, if I put the set statement before the select statement, the combined statement doesn't return any results. May be I am doing something wrong. If there is a way, then I would ave what I need. If not, I think it might be an easy thing to add. We already have different scopes of these optimizer parameters like enable_nestloop 1. the system wide scope 2. a session wide scope and I see no reason why one could not just add a non-disruptive syntax form to change these parameters on a statement-wide scope. By all means in a comment. Why not --! set enable_nestloop = false --! set work_mem = '20 MB' SELECT * FROM ; something like that. It would not be a big deal, no completely new obscure hint syntax. And may be, if that is possible so far, then why not add a CTE scope as well: WITH Foo AS ( --! set enable_nestloop = false SELECT * FROM ... INNER JOIN ... INNER JOIN ... INNER JOIN ... ... ) , Bar AS ( SELECT * FROM Foo INNER JOIN IndexedTable USING(a, b, c) ) SELECT * FROM Bar ... ; this would keep the nestloop off for the CTE Foo with that complex join but allow it to be used for the CTE Bar or the ultimate query. I think these features should be relatively easy to add without causing SQL compatibility issue and also not opening a can of worms with obscure hint features that need a lot of work to implement correctly. But while we are at dreaming up solution, I think materialized indexed sub-plans would also be a nice ting, especially when dealing with CTEs. This could be controlled manually to begin with: WITH Foo AS ( --! set enable_nestloop = false SELECT * FROM ... INNER JOIN ... INNER JOIN ... INNER JOIN ... ... ) MATERIALIZE INDEX ON(a, b, c) , Bar AS ( SELECT * FROM Foo INNER JOIN IndexedTable USING(a, b, c) ) SELECT * FROM Bar ... ; And of course if we don't want to disturb SQL syntax, the "materialize index on ..." clause could be in a --! comment. But then, to dream on, PgSQL could make sub-query plans a temporary table and add indexes that it needs for it on the fly, because a
Re: [PERFORM] OLAP/reporting queries fall into nested loops over seq scans or other horrible planner choices
Thanks for your support Laurent. I have an idea on one thing you said: Just adding to your voice. I recently experienced the same issue with a complex multi-table view, including pivots, and was surprised to see all the nested loops everywhere and here is the clue for me: in spite of indices being available. I would say that sometimes indexes are detrimental. If you don't need them for other reasons, you might want to not have them. And without the index, the Nested Loop strategy might not be chosen. But that is a side-issue, because it can often not be avoided. Just saying in case it might help. I also found the opposite now. In the query that made me "blow the lid" and "complain" here, my team decided to add an index and that did not get rid of Nested Loops but at least made the inner table access indexed rather than a table scan and the performance ended up OK. But it's not always predictable, and these indexes could trap the planner into sub-optimal solutions still. I think there is an opportunity for a PgSQL query plan extension, especially wen dealing with CTE (WITH-clauses), PgSQL could make them a temporary table and add indexes that it needs for it on the fly, because after it has done one pass over the inner loop sequential scan it knows perfectly well how many rows it has, and knowing how many more iterations are coming from the sub-query that's driving the Nested Loop, it could decide that it's much faster to put an index on the nested relation, temporarily materialized. Or it could even decide to change it's plan mid-way and do the Hash Join. This is why I had always dreamed that the PgSQL optimizer had some easy API where one could plug in experimental strategies. I personally am extremely efficient with XSLT for complex intelligent algorithms, and I dream of a PgSQL query plan structure exposed as XML which an XSLT plugin could then process to edit the plan. People could experiment with awesome intelligent new strategies based on statistics gathered along the way of the execution. regards, -Gunther -- Sent via pgsql-performance mailing list (pgsql-performance@postgresql.org) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-performance
Re: [PERFORM] OLAP/reporting queries fall into nested loops over seq scans or other horrible planner choices
Gunther wrote: > But there > is one thing that keeps bothering me both with Oracle and PgSQL. And > that is the preference for Nested Loops. [...] > But the issue is bulk searches, reports, and any analytic queries > scenarios. In those queries Nested Loops are almost always a bad choice, > even if there is an index. In over 20 years of working with RDBMs this > has been my unfailing heuristics. A report runs slow? Look at plan, is > there a Nested Loop? Yes? Squash it! And the report runs 10x faster > instantaneously. [...] > If you can set enable_nestloop off and the Hash Join is chosen and the > performance goes from 1 hour of 100% CPU to 10 seconds completion time, > then something is deadly wrong. [...] > The point is that Nested Loops should never be chosen except in index > lookup situations or may be memory constraints. > > How can I prevent it on a query by query scope? I cannot set > enable_nestloop = off because one query will be for a full report, wile > another one might have indexed constraints running in the same session, > and I don't want to manage side effects and remember to set > enable_nestloop parameter on and off. > > There must be a way to tell the optimizer to penalize nested loops to > make them the last resort. In Oracle there are those infamous hints, but > they don't always work either (or it is easy to make mistakes that you > get no feedback about). > > Is there any chance PgSQL can get something like a hint feature? PostgreSQL doesn't have a way to tell if a query is an OLAP query running against a star schema or a regular OLTP query, it will treat both in the same fashion. I also have had to deal with wrongly chosen nested loop joins, and testing a query with "enable_nestloop=off" is one of the first things to try in my experience. However, it is not true that PostgreSQL "perfers nested loops". Sometimes a nested loop join is the only sane and efficient way to process a query, and removing that capability would be just as bad a disaster as you are experiencing with your OLAP queries. Bad choices are almost always caused by bad estimates. Granted, there is no way that estimates can ever be perfect. So what could be done? One pragmatic solution would be to wrap every query that you know to be an OLAP query with BEGIN; SET LOCAL enable_nestloop=off; SELECT ... COMMIT; Looking deeper, I would say that wrongly chosen nested loop joins often come from an underestimate that is close to zero. PostgreSQL already clamps row count estimates to 1, that is, it will choose an estimate of 1 whenever it thinks fewer rows will be returned. Perhaps using a higher clamp like 2 would get rid of many of your problems, but it is a difficult gamble as it will also prevent some nested loop joins that would have been the best solution. Finally, even though the official line of PostgreSQL is to *not* have query hints, and for a number of good reasons, this is far from being an unanimous decision. The scales may tip at some point, though I personally hope that this point is not too close. Yours, Laurenz Albe -- Sent via pgsql-performance mailing list (pgsql-performance@postgresql.org) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-performance
Re: [PERFORM] OLAP/reporting queries fall into nested loops over seq scans or other horrible planner choices
> -Original Message- > From: pgsql-performance-ow...@postgresql.org [mailto:pgsql-performance- > ow...@postgresql.org] On Behalf Of Gunther > Sent: Wednesday, November 01, 2017 20:29 > To: pgsql-performance@postgresql.org > Subject: [PERFORM] OLAP/reporting queries fall into nested loops over seq > scans or other horrible planner choices > > Hi, this is Gunther, have been with PgSQL for decades, on an off this list. > Haven't been on for a long time making my way just fine. But there is one > thing > that keeps bothering me both with Oracle and PgSQL. And that is the > preference for Nested Loops. > > Over the years the archives have questions about Nested Loops being chosen > over Hash Joins. But the responses seem too specific to the people's queries, > ask many questions, make them post the query plans, and often end up > frustrating with suggestions to change the data model or to add an index and > stuff like that. > > One should not have to go into that personal detail. > > There are some clear boundaries that a smart database should just never cross. > > Especially with OLAP queries. Think a database that is fine for OLTP, has > indexes and the index based accesses for a few records joined with a dozen > other tables all with indexes is no problem. If you fall into a Seq Scan > scenario > or unwanted Hash Join, you usually forgot to add an index or forgot to put > index > columns into your join or other constraints. Such are novice questions and we > should be beyond that. > > But the issue is bulk searches, reports, and any analytic queries scenarios. > In > those queries Nested Loops are almost always a bad choice, even if there is an > index. In over 20 years of working with RDBMs this has been my unfailing > heuristics. A report runs slow? Look at plan, is there a Nested Loop? Yes? > Squash it! And the report runs 10x faster instantaneously. > > So, all the more troublesome is if any database system (here PgSQL) would > ever fall into a Nested Loop trap with CPU spinning at 100% for several > minutes, with a Nested Loop body of anything from a Seq Scan or worse with a > cardinality of anything over 10 or 100. Nested Loops of Nested Loops or Nested > Loops of other complex query plan fragments should be a no-no and chosen > only as an absolute last resort when the system cannot find enough memory, > even then disk based merge sort should be better, i.e., Nested Loops should > never be chosen. Period. > > If you can set enable_nestloop off and the Hash Join is chosen and the > performance goes from 1 hour of 100% CPU to 10 seconds completion time, > then something is deadly wrong. And it doesn't matter to me if I should have > re-written my query in some funny ways or tweaked my data model, these are > all unacceptable options when you have a complex system with hybrid > OLTP/OLAP uses. Don't tell me to de-normalize. I know I can materialize joins > in tables which I can then use again in joins to save time. But that is not > the > point here. > > And I don't think tweaking optimizer statistics is the solution either. > Because optimizer statistics quickly become worthless when your criteria get > more complex. > > The point is that Nested Loops should never be chosen except in index lookup > situations or may be memory constraints. > > How can I prevent it on a query by query scope? I cannot set enable_nestloop = > off because one query will be for a full report, wile another one might have > indexed constraints running in the same session, and I don't want to manage > side effects and remember to set enable_nestloop parameter on and off. > > There must be a way to tell the optimizer to penalize nested loops to make > them the last resort. In Oracle there are those infamous hints, but they don't > always work either (or it is easy to make mistakes that you get no feedback > about). > > Is there any chance PgSQL can get something like a hint feature? Or is there a > way to use postgresql.conf to penalize nested loops so that they would only > ever > be chosen in the most straight-forward situations as with query parameters > that are indexed? I know I need to have sufficient work_mem, but if you can > set > enable_nestloop = off and you get the desired Hash Join, there is obviously > sufficient work_mem, so that isn't the answer either. > > Thanks for listening to my rant. > > regards, > -Gunther > > > > -- > Sent via pgsql-performance mailing list (pgsql-performance@postgresql.org) > To make changes to your subscription: > http://www.postgresql.org/mailpref/pgsql-performance [Laurent Hasson] Hello Gunther, Just adding to your
[PERFORM] OLAP/reporting queries fall into nested loops over seq scans or other horrible planner choices
Hi, this is Gunther, have been with PgSQL for decades, on an off this list. Haven't been on for a long time making my way just fine. But there is one thing that keeps bothering me both with Oracle and PgSQL. And that is the preference for Nested Loops. Over the years the archives have questions about Nested Loops being chosen over Hash Joins. But the responses seem too specific to the people's queries, ask many questions, make them post the query plans, and often end up frustrating with suggestions to change the data model or to add an index and stuff like that. One should not have to go into that personal detail. There are some clear boundaries that a smart database should just never cross. Especially with OLAP queries. Think a database that is fine for OLTP, has indexes and the index based accesses for a few records joined with a dozen other tables all with indexes is no problem. If you fall into a Seq Scan scenario or unwanted Hash Join, you usually forgot to add an index or forgot to put index columns into your join or other constraints. Such are novice questions and we should be beyond that. But the issue is bulk searches, reports, and any analytic queries scenarios. In those queries Nested Loops are almost always a bad choice, even if there is an index. In over 20 years of working with RDBMs this has been my unfailing heuristics. A report runs slow? Look at plan, is there a Nested Loop? Yes? Squash it! And the report runs 10x faster instantaneously. So, all the more troublesome is if any database system (here PgSQL) would ever fall into a Nested Loop trap with CPU spinning at 100% for several minutes, with a Nested Loop body of anything from a Seq Scan or worse with a cardinality of anything over 10 or 100. Nested Loops of Nested Loops or Nested Loops of other complex query plan fragments should be a no-no and chosen only as an absolute last resort when the system cannot find enough memory, even then disk based merge sort should be better, i.e., Nested Loops should never be chosen. Period. If you can set enable_nestloop off and the Hash Join is chosen and the performance goes from 1 hour of 100% CPU to 10 seconds completion time, then something is deadly wrong. And it doesn't matter to me if I should have re-written my query in some funny ways or tweaked my data model, these are all unacceptable options when you have a complex system with hybrid OLTP/OLAP uses. Don't tell me to de-normalize. I know I can materialize joins in tables which I can then use again in joins to save time. But that is not the point here. And I don't think tweaking optimizer statistics is the solution either. Because optimizer statistics quickly become worthless when your criteria get more complex. The point is that Nested Loops should never be chosen except in index lookup situations or may be memory constraints. How can I prevent it on a query by query scope? I cannot set enable_nestloop = off because one query will be for a full report, wile another one might have indexed constraints running in the same session, and I don't want to manage side effects and remember to set enable_nestloop parameter on and off. There must be a way to tell the optimizer to penalize nested loops to make them the last resort. In Oracle there are those infamous hints, but they don't always work either (or it is easy to make mistakes that you get no feedback about). Is there any chance PgSQL can get something like a hint feature? Or is there a way to use postgresql.conf to penalize nested loops so that they would only ever be chosen in the most straight-forward situations as with query parameters that are indexed? I know I need to have sufficient work_mem, but if you can set enable_nestloop = off and you get the desired Hash Join, there is obviously sufficient work_mem, so that isn't the answer either. Thanks for listening to my rant. regards, -Gunther -- Sent via pgsql-performance mailing list (pgsql-performance@postgresql.org) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-performance