Skip to content

Instantly share code, notes, and snippets.

@amitsaxena
Last active January 24, 2024 23:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amitsaxena/0115d1d28fa90a5324560716b586d496 to your computer and use it in GitHub Desktop.
Save amitsaxena/0115d1d28fa90a5324560716b586d496 to your computer and use it in GitHub Desktop.
Useful SQL queries for debugging
// Change SQL client timeout
set statement_timeout = '0s';
set statement_timeout = '10s';
// Change timeout globally
alter database mentimeter set statement_timeout = '10s';
// Time queries
\timing
// Create multicolumn index concurrenty
CREATE INDEX CONCURRENTLY vote_texts_multi_column ON vote_texts (question_id, identifier_id);
// Drop index
DROP INDEX CONCURRENTLY vote_texts_multi_column;
// See all locks
SELECT locktype, relation::regclass, mode, pid FROM pg_locks;
// See all locks with relevant query
SELECT
S.pid,
age(clock_timestamp(), query_start),
query,
L.mode,
L.locktype,
L.granted
FROM pg_stat_activity S
inner join pg_locks L on S.pid = L.pid
order by L.granted, L.pid DESC;
// List all tables of a specific schema
\dt schema_name.*
// Get number of rows per table
WITH tbl AS
(SELECT table_schema,
TABLE_NAME
FROM information_schema.tables
WHERE TABLE_NAME not like 'pg_%'
AND table_schema in ('public'))
SELECT table_schema,
TABLE_NAME,
(xpath('/row/c/text()', query_to_xml(format('select count(*) as c from %I.%I', table_schema, TABLE_NAME), FALSE, TRUE, '')))[1]::text::int AS rows_n
FROM tbl
ORDER BY rows_n DESC;
// Get size of databases
select t1.datname AS db_name,
pg_size_pretty(pg_database_size(t1.datname)) as db_size
from pg_database t1
order by pg_database_size(t1.datname) desc;
@amitsaxena
Copy link
Author

Useful article about types of locks:
http://shiroyasha.io/understanding-postgresql-locks.html

@amitsaxena
Copy link
Author

Interesting read about how an UPDATE resulted in table level exclusive lock instead of a row level lock:
https://blog.heroku.com/curious-case-table-locking-update-query

@amitsaxena
Copy link
Author

@amitsaxena
Copy link
Author

@amitsaxena
Copy link
Author

@amitsaxena
Copy link
Author

@amitsaxena
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment