Skip to content

Instantly share code, notes, and snippets.

@vakiliy
Last active August 29, 2015 14:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vakiliy/8988b12e9c5c93ca8a7e to your computer and use it in GitHub Desktop.
Save vakiliy/8988b12e9c5c93ca8a7e to your computer and use it in GitHub Desktop.
-- View Current Lock
SELECT c.relname, l.mode, l.granted, l.pid FROM pg_locks as l JOIN pg_class as c on c.oid = l.relation;
-- UTF-8 text search by index
create index on <table> (<column> text_pattern_ops);
-- Generate nodes path
create table <table> as select i, format('/%s/%s/', (random() * 10), (random() * 10)) from generate_series(1,100000);
-- Create extension
\c <DB_NAME>
create extension hstore;
-- primary key `id`, btree index `section_id`
-- Per group v1 (1000 rows explain(analyze), total runtime: 35.879 ms )
SELECT a.id, a.section_id FROM articles AS a
LEFT JOIN articles AS a2
ON a.section_id = a2.section_id AND a.id <= a2.id
GROUP BY a.id, a.section_id
HAVING COUNT(*) <= 3;
-- Per group v2 same as v1 (1000 rows explain(analyze), total runtime: 46.916 ms )
SELECT a.* FROM article AS a
WHERE (SELECT COUNT(*) FROM article AS a2 WHERE a.section_id = a2.section_id) <= 3;
-- Per group v3 (1000 rows explain(analyze), total runtime: 2.466 ms )
SELECT * FROM (
SELECT ROW_NUMBER() OVER(PARTITION BY section_id ORDER_BY id), article.* AS n
FROM article
) AS a WHERE a.n <= 3;
select to_tsvector('dict', properties->'name') @@ to_tsquery('dict', 'jimmi');
-- random array
select array_agg(t1.col) from (select format('param-%s', i) col from generate_series(1,rand(10)) as i) as t1;
-- sequence
create sequence t_id_seq;
alter table t alter COLUMN id set default nextval('t_id_seq');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment