Last active
May 24, 2024 15:24
-
-
Save amitsaxena/0115d1d28fa90a5324560716b586d496 to your computer and use it in GitHub Desktop.
Useful SQL queries for debugging
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; |
Query plan viewer:
http://tatiyants.com/pev/#/plans/new
How to speed up sorting/order by:
https://www.cybertec-postgresql.com/en/postgresql-improving-sort-performance/
Reindexing:
https://ketanbhatt.com/postgres-recreate-index/
Debugging Postgres locks:
https://www.crunchydata.com/blog/one-pid-to-lock-them-all-finding-the-source-of-the-lock-in-postgres
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Decent explaination of
EXPLAIN ANALYZE
:https://thoughtbot.com/blog/reading-an-explain-analyze-query-plan