bddnf=# show all;
              name               |                setting                |                                         description
---------------------------------+---------------------------------------+----------------------------------------------------------------------------------------------
 add_missing_from                | off                                   | Automatically adds missing table references to FROM clauses.
 archive_command                 | unset                                 | WAL archiving command.
 australian_timezones            | off                                   | Interprets ACST, CST, EST, and SAT as Australian time zones.
 authentication_timeout          | 60                                    | Sets the maximum time in seconds to complete client authentication.
 autovacuum                      | off                                   | Starts the autovacuum subprocess.
 autovacuum_analyze_scale_factor | 0.2                                   | Number of tuple inserts, updates or deletes prior to analyze as a fraction of reltuples.
 autovacuum_analyze_threshold    | 500                                   | Minimum number of tuple inserts, updates or deletes prior to analyze.
 autovacuum_naptime              | 60                                    | Time to sleep between autovacuum runs, in seconds.
 autovacuum_vacuum_cost_delay    | -1                                    | Vacuum cost delay in milliseconds, for autovacuum.
 autovacuum_vacuum_cost_limit    | -1                                    | Vacuum cost amount available before napping, for autovacuum.
 autovacuum_vacuum_scale_factor  | 0.4                                   | Number of tuple updates or deletes prior to vacuum as a fraction of reltuples.
 autovacuum_vacuum_threshold     | 1000                                  | Minimum number of tuple updates or deletes prior to vacuum.
 bgwriter_all_maxpages           | 5                                     | Background writer maximum number of all pages to flush per round
 bgwriter_all_percent            | 0.333                                 | Background writer percentage of all buffers to flush per round
 bgwriter_delay                  | 200                                   | Background writer sleep time between rounds in milliseconds
 bgwriter_lru_maxpages           | 5                                     | Background writer maximum number of LRU pages to flush per round
 bgwriter_lru_percent            | 1                                     | Background writer percentage of LRU buffers to flush per round
 block_size                      | 8192                                  | Shows size of a disk block
 bonjour_name                    | unset                                 | Sets the Bonjour broadcast service name.
 check_function_bodies           | on                                    | Check function bodies during CREATE FUNCTION.
 checkpoint_segments             | 3                                     | Sets the maximum distance in log segments between automatic WAL checkpoints.
 checkpoint_timeout              | 300                                   | Sets the maximum time in seconds between automatic WAL checkpoints.
 checkpoint_warning              | 30                                    | Logs if filling of checkpoint segments happens more frequently than this (in seconds).
 client_encoding                 | SQL_ASCII                             | Sets the client's character set encoding.
 client_min_messages             | notice                                | Sets the message levels that are sent to the client.
 commit_delay                    | 0                                     | Sets the delay in microseconds between transaction commit and flushing WAL to disk.
 commit_siblings                 | 5                                     | Sets the minimum concurrent open transactions before performing commit_delay.
 config_file                     | /var/lib/pgsql/data/postgresql.conf   | Sets the server's main configuration file.
 constraint_exclusion            | off                                   | Enables the planner to use constraints to optimize queries.
 cpu_index_tuple_cost            | 0.001                                 | Sets the planner's estimate of processing cost for each index tuple (row) during index scan.
 cpu_operator_cost               | 0.0025                                | Sets the planner's estimate of processing cost of each operator in WHERE.
 cpu_tuple_cost                  | 0.01                                  | Sets the planner's estimate of the cost of processing each tuple (row).
 custom_variable_classes         | unset                                 | Sets the list of known custom variable classes.
 data_directory                  | /var/lib/pgsql/data                   | Sets the server's data directory.
 DateStyle                       | ISO, MDY                              | Sets the display format for date and time values.
 db_user_namespace               | off                                   | Enables per-database user names.
 deadlock_timeout                | 1000                                  | The time in milliseconds to wait on lock before checking for deadlock.
 debug_pretty_print              | off                                   | Indents parse and plan tree displays.
 debug_print_parse               | off                                   | Prints the parse tree to the server log.
 debug_print_plan                | off                                   | Prints the execution plan to server log.
 debug_print_rewritten           | off                                   | Prints the parse tree after rewriting to server log.
 default_statistics_target       | 1000                                  | Sets the default statistics target.
 default_tablespace              | unset                                 | Sets the default tablespace to create tables and indexes in.
 default_transaction_isolation   | read committed                        | Sets the transaction isolation level of each new transaction.
 default_transaction_read_only   | off                                   | Sets the default read-only status of new transactions.
 default_with_oids               | off                                   | Create new tables with OIDs by default.
 dynamic_library_path            | $libdir                               | Sets the path for dynamically loadable modules.
 effective_cache_size            | 16000                                 | Sets the planner's assumption about size of the disk cache.
 enable_bitmapscan               | on                                    | Enables the planner's use of bitmap-scan plans.
 enable_hashagg                  | on                                    | Enables the planner's use of hashed aggregation plans.
 enable_hashjoin                 | on                                    | Enables the planner's use of hash join plans.
 enable_indexscan                | on                                    | Enables the planner's use of index-scan plans.
 enable_mergejoin                | on                                    | Enables the planner's use of merge join plans.
 enable_nestloop                 | on                                    | Enables the planner's use of nested-loop join plans.
 enable_seqscan                  | on                                    | Enables the planner's use of sequential-scan plans.
 enable_sort                     | on                                    | Enables the planner's use of explicit sort steps.
 enable_tidscan                  | on                                    | Enables the planner's use of TID scan plans.
 escape_string_warning           | off                                   | Warn about backslash escapes in ordinary string literals.
 explain_pretty_print            | on                                    | Uses the indented output format for EXPLAIN VERBOSE.
 external_pid_file               | unset                                 | Writes the postmaster PID to the specified file.
 extra_float_digits              | 0                                     | Sets the number of digits displayed for floating-point values.
 from_collapse_limit             | 8                                     | Sets the FROM-list size beyond which subqueries are not collapsed.
 fsync                           | on                                    | Forces synchronization of updates to disk.
 full_page_writes                | on                                    | Writes full pages to WAL when first modified after a checkpoint.
 geqo                            | on                                    | Enables genetic query optimization.
 geqo_effort                     | 5                                     | GEQO: effort is used to set the default for other GEQO parameters.
 geqo_generations                | 0                                     | GEQO: number of iterations of the algorithm.
 geqo_pool_size                  | 0                                     | GEQO: number of individuals in the population.
 geqo_selection_bias             | 2                                     | GEQO: selective pressure within the population.
 geqo_threshold                  | 12                                    | Sets the threshold of FROM items beyond which GEQO is used.
 hba_file                        | /var/lib/pgsql/data/pg_hba.conf       | Sets the server's "hba" configuration file
 ident_file                      | /var/lib/pgsql/data/pg_ident.conf     | Sets the server's "ident" configuration file
 integer_datetimes               | off                                   | Datetimes are integer based.
 join_collapse_limit             | 8                                     | Sets the FROM-list size beyond which JOIN constructs are not flattened.
 krb_caseins_users               | off                                   | Sets whether Kerberos user names should be treated as case-insensitive.
 krb_server_hostname             | unset                                 | Sets the hostname of the Kerberos server.
 krb_server_keyfile              | FILE:/etc/sysconfig/pgsql/krb5.keytab | Sets the location of the Kerberos server key file.
 krb_srvname                     | postgres                              | Sets the name of the Kerberos service.
 lc_collate                      | pt_BR                                 | Shows the collation order locale.
 lc_ctype                        | pt_BR                                 | Shows the character classification and case conversion locale.
 lc_messages                     | pt_BR                                 | Sets the language in which messages are displayed.
 lc_monetary                     | pt_BR                                 | Sets the locale for formatting monetary amounts.
 lc_numeric                      | pt_BR                                 | Sets the locale for formatting numbers.
 lc_time                         | pt_BR                                 | Sets the locale for formatting date and time values.
 listen_addresses                | 10.200.27.40,10.200.27.37             | Sets the host name or IP address(es) to listen to.
 log_connections                 | off                                   | Logs each successful connection.
 log_destination                 | stderr                                | Sets the destination for server log output.
 log_directory                   | pg_log                                | Sets the destination directory for log files.
 log_disconnections              | off                                   | Logs end of a session, including duration.
 log_duration                    | off                                   | Logs the duration of each completed SQL statement.
 log_error_verbosity             | default                               | Sets the verbosity of logged messages.
 log_executor_stats              | off                                   | Writes executor performance statistics to the server log.
 log_filename                    | postgresql-%Y-%m-%d_%H%M%S.log        | Sets the file name pattern for log files.
 log_hostname                    | off                                   | Logs the host name in the connection logs.
 log_line_prefix                 | unset                                 | Controls information prefixed to each log line
 log_min_duration_statement      | -1                                    | Sets the minimum execution time in milliseconds above which statements will be logged.
 log_min_error_statement         | panic                                 | Causes all statements generating error at or above this level to be logged.
 log_min_messages                | notice                                | Sets the message levels that are logged.
 log_parser_stats                | off                                   | Writes parser performance statistics to the server log.
 log_planner_stats               | off                                   | Writes planner performance statistics to the server log.
 log_rotation_age                | 1440                                  | Automatic log file rotation will occur after N minutes
 log_rotation_size               | 0                                     | Automatic log file rotation will occur after N kilobytes
 log_statement                   | none                                  | Sets the type of statements logged.
 log_statement_stats             | off                                   | Writes cumulative performance statistics to the server log.
 log_truncate_on_rotation        | on                                    | Truncate existing log files of same name during log rotation.
 maintenance_work_mem            | 512000                                | Sets the maximum memory to be used for maintenance operations.
 max_connections                 | 10                                    | Sets the maximum number of concurrent connections.
 max_files_per_process           | 1000                                  | Sets the maximum number of simultaneously open files for each server process.
 max_fsm_pages                   | 70000                                 | Sets the maximum number of disk pages for which free space is tracked.
 max_fsm_relations               | 1000                                  | Sets the maximum number of tables and indexes for which free space is tracked.
 max_function_args               | 100                                   | Shows the maximum number of function arguments.
 max_identifier_length           | 63                                    | Shows the maximum identifier length
 max_index_keys                  | 32                                    | Shows the maximum number of index keys.
 max_locks_per_transaction       | 64                                    | Sets the maximum number of locks per transaction.
 max_prepared_transactions       | 5                                     | Sets the maximum number of simultaneously prepared transactions.
 max_stack_depth                 | 2048                                  | Sets the maximum stack depth, in kilobytes.
 password_encryption             | on                                    | Encrypt passwords.
 port                            | 5432                                  | Sets the TCP port the server listens on.
 pre_auth_delay                  | 0                                     | no description available
 preload_libraries               | unset                                 | Lists shared libraries to preload into server.
 random_page_cost                | 4                                     | Sets the planner's estimate of the cost of a nonsequentially fetched disk page.
 redirect_stderr                 | on                                    | Start a subprocess to capture stderr output into log files.
 regex_flavor                    | advanced                              | Sets the regular expression "flavor".
 search_path                     | $user,public                          | Sets the schema search order for names that are not schema-qualified.
 server_encoding                 | SQL_ASCII                             | Sets the server (database) character set encoding.
 server_version                  | 8.1.3                                 | Shows the server version.
 shared_buffers                  | 2048                                  | Sets the number of shared memory buffers used by the server.
 silent_mode                     | off                                   | Runs the server silently.
 sql_inheritance                 | on                                    | Causes subtables to be included by default in various commands.
 ssl                             | off                                   | Enables SSL connections.
 standard_conforming_strings     | off                                   | '...' strings treat backslashes literally.
 statement_timeout               | 0                                     | Sets the maximum allowed duration (in milliseconds) of any statement.
 stats_block_level               | off                                   | Collects block-level statistics on database activity.
 stats_command_string            | off                                   | Collects statistics about executing commands.
 stats_reset_on_server_start     | off                                   | Zeroes collected statistics on server restart.
 stats_row_level                 | off                                   | Collects row-level statistics on database activity.
 stats_start_collector           | on                                    | Starts the server statistics-collection subprocess.
 superuser_reserved_connections  | 2                                     | Sets the number of connection slots reserved for superusers.
 syslog_facility                 | LOCAL0                                | Sets the syslog "facility" to be used when syslog enabled.
 syslog_ident                    | postgres                              | Sets the program name used to identify PostgreSQL messages in syslog.
 tcp_keepalives_count            | 9                                     | Maximum number of TCP keepalive retransmits.
 tcp_keepalives_idle             | 7200                                  | Seconds between issuing TCP keepalives.
 tcp_keepalives_interval         | 75                                    | Seconds between TCP keepalive retransmits.
 temp_buffers                    | 1000                                  | Sets the maximum number of temporary buffers used by each session.
 TimeZone                        | BRSV3                                 | Sets the time zone for displaying and interpreting time stamps.
 trace_notify                    | off                                   | Generates debugging output for LISTEN and NOTIFY.
 trace_sort                      | off                                   | Emit information about resource usage in sorting.
 transaction_isolation           | read committed                        | Sets the current transaction's isolation level.
 transaction_read_only           | off                                   | Sets the current transaction's read-only status.
 transform_null_equals           | off                                   | Treats "expr=NULL" as "expr IS NULL".
 unix_socket_directory           | unset                                 | Sets the directory where the Unix-domain socket will be created.
 unix_socket_group               | unset                                 | Sets the owning group of the Unix-domain socket.
 unix_socket_permissions         | 511                                   | Sets the access permissions of the Unix-domain socket.
 vacuum_cost_delay               | 0                                     | Vacuum cost delay in milliseconds.
 vacuum_cost_limit               | 200                                   | Vacuum cost amount available before napping.
 vacuum_cost_page_dirty          | 20                                    | Vacuum cost for a page dirtied by vacuum.
 vacuum_cost_page_hit            | 1                                     | Vacuum cost for a page found in the buffer cache.
 vacuum_cost_page_miss           | 10                                    | Vacuum cost for a page not found in the buffer cache.
 wal_buffers                     | 8                                     | Sets the number of disk-page buffers in shared memory for WAL.
 wal_sync_method                 | fdatasync                             | Selects the method used for forcing WAL updates out to disk.
 work_mem                        | 512000                                | Sets the maximum memory to be used for query workspaces.
 zero_damaged_pages              | off                                   | Continues processing past damaged page headers.
(162 registros)

bddnf=#
bddnf=#

bddnf=# \di
                                            Lista de relaes
 Esquema |                       Nome                        |  Tipo  |   Dono   |        Tabela
---------+---------------------------------------------------+--------+----------+-----------------------
 public  | agrupamento_erro_pkey                             | ndice | postgres | agrupamento_erro
 public  | arquivo_processado_pkey                           | ndice | postgres | arquivo_processado
 public  | cadastro_pkey                                     | ndice | postgres | cadastro
 public  | declaracao_pkey                                   | ndice | postgres | declaracao
 public  | empresa_pkey                                      | ndice | postgres | empresa
 public  | erro_pkey                                         | ndice | postgres | erro
 public  | fki_cadastro_id_declaracao_fkey                   | ndice | postgres | cadastro
 public  | fki_cadastro_id_empresa_fkey                      | ndice | postgres | cadastro
 public  | fki_declaracao_id_arquivo_fkey                    | ndice | postgres | declaracao
 public  | fki_declaracao_id_empresa_fkey                    | ndice | postgres | declaracao
 public  | fki_erro_id_agrupamento_fkey                      | ndice | postgres | erro
 public  | fki_erro_id_arquivo_fkey                          | ndice | postgres | erro
 public  | fki_erro_id_declaracao_fkey                       | ndice | postgres | erro
 public  | fki_erro_id_erro_agrupador_fkey                   | ndice | postgres | erro
 public  | fki_erro_id_tipo_erro_fkey                        | ndice | postgres | erro
 public  | fki_item_nota_id_nf_fkey                          | ndice | postgres | item_nota
 public  | fki_item_nota_id_produto_fkey                     | ndice | postgres | item_nota
 public  | fki_nota_fiscal_id_cadastro_fkey                  | ndice | postgres | nota_fiscal
 public  | fki_processamento_arquivo_id_arquivo_fkey         | ndice | postgres | processamento_arquivo
 public  | fki_produto_id_produto_oficial_fkey               | ndice | postgres | produto
 public  | fki_tipo_produto_empresa_id_empresa_fkey          | ndice | postgres | tipo_produto_empresa
 public  | fki_tipo_produto_empresa_id_tipo_uso_produto_fkey | ndice | postgres | tipo_produto_empresa
 public  | fki_uso_produto_id_produto_fkey                   | ndice | postgres | uso_produto
 public  | fki_uso_produto_id_tipo_uso_produto_fkey          | ndice | postgres | uso_produto
 public  | idx_cnpj_empresa                                  | ndice | postgres | empresa
 public  | idx_co_mercadoria_nao_oficial                     | ndice | postgres | produto
 public  | idx_co_ncm                                        | ndice | postgres | produto
 public  | idx_co_produto_in359                              | ndice | postgres | produto
 public  | idx_co_produto_in445                              | ndice | postgres | produto
 public  | idx_co_produto_in63                               | ndice | postgres | produto
 public  | idx_destinatario                                  | ndice | postgres | nota_fiscal
 public  | idx_dh_fim_proc                                   | ndice | postgres | processamento_arquivo
 public  | idx_dh_inicio_proc                                | ndice | postgres | processamento_arquivo
 public  | idx_dh_recepcao_legal                             | ndice | postgres | declaracao
 public  | idx_dh_recepcao_trans                             | ndice | postgres | declaracao
 public  | idx_dt_emissao                                    | ndice | postgres | nota_fiscal
 public  | idx_dt_referencia                                 | ndice | postgres | declaracao
 public  | idx_in_oficial                                    | ndice | postgres | produto
 public  | idx_no_arquivo                                    | ndice | postgres | arquivo_processado
 public  | idx_nu_bytes_arq                                  | ndice | postgres | arquivo_processado
 public  | idx_nu_linha                                      | ndice | postgres | declaracao
 public  | idx_nu_serie_nf                                   | ndice | postgres | nota_fiscal
 public  | idx_nu_severidade                                 | ndice | postgres | erro
 public  | idx_va_total                                      | ndice | postgres | item_nota
 public  | idx_versao_layout                                 | ndice | postgres | declaracao
 public  | item_nota_pkey                                    | ndice | postgres | item_nota
 public  | linha_arquivo_pkey                                | ndice | postgres | linha_arquivo
 public  | nota_fiscal_pkey                                  | ndice | postgres | nota_fiscal
 public  | pkteste                                           | ndice | postgres | teste
 public  | processamento_arquivo_pkey                        | ndice | postgres | processamento_arquivo
 public  | produto_pkey                                      | ndice | postgres | produto
 public  | prorrogacao_entrega_pkey                          | ndice | postgres | prorrogacao_entrega
 public  | tipo_erro_pkey                                    | ndice | postgres | tipo_erro
 public  | tipo_produto_empresa_pkey                         | ndice | postgres | tipo_produto_empresa
 public  | tipo_uso_produto_pkey                             | ndice | postgres | tipo_uso_produto
 public  | uso_produto_pkey                                  | ndice | postgres | uso_produto
(56 registros)

bddnf=#
bddnf=# cluster;
CLUSTER
bddnf=# vacuum analyze;
VACUUM
bddnf=#

bddnf=# explain analyze select count(ID_ITEM) from DECLARACAO DECL  inner join CADASTRO CAD on (CAD.ID_DECLARACAO=DECL.ID_DECLARACAO)     inner join NOTA_FISCAL NF on (NF.ID_CADASTRO=CAD.ID_CADASTRO) inner join ITEM_NOTA INF on (INF.ID_NF=NF.ID_NF) where DECL.ID_ARQUIVO=1;
                                                                                            QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=163047.99..163048.00 rows=1 width=4) (actual time=9108.288..9108.289 rows=1 loops=1)
   ->  Hash Join  (cost=60942.42..160232.66 rows=1126134 width=4) (actual time=3444.495..8432.343 rows=1151043 loops=1)
         Hash Cond: ("outer".id_nf = "inner".id_nf)
         ->  Seq Scan on item_nota inf  (cost=0.00..64427.45 rows=2360145 width=8) (actual time=0.048..2335.431 rows=2360145 loops=1)
         ->  Hash  (cost=59181.89..59181.89 rows=704212 width=4) (actual time=3443.537..3443.537 rows=719746 loops=1)
               ->  Merge Join  (cost=1688.76..59181.89 rows=704212 width=4) (actual time=86.426..2827.899 rows=719746 loops=1)
                     Merge Cond: ("outer".id_cadastro = "inner".id_cadastro)
                     ->  Index Scan using fki_nota_fiscal_id_cadastro_fkey on nota_fiscal nf  (cost=0.00..43240.71 rows=1475883 width=8) (actual time=0.093..905.268 rows=719747 loops=1)
                     ->  Sort  (cost=1688.76..1707.24 rows=7391 width=4) (actual time=86.321..526.967 rows=722613 loops=1)
                           Sort Key: cad.id_cadastro
                           ->  Hash Join  (cost=175.67..1213.83 rows=7391 width=4) (actual time=18.410..69.542 rows=7467 loops=1)
                                 Hash Cond: ("outer".id_declaracao = "inner".id_declaracao)
                                 ->  Seq Scan on cadastro cad  (cost=0.00..731.90 rows=15490 width=8) (actual time=0.021..25.918 rows=15490 loops=1)
                                 ->  Hash  (cost=164.00..164.00 rows=4667 width=4) (actual time=18.346..18.346 rows=4667 loops=1)
                                       ->  Index Scan using fki_declaracao_id_arquivo_fkey on declaracao decl  (cost=0.00..164.00 rows=4667 width=4) (actual time=0.069..12.942 rows=4667 loops=1)
                                             Index Cond: (id_arquivo = 1)
 Total runtime: 9116.481 ms
(17 registros)

bddnf=# 
bddnf=# explain analyze select * from DECLARACAO DECL  inner join CADASTRO CAD on (CAD.ID_DECLARACAO=DECL.ID_DECLARACAO)     inner join NOTA_FISCAL NF on (NF.ID_CADASTRO=CAD.ID_CADASTRO) inner join ITEM_NOTA INF on (INF.ID_NF=NF.ID_NF) where DECL.ID_ARQUIVO=1;
                                                                                           QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Hash Join  (cost=60942.42..161275.24 rows=1126134 width=739) (actual time=9321.880..21373.666 rows=1151043 loops=1)
   Hash Cond: ("outer".id_nf = "inner".id_nf)
   ->  Seq Scan on item_nota inf  (cost=0.00..64427.45 rows=2360145 width=152) (actual time=8.663..5004.388 rows=2360145 loops=1)
   ->  Hash  (cost=59181.89..59181.89 rows=704212 width=587) (actual time=9312.388..9312.388 rows=719746 loops=1)
         ->  Merge Join  (cost=1688.76..59181.89 rows=704212 width=587) (actual time=753.682..5281.909 rows=719746 loops=1)
               Merge Cond: ("outer".id_cadastro = "inner".id_cadastro)
               ->  Index Scan using fki_nota_fiscal_id_cadastro_fkey on nota_fiscal nf  (cost=0.00..43240.71 rows=1475883 width=188) (actual time=59.561..1808.476 rows=719747 loops=1)
               ->  Sort  (cost=1688.76..1707.24 rows=7391 width=399) (actual time=694.100..1127.239 rows=722613 loops=1)
                     Sort Key: cad.id_cadastro
                     ->  Hash Join  (cost=175.67..1213.83 rows=7391 width=399) (actual time=296.375..622.416 rows=7467 loops=1)
                           Hash Cond: ("outer".id_declaracao = "inner".id_declaracao)
                           ->  Seq Scan on cadastro cad  (cost=0.00..731.90 rows=15490 width=295) (actual time=34.450..329.357 rows=15490 loops=1)
                           ->  Hash  (cost=164.00..164.00 rows=4667 width=104) (actual time=261.807..261.807 rows=4667 loops=1)
                                 ->  Index Scan using fki_declaracao_id_arquivo_fkey on declaracao decl  (cost=0.00..164.00 rows=4667 width=104) (actual time=48.357..256.646 rows=4667 loops=1)
                                       Index Cond: (id_arquivo = 1)
 Total runtime: 22061.654 ms
(16 registros)

