PostgreSQL
last updated 2021-09
PSQL aka Postgres aka PostgreSQL… i prefer psql
dump and restore
dump:
$ pg_dump -h host -p 5432 -U user -F c -b -v -f /tmp/db_name.backup db_name
restore:
$ pg_restore -h host -p 5432 -U user -d db_name -v /tmp/db_name.backup
delete duplicate lines
before you can add a unique constraint to a table, you have to make sure it does satisfy this criterion
with table_T and columns criteria_1, …, criteria_N
;;
;; list rows that do not satisfy the uniqueness constraint
;;
SELECT
criteria_1,
...
criteria_N,
COUNT(*)
FROM
table_T
GROUP BY
criteria_1, ..., criteria_N
HAVING
COUNT(*) > 1
ORDER BY
criteria_1, ..., criteria_N;
;;
;; delete all rows that do not satisfy the constraint, keeping the ones with lowest id value
;;
DELETE FROM
table_T a
USING table_T b
WHERE
a.id > b.id
AND a.criteria_1 = b.criteria_1
...
AND a.criteria_N = b.criteria_N;
set sequence value to max of table's ID
SELECT setval('table_id_seq', (SELECT MAX(id) FROM table));
find and kill stuck queries
to get the list of queries that are running for more than 5 minutes:
SELECT
pid,
NOW() - pg_stat_activity.query_start AS duration,
query,
state
FROM pg_stat_activity
WHERE (NOW() - pg_stat_activity.query_start) > INTERVAL '5 MINUTES';
kill these by PID:
SELECT pg_terminate_backend(_pid_);