AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / dba / Perguntas / 337320
Accepted
ankush chauhan
ankush chauhan
Asked: 2024-02-28 21:21:29 +0800 CST2024-02-28 21:21:29 +0800 CST 2024-02-28 21:21:29 +0800 CST

Como fazer esta consulta postgresql usar apenas índice composto? Alguma sugestão

  • 772

Consulta:

with firstData as
(select rm.display_name as register, br.createdat, br.status, br.id as runid
from bad_run br 
inner join bad_master bm on bm.id = br.badmasterid
inner join regis_master rm on rm.id = bm.registerid
where rm.display_name in ('abc', 'pqr')
order by br.createdat desc limit 100)

select fi.runid,
            (SELECT count(*) FROM bigTable b 
            WHERE b.runid=fi.runid AND action = 'Add'  and type = 'BANK') as add,
            (SELECT count(*) FROM bigTable b 
            WHERE b.runid=fi.runid AND action = 'Modify' and type = 'BANK') as modify,
            (SELECT count(*) FROM bigTable b 
            WHERE b.runid=fi.runid AND action = 'Delete' and type = 'BANK') as delete,
            (SELECT count(*) FROM bigTable b 
            WHERE b.runid=fi.runid AND action is null and type = 'BANK') as pending,
            (SELECT count(*) FROM bigTable b 
            WHERE b.runid=fi.runid AND (status = 'FAILED' or status = 'Failed') and type = 'BANK') as fail
from firstData fi 

Detalhes do índice:

 INDEX composite_1_idx ON public.bigTable USING btree (runid, action, type) WHERE (runid IS NOT NULL)

 INDEX composite_2_idx ON public.bigTable USING btree (runid, status, type) WHERE (runid IS NOT NULL)

 INDEX runid_idx ON public.bigTable USING btree (runid) WHERE (runid IS NOT NULL)

Detalhes da tabela:

TABLE bigTable (
    id SERIAL PRIMARY KEY,
    createdAt TIMESTAMPTZ,
    registerId BIGINT REFERENCES bank(id),
    status TEXT,
    runid BIGINT REFERENCES customer(id)
)

Problema:


It supposed to use index only scan for all scenario (Pending, Add, failed) 

It is only using index only scan for (delete, modify)   

portion of Query:
select fi.runid,
            (SELECT count(*) FROM bigTable b 
            WHERE b.runid=fi.runid AND action = 'Add'  and type = 'BANK') as add,
            (SELECT count(*) FROM bigTable b 
            WHERE b.runid=fi.runid AND action = 'Modify' and type = 'BANK') as modify,
            (SELECT count(*) FROM bigTable b 
            WHERE b.runid=fi.runid AND action = 'Delete' and type = 'BANK') as delete,
            (SELECT count(*) FROM bigTable b 
            WHERE b.runid=fi.runid AND action is null and type = 'BANK') as pending,
            (SELECT count(*) FROM bigTable b 
            WHERE b.runid=fi.runid AND (status = 'FAILED' or status = 'Failed') and type = 'BANK') as fail
from firstData fi 
    

Plano de execução:


Subquery Scan on fi  (cost=79.27..21812.52 rows=100 width=44) (actual time=3.117..111.762 rows=100 loops=1)
  ->  Limit  (cost=79.27..79.52 rows=100 width=76) (actual time=2.119..2.194 rows=100 loops=1)
        ->  Sort  (cost=79.27..79.90 rows=250 width=76) (actual time=2.118..2.170 rows=100 loops=1)
              Sort Key: br.createdat DESC
              Sort Method: top-N heapsort  Memory: 30kB
              ->  Hash Join  (cost=2.84..69.72 rows=250 width=76) (actual time=0.093..1.630 rows=2500 loops=1)
                    Hash Cond: (br.badmasterid = bm.id)
                    ->  Seq Scan on bad_run br  (cost=0.00..55.00 rows=2500 width=20) (actual time=0.017..0.253 rows=2500 loops=1)
                    ->  Hash  (cost=2.79..2.79 rows=4 width=4) (actual time=0.063..0.065 rows=40 loops=1)
                          Buckets: 1024  Batches: 1  Memory Usage: 10kB
                          ->  Hash Join  (cost=1.27..2.79 rows=4 width=4) (actual time=0.045..0.058 rows=40 loops=1)
                                Hash Cond: (bm.registerid = rm.id)
                                ->  Seq Scan on bad_master bm  (cost=0.00..1.40 rows=40 width=12) (actual time=0.009..0.012 rows=40 loops=1)
                                ->  Hash  (cost=1.25..1.25 rows=2 width=4) (actual time=0.023..0.024 rows=20 loops=1)
                                      Buckets: 1024  Batches: 1  Memory Usage: 9kB
                                      ->  Seq Scan on regis_master rm  (cost=0.00..1.25 rows=2 width=4) (actual time=0.011..0.016 rows=20 loops=1)
                                            Filter: (display_name = ANY ('{abc,pqr}'::text[]))
  SubPlan 1
    ->  Aggregate  (cost=11549..11549.60 rows=1 width=8) (actual time=38.433..38.43 rows=1 loops=100)
          ->  Index Scan using runid_idx on bigTable b  (cost=0.56..11475.63 rows=29585 width=0) (actual time=0.008..24.212 rows=17888 loops=100)
                Index Cond: ((runid = fi.runid))
                Filter ((type='BANK'::text) AND (action'Add'::text))
                Rows Removed by Filter: 17428
  SubPlan 2
    ->  Aggregate  (cost=19.86..19.87 rows=1 width=8) (actual time=0.120..0.120 rows=1 loops=100)
          ->  Index Only Scan using composite_1_idx on bigTable b_1  (cost=0.56..18.33 rows=612 width=0) (actual time=0.012..0.081 rows=598 loops=100)
                Index Cond: ((runid = fi.runid) AND (action = 'Modify'::text) AND (type = 'BANK'::text))
                Heap Fetches: 0
  SubPlan 3
    ->  Aggregate  (cost=19.61..19.62 rows=1 width=8) (actual time=0.122..0.122 rows=1 loops=100)
          ->  Index Only Scan using composite_1_idx on bigTable b_2  (cost=0.56..18.11 rows=602 width=0) (actual time=0.011..0.082 rows=603 loops=100)
                Index Cond: ((runid = fi.runid) AND (action = 'Delete'::text) AND (type = 'BANK'::text))
                Heap Fetches: 0
  SubPlan 4
    ->  Aggregate  (cost=11549..11549.60 rows=1 width=8) (actual time=38.433..38.43 rows=1 loops=100)
          ->  Index Scan using runid_idx on bigTable b  (cost=0.56..11475.63 rows=29585 width=0) (actual time=0.008..24.212 rows=17888 loops=100)
                  Index Cond: ((runid = fi.runid))
                  Filter ((action is null)AND (type='BANK'::text) )
                  Rows Removed by Filter: 1
  SubPlan 5
    ->  Aggregate  (cost=11549..11549.60 rows=1 width=8) (actual time=38.433..38.43 rows=1 loops=100)
          ->  Index Scan using runid_idx on bigTable b_4  (cost=0.56..11475.63 rows=29585 width=0) (actual time=0.008..24.212 rows=17888 loops=100)
                Index Cond: ((runid = fi.runid))
                Filter: (type='BANK'::text) AND ((status = 'FAILED'::text) OR (status = 'Failed'::text)))
                Rows Removed by Filter: 12730
Planning Time: 2.223 ms
Execution Time: 12282.836 ms              

postgresql
  • 1 1 respostas
  • 48 Views

1 respostas

  • Voted
  1. Best Answer
    Laurenz Albe
    2024-02-28T22:43:02+08:002024-02-28T22:43:02+08:00

    As subconsultas da SELECTlista são o que custa caro; eles são executados para cada linha de resultado.

    Use o poder dos agregados filtrados:

    SELECT fi.runid,
           count(*) FILTER (WHERE action = 'Add' and type = 'BANK') AS add,
           count(*) FILTER (WHERE action = 'Modify' and type = 'BANK') AS modify,
           count(*) FILTER (WHERE action = 'Delete' and type = 'BANK') AS modify,
           count(*) FILTER (WHERE status IN ('FAILED', 'Failed') and type = 'BANK') AS fail,
    from firstData fi
       LEFT JOIN bigTable b ON b.runid=fi.runid;
    
    • 0

relate perguntas

  • Posso ativar o PITR depois que o banco de dados foi usado

  • Práticas recomendadas para executar a replicação atrasada do deslocamento de tempo

  • Os procedimentos armazenados impedem a injeção de SQL?

  • Sequências Biológicas do UniProt no PostgreSQL

  • Qual é a diferença entre a replicação do PostgreSQL 9.0 e o Slony-I?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host

    • 12 respostas
  • Marko Smith

    Como fazer a saída do sqlplus aparecer em uma linha?

    • 3 respostas
  • Marko Smith

    Selecione qual tem data máxima ou data mais recente

    • 3 respostas
  • Marko Smith

    Como faço para listar todos os esquemas no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Listar todas as colunas de uma tabela especificada

    • 5 respostas
  • Marko Smith

    Como usar o sqlplus para se conectar a um banco de dados Oracle localizado em outro host sem modificar meu próprio tnsnames.ora

    • 4 respostas
  • Marko Smith

    Como você mysqldump tabela (s) específica (s)?

    • 4 respostas
  • Marko Smith

    Listar os privilégios do banco de dados usando o psql

    • 10 respostas
  • Marko Smith

    Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Como faço para listar todos os bancos de dados e tabelas usando o psql?

    • 7 respostas
  • Martin Hope
    Jin conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host 2014-12-02 02:54:58 +0800 CST
  • Martin Hope
    Stéphane Como faço para listar todos os esquemas no PostgreSQL? 2013-04-16 11:19:16 +0800 CST
  • Martin Hope
    Mike Walsh Por que o log de transações continua crescendo ou fica sem espaço? 2012-12-05 18:11:22 +0800 CST
  • Martin Hope
    Stephane Rolland Listar todas as colunas de uma tabela especificada 2012-08-14 04:44:44 +0800 CST
  • Martin Hope
    haxney O MySQL pode realizar consultas razoavelmente em bilhões de linhas? 2012-07-03 11:36:13 +0800 CST
  • Martin Hope
    qazwsx Como posso monitorar o andamento de uma importação de um arquivo .sql grande? 2012-05-03 08:54:41 +0800 CST
  • Martin Hope
    markdorison Como você mysqldump tabela (s) específica (s)? 2011-12-17 12:39:37 +0800 CST
  • Martin Hope
    Jonas Como posso cronometrar consultas SQL usando psql? 2011-06-04 02:22:54 +0800 CST
  • Martin Hope
    Jonas Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL? 2011-05-28 00:33:05 +0800 CST
  • Martin Hope
    Jonas Como faço para listar todos os bancos de dados e tabelas usando o psql? 2011-02-18 00:45:49 +0800 CST

Hot tag

sql-server mysql postgresql sql-server-2014 sql-server-2016 oracle sql-server-2008 database-design query-performance sql-server-2017

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve