Часто задаваемые вопросы: https://aik84from.github.io/faq.html
(C) Калинин Александр Игоревич
SELECT VERSION();
CREATE TABLE example (
id SERIAL PRIMARY KEY,
visitors INT
);
INSERT INTO example (id, visitors) VALUES
(1, 709),
(2, 749),
(3, 180),
(4, 518),
(5, 964),
(6, 180),
(7, 997),
(8, 562);
UPDATE example SET visitors = 100 WHERE id = 8;
DELETE FROM example WHERE id = 8;
SELECT COUNT(*) FROM example;
SELECT AVG(visitors) FROM example;
SELECT MAX(visitors), MIN(visitors) FROM example;
SELECT VARIANCE(visitors) FROM example;
SELECT SUM(visitors) FROM example;
SELECT * FROM example ORDER BY visitors DESC LIMIT 5;
SELECT * FROM example WHERE visitors BETWEEN 190 AND 800;
SELECT
COUNT(visitors),
visitors
FROM example
GROUP BY visitors
HAVING COUNT(visitors) > 1;
SELECT
id,
visitors,
dense_rank() OVER (ORDER BY visitors DESC) AS rank
FROM example;
WITH data AS (
SELECT ARRAY[1, 2, 3, 4] AS alpha
)
SELECT * FROM data;
SELECT 26 AS age
UNION ALL
SELECT 40 AS age;
CREATE FUNCTION example_f(n integer)
RETURNS integer AS $$
BEGIN
RETURN factorial(n);
END; $$
LANGUAGE plpgsql;
SELECT pg_size_pretty(pg_relation_size('example')) relation_size;
CREATE INDEX idx_example_visitors ON example(visitors);
EXPLAIN (ANALYZE)
SELECT * FROM example WHERE id IN (1, 5, 7);
CREATE TABLE backup_example AS TABLE example;
CREATE TABLE documents (
id SERIAL PRIMARY KEY,
title VARCHAR(256)
);
INSERT INTO documents (id, title) VALUES
(1, 'Better late than never'),
(2, 'A good man is hard to find'),
(3, 'Worrying never did anyone any good');
ALTER TABLE documents
ADD COLUMN title_gin tsvector
GENERATED ALWAYS AS (to_tsvector('english', title)) STORED;
CREATE INDEX idx_title_gin ON documents USING GIN (title_gin);
SELECT *
FROM documents
WHERE title_gin @@ to_tsquery('english', 'never');
SELECT title, REGEXP_MATCHES(title, 'never') result FROM documents;
SELECT title, LENGTH(title), MD5(title) FROM documents;
SELECT SQRT(AVG(POWER(beta - alpha, 2))) AS RMSE
FROM (
SELECT
unnest(ARRAY[8, 4, 9, 7, -9, 0, 2, 5, -8, -6, -4, -2, -1, 3]) as alpha,
unnest(ARRAY[0, -7, -5, -8, -1, -4, 1, 6, 5, 3, 8, -2, 7, -6]) as beta
);