bddnf=# explain analyze update NOTA_FISCAL  set VA_TOTAL_ITENSDNF = (select sum(ITEM_NOTA.VA_TOTAL) from ITEM_NOTA where ITEM_NOTA.ID_NF = NOTA_FISCAL.ID_NF)  where exists (select CAD.ID_CADASTRO from DECLARACAO DE, CADASTRO CAD where DE.ID_ARQUIVO in (10) and CAD.ID_DECLARACAO = DE.ID_DECLARACAO  and CAD.ID_CADASTRO = NOTA_FISCAL.ID_CADASTRO  ) and (select sum(ITEM_NOTA.VA_TOTAL) from ITEM_NOTA where ITEM_NOTA.ID_NF = NOTA_FISCAL.ID_NF) < 999999999999;
                                                                             QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Seq Scan on nota_fiscal  (cost=0.00..16335303.11 rows=245980 width=182) (actual time=208.651..63223.749 rows=172 loops=1)
   Filter: ((subplan) AND ((subplan) < 999999999999::numeric))
   SubPlan
     ->  Aggregate  (cost=3.04..3.05 rows=1 width=12) (actual time=0.017..0.018 rows=1 loops=172)
           ->  Index Scan using fki_item_nota_id_nf_fkey on item_nota  (cost=0.00..3.03 rows=2 width=12) (actual time=0.009..0.010 rows=1 loops=172)
                 Index Cond: (id_nf = $0)
     ->  Hash Join  (cost=4.25..7.49 rows=1 width=4) (actual time=0.040..0.040 rows=0 loops=1475883)
           Hash Cond: ("outer".id_declaracao = "inner".id_declaracao)
           ->  Index Scan using fki_declaracao_id_arquivo_fkey on declaracao de  (cost=0.00..3.16 rows=12 width=4) (actual time=0.004..0.016 rows=12 loops=1475883)
                 Index Cond: (id_arquivo = 10)
           ->  Hash  (cost=4.25..4.25 rows=1 width=8) (actual time=0.010..0.010 rows=1 loops=1475883)
                 ->  Index Scan using cadastro_pkey on cadastro cad  (cost=0.00..4.25 rows=1 width=8) (actual time=0.005..0.007 rows=1 loops=1475883)
                       Index Cond: (id_cadastro = $1)
     ->  Aggregate  (cost=3.04..3.05 rows=1 width=12) (actual time=0.012..0.012 rows=1 loops=172)
           ->  Index Scan using fki_item_nota_id_nf_fkey on item_nota  (cost=0.00..3.03 rows=2 width=12) (actual time=0.005..0.007 rows=1 loops=172)
                 Index Cond: (id_nf = $0)
 Total runtime: 63271.215 ms
(17 registros)

bddnf=#
bddnf=# explain analyze select INF.* from ITEM_NOTA INF inner join NOTA_FISCAL NF on (NF.ID_NF=INF.ID_NF) inner join CADASTRO CAD on  (CAD.ID_CADASTRO=NF.ID_CADASTRO) inner join DECLARACAO DE on (DE.ID_DECLARACAO=CAD.ID_DECLARACAO) where DE.ID_ARQUIVO=3;
                                                                           QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------------------------------
 Nested Loop  (cost=0.00..1480.58 rows=697 width=152) (actual time=0.116..0.383 rows=24 loops=1)
   ->  Nested Loop  (cost=0.00..149.16 rows=436 width=4) (actual time=0.103..0.183 rows=22 loops=1)
         ->  Nested Loop  (cost=0.00..38.71 rows=10 width=4) (actual time=0.025..0.083 rows=7 loops=1)
               ->  Index Scan using fki_declaracao_id_arquivo_fkey on declaracao de  (cost=0.00..3.08 rows=6 width=4) (actual time=0.012..0.021 rows=6 loops=1)
                     Index Cond: (id_arquivo = 3)
               ->  Index Scan using fki_cadastro_id_declaracao_fkey on cadastro cad  (cost=0.00..5.91 rows=2 width=8) (actual time=0.005..0.007 rows=1 loops=6)
                     Index Cond: ("outer".id_declaracao = cad.id_declaracao)
         ->  Index Scan using fki_nota_fiscal_id_cadastro_fkey on nota_fiscal nf  (cost=0.00..8.62 rows=194 width=8) (actual time=0.005..0.009 rows=3 loops=7)
               Index Cond: ("outer".id_cadastro = nf.id_cadastro)
   ->  Index Scan using fki_item_nota_id_nf_fkey on item_nota inf  (cost=0.00..3.03 rows=2 width=152) (actual time=0.005..0.006 rows=1 loops=22)
         Index Cond: ("outer".id_nf = inf.id_nf)
 Total runtime: 0.508 ms
(12 registros)

bddnf=#
bddnf=# explain analyze update NOTA_FISCAL  set VA_TOTAL_ITENSDNF = (select sum(ITEM_NOTA.VA_TOTAL) from ITEM_NOTA where ITEM_NOTA.ID_NF = NOTA_FISCAL.ID_NF)  where ID_NF in (select NF2.ID_NF from DECLARACAO DE inner join CADASTRO CAD on (CAD.ID_DECLARACAO=DE.ID_DECLARACAO) inner join NOTA_FISCAL  NF2 on (NF2.ID_CADASTRO=CAD.ID_CADASTRO) where DE.ID_ARQUIVO in (1) );
                                                                                        QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Hash IN Join  (cost=56111.01..1154271.68 rows=339191 width=182) (actual time=3910.730..157754.341 rows=719746 loops=1)
   Hash Cond: ("outer".id_nf = "inner".id_nf)
   ->  Seq Scan on nota_fiscal  (cost=0.00..38531.45 rows=1475945 width=182) (actual time=0.048..14606.755 rows=1475883 loops=1)
   ->  Hash  (cost=55263.03..55263.03 rows=339191 width=4) (actual time=3881.754..3881.754 rows=719746 loops=1)
         ->  Hash Join  (cost=2270.08..55263.03 rows=339191 width=4) (actual time=102.163..3259.302 rows=719746 loops=1)
               Hash Cond: ("outer".id_cadastro = "inner".id_cadastro)
               ->  Seq Scan on nota_fiscal nf2  (cost=0.00..38531.45 rows=1475945 width=8) (actual time=0.003..1558.547 rows=1475883 loops=1)
               ->  Hash  (cost=2251.61..2251.61 rows=7391 width=4) (actual time=102.135..102.135 rows=7467 loops=1)
                     ->  Hash Join  (cost=175.67..2251.61 rows=7391 width=4) (actual time=40.469..94.866 rows=7467 loops=1)
                           Hash Cond: ("outer".id_declaracao = "inner".id_declaracao)
                           ->  Seq Scan on cadastro cad  (cost=0.00..1519.61 rows=32161 width=8) (actual time=0.458..35.315 rows=15490 loops=1)
                           ->  Hash  (cost=164.00..164.00 rows=4667 width=4) (actual time=39.987..39.987 rows=4667 loops=1)
                                 ->  Index Scan using fki_declaracao_id_arquivo_fkey on declaracao de  (cost=0.00..164.00 rows=4667 width=4) (actual time=8.702..34.440 rows=4667 loops=1)
                                       Index Cond: (id_arquivo = 1)
   SubPlan
     ->  Aggregate  (cost=3.04..3.05 rows=1 width=12) (actual time=0.183..0.183 rows=1 loops=719746)
           ->  Index Scan using fki_item_nota_id_nf_fkey on item_nota  (cost=0.00..3.03 rows=2 width=12) (actual time=0.157..0.177 rows=2 loops=719746)
                 Index Cond: (id_nf = $0)
 Total runtime: 746551.492 ms
(19 registros)

bddnf=#

bddnf=# explain analyze select count(distinct NF.ID_NF ) as contagem, DE.AM_REFERENCIA as campo from DECLARACAO DE  inner join CADASTRO CAD on (CAD.ID_DECLARACAO=DE.ID_DECLARACAO) inner join NOTA_FISCAL NF on (NF.ID_CADASTRO=CAD.ID_CADASTRO) inner join EMPRESA EMP on (EMP.ID_EMPRESA=DE.ID_EMPRESA) inner join ARQUIVO_PROCESSADO ARQ on (ARQ.ID_ARQUIVO=DE.ID_ARQUIVO) group by DE.AM_REFERENCIA order by DE.AM_REFERENCIA;
                                                                                      QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 GroupAggregate  (cost=262825.58..273357.29 rows=21 width=8) (actual time=8570.712..11360.890 rows=18 loops=1)
   ->  Sort  (cost=262825.58..266336.06 rows=1404193 width=8) (actual time=8570.602..9396.506 rows=1475883 loops=1)
         Sort Key: de.am_referencia
         ->  Merge Join  (cost=4321.78..119448.27 rows=1404193 width=8) (actual time=186.105..6183.130 rows=1475883 loops=1)
               Merge Cond: ("outer".id_cadastro = "inner".id_cadastro)
               ->  Index Scan using fki_nota_fiscal_id_cadastro_fkey on nota_fiscal nf  (cost=0.00..86775.90 rows=2915445 width=8) (actual time=15.781..2237.235 rows=1475883 loops=1)
               ->  Sort  (cost=4321.78..4360.50 rows=15490 width=8) (actual time=170.309..1024.737 rows=1483001 loops=1)
                     Sort Key: cad.id_cadastro
                     ->  Hash Join  (cost=765.21..3243.75 rows=15490 width=8) (actual time=86.010..146.987 rows=15490 loops=1)
                           Hash Cond: ("outer".id_declaracao = "inner".id_declaracao)
                           ->  Seq Scan on cadastro cad  (cost=0.00..1519.61 rows=32161 width=8) (actual time=0.918..30.352 rows=15490 loops=1)
                           ->  Hash  (cost=740.76..740.76 rows=9781 width=8) (actual time=85.057..85.057 rows=9781 loops=1)
                                 ->  Hash Join  (cost=91.16..740.76 rows=9781 width=8) (actual time=10.202..71.432 rows=9781 loops=1)
                                       Hash Cond: ("outer".id_empresa = "inner".id_empresa)
                                       ->  Hash Join  (cost=1.15..430.67 rows=9781 width=12) (actual time=0.141..39.093 rows=9781 loops=1)
                                             Hash Cond: ("outer".id_arquivo = "inner".id_arquivo)
                                             ->  Seq Scan on declaracao de  (cost=0.00..282.81 rows=9781 width=16) (actual time=0.043..14.650 rows=9781 loops=1)
                                             ->  Hash  (cost=1.12..1.12 rows=12 width=4) (actual time=0.072..0.072 rows=12 loops=1)
                                                   ->  Seq Scan on arquivo_processado arq  (cost=0.00..1.12 rows=12 width=4) (actual time=0.035..0.051 rows=12 loops=1)
                                       ->  Hash  (cost=80.61..80.61 rows=3761 width=4) (actual time=10.043..10.043 rows=3761 loops=1)
                                             ->  Seq Scan on empresa emp  (cost=0.00..80.61 rows=3761 width=4) (actual time=0.028..5.605 rows=3761 loops=1)
 Total runtime: 11466.031 ms
(22 registros)

bddnf=#

bddnf=# explain analyze update NOTA_FISCAL set VA_TOTAL_ITENSDNF = (select sum(ITEM_NOTA.VA_TOTAL) from ITEM_NOTA  where ITEM_NOTA.ID_NF = NOTA_FISCAL.ID_NF) where NOTA_FISCAL.ID_CADASTRO  in (select CAD.ID_CADASTRO from DECLARACAO DE inner join CADASTRO CAD on (CAD.ID_DECLARACAO=DE.ID_DECLARACAO) where DE.ID_ARQUIVO in (10)  )  and (select sum(ITEM_NOTA.VA_TOTAL) from ITEM_NOTA  where  ITEM_NOTA.ID_NF = NOTA_FISCAL.ID_NF) < 999999999999;
                                                                            QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Nested Loop  (cost=74.46..24386.95 rows=574 width=182) (actual time=0.217..8.771 rows=172 loops=1)
   ->  HashAggregate  (cost=74.46..74.65 rows=19 width=4) (actual time=0.153..0.173 rows=14 loops=1)
         ->  Nested Loop  (cost=0.00..74.41 rows=19 width=4) (actual time=0.025..0.134 rows=14 loops=1)
               ->  Index Scan using fki_declaracao_id_arquivo_fkey on declaracao de  (cost=0.00..3.16 rows=12 width=4) (actual time=0.011..0.026 rows=12 loops=1)
                     Index Cond: (id_arquivo = 10)
               ->  Index Scan using fki_cadastro_id_declaracao_fkey on cadastro cad  (cost=0.00..5.91 rows=2 width=8) (actual time=0.004..0.006 rows=1 loops=12)
                     Index Cond: (cad.id_declaracao = "outer".id_declaracao)
   ->  Index Scan using fki_nota_fiscal_id_cadastro_fkey on nota_fiscal  (cost=0.00..1185.89 rows=128 width=182) (actual time=0.023..0.347 rows=12 loops=14)
         Index Cond: (nota_fiscal.id_cadastro = "outer".id_cadastro)
         Filter: ((subplan) < 999999999999::numeric)
         SubPlan
           ->  Aggregate  (cost=3.04..3.05 rows=1 width=12) (actual time=0.015..0.016 rows=1 loops=172)
                 ->  Index Scan using fki_item_nota_id_nf_fkey on item_nota  (cost=0.00..3.03 rows=2 width=12) (actual time=0.008..0.010 rows=1 loops=172)
                       Index Cond: (id_nf = $0)
   SubPlan
     ->  Aggregate  (cost=3.04..3.05 rows=1 width=12) (actual time=0.014..0.015 rows=1 loops=172)
           ->  Index Scan using fki_item_nota_id_nf_fkey on item_nota  (cost=0.00..3.03 rows=2 width=12) (actual time=0.007..0.009 rows=1 loops=172)
                 Index Cond: (id_nf = $0)
 Total runtime: 71.189 ms
(19 registros)

bddnf=#
bddnf=# explain analyze select DE.ID_DECLARACAO, PROD.ID_PRODUTO_OFICIAL, NF.CO_CNPJ_CPF_DESTINATARIO, sum(INF.VA_TOTAL) as va_total, count(INF.ID_ITEM) as qtdItens, count(distinct NF.ID_NF) as qtdNotas from DECLARACAO DE inner join CADASTRO CAD on (CAD.ID_DECLARACAO=DE.ID_DECLARACAO) inner join NOTA_FISCAL NF on (NF.ID_CADASTRO=CAD.ID_CADASTRO) inner join ITEM_NOTA INF on (INF.ID_NF=NF.ID_NF) inner join PRODUTO PROD on (PROD.ID_PRODUTO=INF.ID_PRODUTO) group by DE.ID_DECLARACAO, PROD.ID_PRODUTO_OFICIAL, NF.CO_CNPJ_CPF_DESTINATARIO order by  DE.ID_DECLARACAO, PROD.ID_PRODUTO_OFICIAL, NF.CO_CNPJ_CPF_DESTINATARIO;
                                                                                                QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 GroupAggregate  (cost=353306.58..393092.44 rows=1136739 width=43) (actual time=48139.444..56129.953 rows=534261 loops=1)
   ->  Sort  (cost=353306.58..356148.42 rows=1136739 width=43) (actual time=48139.303..49518.977 rows=2360145 loops=1)
         Sort Key: de.id_declaracao, prod.id_produto_oficial, nf.co_cnpj_cpf_destinatario
         ->  Hash Join  (cost=122523.32..238970.70 rows=1136739 width=43) (actual time=20657.461..33634.368 rows=2360145 loops=1)
               Hash Cond: ("outer".id_produto = "inner".id_produto)
               ->  Hash Join  (cost=122518.32..221914.61 rows=1136739 width=43) (actual time=20647.140..29881.773 rows=2360145 loops=1)
                     Hash Cond: ("outer".id_nf = "inner".id_nf)
                     ->  Seq Scan on item_nota inf  (cost=0.00..64427.45 rows=2360145 width=24) (actual time=6.745..4314.709 rows=2360145 loops=1)
                     ->  Hash  (cost=119007.32..119007.32 rows=1404402 width=23) (actual time=20638.800..20638.800 rows=1475883 loops=1)
                           ->  Merge Join  (cost=3863.83..119007.32 rows=1404402 width=23) (actual time=727.633..19046.674 rows=1475883 loops=1)
                                 Merge Cond: ("outer".id_cadastro = "inner".id_cadastro)
                                 ->  Index Scan using fki_nota_fiscal_id_cadastro_fkey on nota_fiscal nf  (cost=0.00..86788.67 rows=2915879 width=23) (actual time=49.214..14321.034 rows=1475883 loops=1)
                                 ->  Sort  (cost=3863.83..3902.55 rows=15490 width=8) (actual time=678.405..1551.261 rows=1483001 loops=1)
                                       Sort Key: cad.id_cadastro
                                       ->  Hash Join  (cost=307.26..2785.80 rows=15490 width=8) (actual time=361.588..655.265 rows=15490 loops=1)
                                             Hash Cond: ("outer".id_declaracao = "inner".id_declaracao)
                                             ->  Seq Scan on cadastro cad  (cost=0.00..1519.61 rows=32161 width=8) (actual time=20.267..285.276 rows=15490 loops=1)
                                             ->  Hash  (cost=282.81..282.81 rows=9781 width=4) (actual time=341.279..341.279 rows=9781 loops=1)
                                                   ->  Seq Scan on declaracao de  (cost=0.00..282.81 rows=9781 width=4) (actual time=38.907..333.181 rows=9781 loops=1)
               ->  Hash  (cost=4.60..4.60 rows=160 width=8) (actual time=10.310..10.310 rows=160 loops=1)
                     ->  Seq Scan on produto prod  (cost=0.00..4.60 rows=160 width=8) (actual time=9.330..10.175 rows=160 loops=1)
 Total runtime: 56790.091 ms
(22 registros)

bddnf=#
bddnf=# explain analyze update CADASTRO set IN_CADASTRO_MAIS_ATUAL = case when CADASTRO.ID_CADASTRO=  (select max(CAD2.ID_CADASTRO) from CADASTRO CAD2 inner join DECLARACAO DECL on (DECL.ID_DECLARACAO=CAD2.ID_DECLARACAO) where CAD2.ID_EMPRESA=CADASTRO.ID_EMPRESA  and DECL.AM_REFERENCIA =  (select max(DEC2.AM_REFERENCIA) from DECLARACAO DEC2 where DEC2.IN_FOI_RETIFICADA=0 and        1         in (select CAD3.ID_CADASTRO from CADASTRO CAD3  where CAD3.ID_DECLARACAO=DEC2.ID_DECLARACAO and CAD3.ID_EMPRESA=CADASTRO.ID_EMPRESA )  )and DECL.IN_FOI_RETIFICADA=0 )then 1 else 0 end;
                                                                                     QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Seq Scan on cadastro  (cost=0.00..943416695.62 rows=32161 width=299) (actual time=2416.931..1281281.624 rows=15490 loops=1)
   SubPlan
     ->  Aggregate  (cost=29334.12..29334.13 rows=1 width=4) (actual time=82.695..82.695 rows=1 loops=15490)
           InitPlan
             ->  Aggregate  (cost=29296.77..29296.78 rows=1 width=4) (actual time=82.590..82.591 rows=1 loops=15490)
                   ->  Seq Scan on declaracao dec2  (cost=0.00..29284.64 rows=4850 width=4) (actual time=82.559..82.579 rows=0 loops=15490)
                         Filter: ((in_foi_retificada = 0) AND (subplan))
                         SubPlan
                           ->  Index Scan using fki_cadastro_id_declaracao_fkey on cadastro cad3  (cost=0.00..5.92 rows=1 width=4) (actual time=0.007..0.007 rows=0 loops=150253000)
                                 Index Cond: (id_declaracao = $0)
                                 Filter: (id_empresa = $1)
           ->  Nested Loop  (cost=0.00..37.34 rows=1 width=4) (actual time=82.691..82.691 rows=0 loops=15490)
                 ->  Index Scan using fki_cadastro_id_empresa_fkey on cadastro cad2  (cost=0.00..17.26 rows=4 width=8) (actual time=0.022..0.038 rows=5 loops=15490)
                       Index Cond: (id_empresa = $1)
                 ->  Index Scan using declaracao_pkey on declaracao decl  (cost=0.00..5.01 rows=1 width=4) (actual time=18.105..18.105 rows=0 loops=70706)
                       Index Cond: (decl.id_declaracao = "outer".id_declaracao)
                       Filter: ((am_referencia = $3) AND (in_foi_retificada = 0))
 Total runtime: 1283207.744 ms
