Loading...
Loading...
SQL patterns for query optimization, schema design, and data modeling
npx skill4agent add alexanderstephenthompson/claude-hub data-sqlSELECT *securitydata-pipelinesSELECT *-- Good - logical steps, easy to debug
WITH active_users AS (
SELECT user_id, email
FROM users
WHERE status = 'active'
),
recent_orders AS (
SELECT user_id, COUNT(*) as order_count
FROM orders
WHERE created_at > CURRENT_DATE - INTERVAL '30 days'
GROUP BY user_id
)
SELECT
u.email,
COALESCE(o.order_count, 0) as recent_orders
FROM active_users u
LEFT JOIN recent_orders o USING (user_id);INSERT INTO inventory (sku, quantity, updated_at)
VALUES ('ABC123', 100, NOW())
ON CONFLICT (sku) DO UPDATE SET
quantity = EXCLUDED.quantity,
updated_at = EXCLUDED.updated_at;-- Running total and row number
SELECT
date,
revenue,
SUM(revenue) OVER (ORDER BY date) as running_total,
ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue DESC) as rank
FROM daily_sales;| Anti-Pattern | Problem | Fix |
|---|---|---|
| Breaks on schema changes, wastes bandwidth | List explicit columns |
| Correlated subqueries | N+1 query behavior | Use JOINs or window functions |
| Prevents index use | Restructure or use UNION |
| Functions on indexed columns | | Use range: |
Missing | Undefined behavior | Include all non-aggregated columns |
SELECT *references/query-optimization.mdreferences/window-functions.mdassets/query-patterns.md