Skip to content

Instantly share code, notes, and snippets.

View NikolayS's full-sized avatar
🐘
Need help with Postgres? Let me know!

Nikolay Samokhvalov NikolayS

🐘
Need help with Postgres? Let me know!
View GitHub Profile
@NikolayS
NikolayS / pg_graph
Last active December 21, 2023 08:32 — forked from akorotkov/pg_graph
Draw psql output as iTerm2 v3 inline graph using matplotlib
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Draw psql output as iTerm2 v3 inline graph using matplotlib
# Author: Alexander Korotkov <aekorotkov@gmail.com>
# with a few edits by nik@postgres.ai to support Python3
import sys
import re
import warnings
import matplotlib
@NikolayS
NikolayS / 00_slowest_queries_full.sql
Last active November 28, 2023 19:06
Useful Postgres Queries
-- In pg_stat_statements, there is a problem: sometimes (quite often), it registers the same query twice (or even more).
-- It's easy to check in your DB:
--
-- with heh as (
-- select userid, dbid, query, count(*), array_agg(queryid) queryids
-- from pg_stat_statements group by 1, 2, 3 having count(*) > 1
-- ) select left(query, 85) || '...', userid, dbid, count, queryids from heh;
--
-- This query gives you "full picture", aggregating stats for each query-database-username ternary
@NikolayS
NikolayS / file_fdw__csv.sql
Last active October 15, 2023 02:54
Postgres: CSV file as a table using FDW
-- Installs "file_fdw" extension and creates foreign table to work with data from CSV file.
-- See also the comment below which helps to automate the process for Google Spreadsheets
-- Another option would be using Multicorn for Google Spreadsheets, but it requires additional steps
-- (see https://wiki.postgresql.org/wiki/Foreign_data_wrappers).
create extension file_fdw;
create server "import" foreign data wrapper file_fdw;
create foreign table "table1" (
col1 text,
@NikolayS
NikolayS / 1.md
Created September 26, 2023 15:28
EXPLAIN ANALYZE or EXPLAIN (ANALYZE, BUFFERS)?

When analyzing Postgres query execution plans, it is recommended using the BUFFERS option:

explain (analyze, buffers) <query>;

Example:

test=# explain (analyze, buffers) select * from t1 where num > 10000 order by num limit 1000;
                                                                QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------
@NikolayS
NikolayS / gist:1bbc624dfc088be6f15c
Last active July 23, 2023 16:51
Oracle's attempt to protect its place on the Russian market of database systems (RU + EN)
Источник: http://img11.postila.ru/data/34/fb/11/82/34fb118246ebb0b6a7f2dc6e7685f5ff62c0d9cff90876b283f3ecb521444775.jpg
(документ, упоминаемый в статье Ведомостей http://www.vedomosti.ru/technology/articles/2016/03/17/633926-importnii-soft-zamenit)
Почему PostgreSQL не является аналогом СУБД Oracle
С 1 января 2016 года в России вступает в действие постановление РФ "Об установлении запрета на допуск
Программного обеспечения, происходящего из иностранных государств, для целей осуществления закупок для обеспечения
государственных и муниципальных нужд". В соответствии с этим постановлением 1 января 2016 года формируется
реестр российского программного обеспечения (ПО)и госорганизации могут покупать ПО иностранных фирм
@NikolayS
NikolayS / howto.md
Last active January 29, 2023 20:25
log_min_duration_statement = 0 and I/O impact

How to get an estimate of the impact of writing Postgres logs with log_min_duration_statement = 0:

  1. Do select pg_stat_statements_reset(); and wait N seconds (where N >> 60 – say 1-24 hours, covering typical busy hours). Remember when it was, and write down somewhere – this timestamp will be needed!

  2. Check if select count(*) from pg_stat_statements is lower than pg_stat_statements.max. If it's equal to it, then raise pg_stat_statements.max and restart with the step 1.

  3. Get the estimate:

\set TS_PGSS_RESET 'XXXX-XX-XX XX:XX:XX';
@NikolayS
NikolayS / dba_pgss.sql
Last active November 19, 2021 16:55
Simple pg_stat_statements snapshots
create schema dba;
-- on GCP's Cloud SQL for Postgres, if we work with more than one DB user,
-- we have a problem – some queries are not visible (`<insufficient privilege>`),
-- so we need to use a workaround
create or replace function dba.pgss_snapshot() returns setof pg_stat_statements as $$
declare
rec pg_stat_statements;
_role text;
begin
@NikolayS
NikolayS / becnh_m5.2xlarge.out
Last active November 17, 2021 21:52
pgbench: simple INSERTs, UPDATEs with and without triggers
# m5.2xlarge 32.0 GiB 8 vCPUs
# s=100, n=10
*** Only SELECTs, -T 30 -j4 -c12
transaction type: <builtin: select only>
scaling factor: 100
query mode: prepared
number of clients: 12
number of threads: 4
duration: 30 s
@NikolayS
NikolayS / abstracts_writings.md
Last active July 15, 2021 13:02
Как написать хорошие тезисы для доклада на конференции

Рекомендации для докладов типа Case Study (компания/проект делится своим опытом)

Недостаточно просто описать задачу в тезисах. Довольно часто бывает так, что заинтересованные слушатели могут это сделать не хуже докладчика. Хорошие же тезисы отличает конкретика: конкретные названия, конкретные числовые показатели (последнее особенно важно для Highload++).

Главное — приоткрыть суть вашего доклада, оставаясь при этом в рамках сжатых тезисов.

И это не так сложно. При подготовке доклада и его тезисов нужно сделать всего лишь три шага.

@NikolayS
NikolayS / queries_by_keyword.sql
Last active January 6, 2020 12:29
workload - pg_stat_statements
-- based on pg_stat_statements only
with data as (
select
lower(regexp_replace(query, '^\W*(\w+)\W+.*$', '\1')) word,
count(*) cnt,
sum(calls) calls,
sum(total_time) total_time
from pg_stat_statements
--where not query ~* '^\W*set\W+' -- uncomment this to exclude `SET ...`
group by 1