Slow query on “UNION ALL” view

后端 未结 8 1907
伪装坚强ぢ
伪装坚强ぢ 2021-02-13 06:20

I have a DB view which basically consists of two SELECT queries with UNION ALL, like this:

CREATE VIEW v AS
SELECT time, etc. FROM t1 /         


        
相关标签:
8条回答
  • 2021-02-13 07:19

    Encountered same scenario on 11g:

    Scenario 1:

    CREATE VIEW v AS
      SELECT time, etc. FROM t1 // #1...
    

    The following query runs fast, plan looks okay:

    SELECT ... FROM v WHERE time >= ... AND time < ...
    

    Scenario 2:

    CREATE VIEW v AS
      SELECT time, etc. FROM t2 // #2...
    

    The following query runs fast, plan looks okay:

    SELECT ... FROM v WHERE time >= ... AND time < ...
    

    Scenario 3, with UNION ALL:

    CREATE VIEW v AS
      SELECT time, etc. FROM t1 // #1...
      UNION ALL
      SELECT time, etc. FROM t2 // #2...
    

    The following runs slow. Plan breaks apart t1 and t2 (which were also views) and assembles them as a big series of unions. The time filters are being applied properly on the individual components, but it is still very slow:

    SELECT ... FROM v WHERE time >= ... AND time < ...
    

    I would have been happy to just get a time in the ballpark of t1 plus t2, but it was more than double. Adding the parallel hint did the trick for me in this case. It re-arranged everything into a better plan:

    SELECT /*+ parallel */ ... FROM v WHERE time >= ... AND time < ...
    
    0 讨论(0)
  • 2021-02-13 07:22

    This seems to be a case of a pilot error. The "v" query plan selects from at least 5 different tables.

    Now, Are You sure You are connected to the right database? Maybe there are some funky search_path settings? Maybe t1 and t2 are actually views (possibly in a different schema)? Maybe You are somehow selecting from the wrong view?

    Edited after clarification:

    You are using a quite new feature called "join removal" : http://wiki.postgresql.org/wiki/What%27s_new_in_PostgreSQL_9.0#Join_Removal

    http://rhaas.blogspot.com/2010/06/why-join-removal-is-cool.html

    It appears that the feature does not kick in when union all is involved. You probably have to rewrite the view using only the required two tables.

    another edit: You appear to be using an aggregate (like "select count(*) from v" vs. "select * from v"), which could get vastly different plans in face of join removal. I guess we won't get very far without You posting the actual queries, view and table definitions and plans used...

    0 讨论(0)
提交回复
热议问题