вторник, 13 февраля 2018 г.

Иерархический запрос в postgres Аналог order siblings by


 WITH RECURSIVE temp1(hierarchy,id,parent_id,industry_tree_name,order_by,lvl) AS
     (
    select  ARRAY[it.industry_tree_id] AS hierarchy,
            it.industry_tree_id        as id,
            it.industry_tree_parent_id as parent_id,
            it.industry_tree_name,
            it.order_by,
            it.lvl
    from    industry_tree it
    where   it.industry_version_id = 11
    and     it.active_from <= current_timestamp
    and     it.active_to > current_timestamp
     union
    select  temp1.hierarchy || t2.industry_tree_id AS hierarchy,
            t2.industry_tree_id        as id,
            t2.industry_tree_parent_id as parent_id,
            t2.industry_tree_name,
            t2.order_by,
            temp1.lvl+1 as lvl
    from    industry_tree t2
    INNER JOIN temp1 on (temp1.id = T2.industry_tree_parent_id) 
       and     t2.active_from <= current_timestamp
       and     t2.active_to > current_timestamp
    )
     select *
       from temp1
ORDER  BY hierarchy;

Взято с stackoverflow.com

понедельник, 15 января 2018 г.

Вакуум, статистика

-- примерное количестов записей в таблице
 SELECT relname,reltuples AS approximate_row_count FROM pg_class where relowner=22268 and relkind='r' order by 2 desc

-- информация по вакууму и статистике
select 'vacuum analyze '||schemaname||'.'||relname||';' as tbl,last_vacuum,last_analyze,last_autovacuum,autovacuum_count,last_autoanalyze,
       (
        SELECT reltuples AS approximate_row_count
          FROM pg_class
         where relowner=22268 and relkind='r' and relname=att.relname
       ) as apx_row_nums
  from pg_stat_all_tables att
 where att.schemaname not in ('pg_catalog','pg_toast','prm_analytics','prm_ctp','public',
                              'prm_log','auth','prm_analytics_rep','information_schema','prm_root')
 --
 /*
 and
 autovacuum_count=0 and
 last_autovacuum is null and
 last_autoanalyze is null and
 last_vacuum is null
 --
 */
 order by att.autovacuum_count desc

 commit;

Статистика по запросам

 select pss.*
   from pg_stat_statements pss
  where pss.query not like 'FETCH ALL IN cursor%' and
        pss.query not like 'CLOSE cursor%' and
        pss.query not like '%privilege%' and
        pss.query not like 'SET datestyle%'
 order by pss.total_time desc