PostgreSQL Cheatsheet

MD
R
Markdown

Essential PostgreSQL commands and syntax for quick reference. Covers basic operations, data manipulation, querying, and administration tasks. Ideal for developers and database administrators.

Database Size

SELECT pg_size_pretty( pg_database_size('x'));

Select Queries

select * from information_schema.table_constraints where table_name = 'ref_v2_ref_metadata_codes'

select * from information_schema.constraint_column_usage where table_name = 'ref_v2_ref_metadata_codes'

select column_name, data_type from information_schema.columns where table_name = 'D06Z26_24_3_2021';

Count Tables Rows

create function 
cnt_rows(schema text, tablename text) returns integer
as
$body$
declare
  result integer;
  query varchar;
begin
  query := 'SELECT count(1) FROM ' || schema || '.' || tablename;
  execute query into result;
  return result;
end;
$body$
language plpgsql;

// Run this query to get rows count for all the tables
select sum(cnt_rows) as total_no_of_rows from (select 
  cnt_rows(table_schema, table_name)
from information_schema.tables
where 
  table_schema not in ('pg_catalog', 'information_schema') 
  and table_type='BASE TABLE') as subq;
or

// To get rows counts tablewise
select
  table_schema,
  table_name, 
  cnt_rows(table_schema, table_name)
from information_schema.tables
where 
  table_schema not in ('pg_catalog', 'information_schema') 
  and table_type='BASE TABLE'
order by 3 desc;

Created on 3/24/2021