(18 registros)

bddnf=#






bddnf=# explain analyze update CADASTRO set IN_CADASTRO_MAIS_ATUAL = case when CADASTRO.ID_CADASTRO=  (select max(CAD2.ID_CADASTRO) from CADASTRO CAD2 inner join DECLARACAO DECL on (DECL.ID_DECLARACAO=CAD2.ID_DECLARACAO) where CAD2.ID_EMPRESA=CADASTRO.ID_EMPRESA  and DECL.AM_REFERENCIA =  (select max(DEC2.AM_REFERENCIA) from DECLARACAO DEC2 where DEC2.IN_FOI_RETIFICADA=0 and exists (select CAD3.ID_CADASTRO from CADASTRO CAD3  where CAD3.ID_DECLARACAO=DEC2.ID_DECLARACAO and CAD3.ID_EMPRESA=CADASTRO.ID_EMPRESA )  )and DECL.IN_FOI_RETIFICADA=0 )then 1 else 0 end ;
                                                                                     QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Seq Scan on cadastro  (cost=0.00..2767718742.41 rows=47517 width=299) (actual time=122.230..1305494.888 rows=15490 loops=1)
   SubPlan
     ->  Aggregate  (cost=58246.85..58246.86 rows=1 width=4) (actual time=84.261..84.262 rows=1 loops=15490)
           InitPlan
             ->  Aggregate  (cost=58209.49..58209.50 rows=1 width=4) (actual time=84.169..84.169 rows=1 loops=15490)
                   ->  Seq Scan on declaracao dec2  (cost=0.00..58197.37 rows=4850 width=4) (actual time=12.035..84.147 rows=5 loops=15490)
                         Filter: ((in_foi_retificada = 0) AND (subplan))
                         SubPlan
                           ->  Index Scan using fki_cadastro_id_declaracao_fkey on cadastro cad3  (cost=0.00..5.92 rows=1 width=4) (actual time=0.007..0.007 rows=0 loops=150253000)
                                 Index Cond: (id_declaracao = $0)
                                 Filter: (id_empresa = $1)
           ->  Nested Loop  (cost=0.00..37.35 rows=1 width=4) (actual time=84.214..84.254 rows=2 loops=15490)
                 ->  Index Scan using fki_cadastro_id_empresa_fkey on cadastro cad2  (cost=0.00..17.27 rows=4 width=8) (actual time=0.010..0.026 rows=5 loops=15490)
                       Index Cond: (id_empresa = $1)
                 ->  Index Scan using declaracao_pkey on declaracao decl  (cost=0.00..5.01 rows=1 width=4) (actual time=18.449..18.449 rows=0 loops=70706)
                       Index Cond: (decl.id_declaracao = "outer".id_declaracao)
                       Filter: ((am_referencia = $2) AND (in_foi_retificada = 0))
 Total runtime: 1306981.498 ms at 100% cpu
(18 registros)

bddnf=#







bddnf=# explain analyze update CADASTRO set IN_CADASTRO_MAIS_ATUAL = case when CADASTRO.ID_CADASTRO=  (select max(CAD2.ID_CADASTRO) from CADASTRO CAD2 inner join DECLARACAO DECL on (DECL.ID_DECLARACAO=CAD2.ID_DECLARACAO) where CAD2.ID_EMPRESA=CADASTRO.ID_EMPRESA  and DECL.AM_REFERENCIA =  (select max(DEC2.AM_REFERENCIA) from DECLARACAO DEC2 where DEC2.IN_FOI_RETIFICADA=0 and exists (select CAD3.ID_CADASTRO from CADASTRO CAD3  where CAD3.ID_DECLARACAO=DEC2.ID_DECLARACAO and CAD3.ID_EMPRESA=CADASTRO.ID_EMPRESA )  )and DECL.IN_FOI_RETIFICADA=0 )then 1 else 0 end ;
                                                                                     QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Seq Scan on cadastro  (cost=0.00..975191512.43 rows=16752 width=299) (actual time=92.813..1151887.013 rows=15490 loops=1)
   SubPlan
     ->  Aggregate  (cost=58213.38..58213.39 rows=1 width=4) (actual time=74.347..74.347 rows=1 loops=15490)
           InitPlan
             ->  Aggregate  (cost=58176.05..58176.06 rows=1 width=4) (actual time=74.264..74.265 rows=1 loops=15490)
                   ->  Seq Scan on declaracao dec2  (cost=0.00..58163.92 rows=4850 width=4) (actual time=10.611..74.245 rows=5 loops=15490)
                         Filter: ((in_foi_retificada = 0) AND (subplan))
                         SubPlan
                           ->  Index Scan using fki_cadastro_id_declaracao_fkey on cadastro cad3  (cost=0.00..5.92 rows=1 width=4) (actual time=0.006..0.006 rows=0 loops=150253000)
                                 Index Cond: (id_declaracao = $0)
                                 Filter: (id_empresa = $1)
           ->  Nested Loop  (cost=0.00..37.31 rows=1 width=4) (actual time=74.310..74.340 rows=2 loops=15490)
                 ->  Index Scan using fki_cadastro_id_empresa_fkey on cadastro cad2  (cost=0.00..17.24 rows=4 width=8) (actual time=0.010..0.020 rows=5 loops=15490)
                       Index Cond: (id_empresa = $1)
                 ->  Index Scan using declaracao_pkey on declaracao decl  (cost=0.00..5.01 rows=1 width=4) (actual time=16.278..16.279 rows=0 loops=70706)
                       Index Cond: (decl.id_declaracao = "outer".id_declaracao)
                       Filter: ((am_referencia = $2) AND (in_foi_retificada = 0))
 Total runtime: 1153168.731 ms at 100% cpu
(18 registros)

bddnf=#
