sql-advanced
БесплатноБез исполняемых скриптовНе проверенAdvanced SQL patterns including CTEs, window functions, recursive queries, query optimization, and EXPLAIN analysis. Use for complex query writing and…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
SQL Advanced Core Knowledge
Deep Knowledge: Use
mcp__documentation__fetch_docswith technology:sqlfor comprehensive documentation.
Common Table Expressions (CTEs)
Basic CTE
WITH active_users AS (
SELECT id, name, email
FROM users
WHERE status = 'active'
)
SELECT u.name, COUNT(o.id) as order_count
FROM active_users u
LEFT JOIN orders o ON o.user_id = u.id
GROUP BY u.id, u.name;
Multiple CTEs
WITH
active_users AS (
SELECT id, name FROM users WHERE status = 'active'
),
user_orders AS (
SELECT user_id, COUNT(*) as order_count, SUM(total) as total_spent
FROM orders
WHERE status = 'completed'
GROUP BY user_id
),
high_value_users AS (
SELECT u.*, uo.order_count, uo.total_spent
FROM active_users u
JOIN user_orders uo ON uo.user_id = u.id
WHERE uo.total_spent > 10000
)
SELECT * FROM high_value_users ORDER BY total_spent DESC;
Recursive CTEs
-- Hierarchical data (org chart, categories)
WITH RECURSIVE org_chart AS (
-- Base case: top-level employees
SELECT id, name, manager_id, 1 as level, ARRAY[name] as path
FROM employees
WHERE manager_id IS NULL
UNION ALL
-- Recursive case
SELECT e.id, e.name, e.manager_id, oc.level + 1, oc.path || e.name
FROM employees e
JOIN org_chart oc ON e.manager_id = oc.id
)
SELECT * FROM org_chart ORDER BY path;
-- Generate series
WITH RECURSIVE numbers AS (
SELECT 1 as n
UNION ALL
SELECT n + 1 FROM numbers WHERE n < 100
)
SELECT * FROM numbers;
-- Date range
WITH RECURSIVE dates AS (
SELECT DATE '2024-01-01' as date
UNION ALL
SELECT date + INTERVAL '1 day' FROM dates WHERE date < '2024-12-31'
)
SELECT * FROM dates;
Materialized CTE (PostgreSQL 12+)
-- Force CTE to be materialized (evaluated once)
WITH active_users AS MATERIALIZED (
SELECT * FROM users WHERE status = 'active'
)
SELECT * FROM active_users WHERE id = 1
UNION ALL
SELECT * FROM active_users WHERE id = 2;
-- Force CTE to be inlined (not materialized)
WITH active_users AS NOT MATERIALIZED (
SELECT * FROM users WHERE status = 'active'
)
SELECT * FROM active_users WHERE id = 1;
Window Functions Deep Dive
Partitioned Calculations
SELECT
department,
name,
salary,
-- Within department
SUM(salary) OVER (PARTITION BY department) as dept_total,
AVG(salary) OVER (PARTITION BY department) as dept_avg,
salary - AVG(salary) OVER (PARTITION BY department) as diff_from_avg,
-- Percentage of department total
ROUND(100.0 * salary / SUM(salary) OVER (PARTITION BY department), 2) as pct_of_dept
FROM employees;
Running Calculations
SELECT
date,
amount,
-- Running totals
SUM(amount) OVER (ORDER BY date) as running_total,
SUM(amount) OVER (ORDER BY date ROWS UNBOUNDED PRECEDING) as same_as_above,
-- Moving averages
AVG(amount) OVER (ORDER BY date ROWS 6 PRECEDING) as moving_avg_7d,
AVG(amount) OVER (ORDER BY date ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING) as centered_avg,
-- Cumulative stats
COUNT(*) OVER (ORDER BY date) as cumulative_count,
MIN(amount) OVER (ORDER BY date) as running_min,
MAX(amount) OVER (ORDER BY date) as running_max
FROM daily_transactions;
Gap and Island Analysis
-- Find consecutive sequences (islands)
WITH numbered AS (
SELECT
date,
value,
ROW_NUMBER() OVER (ORDER BY date) as rn,
date - (ROW_NUMBER() OVER (ORDER BY date) * INTERVAL '1 day') as grp
FROM daily_data
)
SELECT
MIN(date) as island_start,
MAX(date) as island_end,
COUNT(*) as days_in_sequence
FROM numbered
GROUP BY grp
ORDER BY island_start;
-- Find gaps in sequence
SELECT
id,
LEAD(id) OVER (ORDER BY id) as next_id,
LEAD(id) OVER (ORDER BY id) - id - 1 as gap_size
FROM items
WHERE LEAD(id) OVER (ORDER BY id) - id > 1;
First/Last in Group
-- Get first and last values per group
SELECT DISTINCT ON (department)
department,
name as highest_paid,
salary
FROM employees
ORDER BY department, salary DESC;
-- With window functions
SELECT DISTINCT
department,
FIRST_VALUE(name) OVER w as highest_paid,
LAST_VALUE(name) OVER w as lowest_paid
FROM employees
WINDOW w AS (
PARTITION BY department
ORDER BY salary DESC
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
);
Query Optimization
EXPLAIN Basics
-- Show query plan
EXPLAIN SELECT * FROM users WHERE email = '[email protected]';
-- Show actual execution stats
EXPLAIN ANALYZE SELECT * FROM users WHERE email = '[email protected]';
-- More details
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT * FROM users WHERE email = '[email protected]';
-- JSON output for tools
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
SELECT * FROM users WHERE email = '[email protected]';
Reading EXPLAIN Output
Seq Scan on users (cost=0.00..155.00 rows=1 width=100) (actual time=0.01
Установить sql-advanced в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditВложенные файлы
FAQ
Что делает скилл sql-advanced?
Advanced SQL patterns including CTEs, window functions, recursive queries, query optimization, and EXPLAIN analysis. Use for complex query writing and performance tuning. USE WHEN: user mentions "CTE", "window functions", "recursive queries", "EXPLAIN", "query optimization", "ROW_NUMBER", "RANK", "PARTITION BY", "running totals" DO NOT USE FOR: basic SQL - use `sql-fundamentals` instead, database-specific features - use `postgresql`, `mysql`, or `sqlserver` instead
Как установить скилл sql-advanced?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл sql-advanced запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic