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 / 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 / circle.yml
Created January 27, 2017 17:18 — forked from jnwheeler44/circle.yml
How to use Postgres 9.6.1 on circleci 14.04 image
# Other settings have been omitted, the below changes are relevant
machine:
pre:
- sudo service postgresql stop
- sudo apt-get purge -y postgresql*
- sudo apt-get update
- sudo apt-get install postgresql
- sudo service postgresql start
- sudo su - postgres -c "echo \"create user ubuntu with password 'ubuntu';\" | psql"
- sudo su - postgres -c "echo \"alter user ubuntu with superuser;\" | psql"
create table multi(id bigserial primary key, data text);
create table multi1(instance int2 not null default 1) inherits(multi);
create rule domultiply as on insert to multi do instead insert into multi1(data) values('auto1'), ('auto2') returning id, data;
insert into multi(data) values('manual') returning *; -- returns 2 rows!
@NikolayS
NikolayS / 1. Gmail Contacts (Outlook CSV format) as FDW table in Postgres, Import
Last active December 15, 2016 22:02
Gmail Contacts (Outlook CSV format) in Postgres, Import, Sampling and Export
create extension file_fdw;
create server csvfile foreign data wrapper file_fdw;
create foreign table contacts_exported(
"First Name" text not null default '',
"Middle Name" text not null default '',
"Last Name" text not null default '',
"Title" text not null default '',
"Suffix" text not null default '',
"Initials" text not null default '',
@NikolayS
NikolayS / 1_ini_data.sql
Last active October 14, 2016 00:33
Index scan speed doesn't depend on underlying data type and size (PostgreSQL)
--util function
create or replace function random_string(length integer) returns text as
$$
declare
chars text[] := '{0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}';
result text := '';
i integer := 0;
begin
if length < 0 then
raise exception 'Given length cannot be less than 0';
@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 / 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 / gist:5395b4ac4cfae7558e4d
Last active January 21, 2016 07:49
Fast search of row ID that has "nearest" "created" timetsamp to NOW() - INTERVAL 'N days' (a-la loose index scan technique)
-- Use this in your matview/report as a tool to fetch all IDs that "slightly" overlap "N last days" of data
-- This recursive CTE walks back step by step, assuming that orders of "id" and "created" fields are the same.
-- Step size is 50,000 here,
-- time window is 30 days
-- (edit both params and/or embed them to SQL code itself, if needed).
-- [TODO] Warning: in case of missing IDs in the table, line #26 can lead to a bit incorrect result
SET user_vars.reporting_window = '30 day';
SET user_vars.reporting_scan_stepsize = 50000;
@NikolayS
NikolayS / abstracts_writings.md
Last active July 15, 2021 13:02
Как написать хорошие тезисы для доклада на конференции

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

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

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

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