repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

opencode/skills/sql-optimization/SKILL.md

Raw

name: sql-optimization description: Optimize SQL queries — EXPLAIN/EXPLAIN ANALYZE, index design (composite, partial, covering), N+1 elimination, keyset pagination, query plan reading. license: MIT

Query Performance

SELECT *

-- Bad: SELECT * anti-pattern
SELECT * FROM large_table lt
JOIN another_table at ON lt.id = at.ref_id;

-- Good: Explicit column selection
SELECT lt.id, lt.name, at.value
FROM large_table lt
JOIN another_table at ON lt.id = at.ref_id;

Functions in WHERE

-- Bad: Prevents index usage
SELECT * FROM orders 
WHERE UPPER(customer_email) = 'JOHN@EXAMPLE.COM';

-- Good: Index-friendly
SELECT * FROM orders 
WHERE customer_email = 'john@example.com';

Subqueries

-- Bad: Correlated subquery (runs for each row)
SELECT p.product_name, p.price
FROM products p
WHERE p.price > (
    SELECT AVG(price) FROM products p2 
    WHERE p2.category_id = p.category_id
);

-- Good: Window function
SELECT product_name, price
FROM (
    SELECT product_name, price,
           AVG(price) OVER (PARTITION BY category_id) as avg_category_price
    FROM products
) ranked
WHERE price > avg_category_price;

JOIN Optimization

-- Bad: Inefficient JOIN with filtering in WHERE
SELECT o.*, c.name, p.product_name
FROM orders o
LEFT JOIN customers c ON o.customer_id = c.id
LEFT JOIN order_items oi ON o.id = oi.order_id
LEFT JOIN products p ON oi.product_id = p.id
WHERE o.created_at > '2024-01-01' AND c.status = 'active';

-- Good: Filter early, use INNER JOIN
SELECT o.id, o.total_amount, c.name, p.product_name
FROM orders o
INNER JOIN customers c ON o.customer_id = c.id AND c.status = 'active'
INNER JOIN order_items oi ON o.id = oi.order_id
INNER JOIN products p ON oi.product_id = p.id
WHERE o.created_at > '2024-01-01';

Pagination

-- Bad: OFFSET becomes slow with large offsets
SELECT * FROM products 
ORDER BY created_at DESC 
LIMIT 20 OFFSET 10000;

-- Good: Cursor-based
SELECT * FROM products 
WHERE created_at < '2024-06-15 10:30:00'
ORDER BY created_at DESC 
LIMIT 20;

-- Or ID-based cursor
SELECT * FROM products 
WHERE id > 1000
ORDER BY id 
LIMIT 20;

Indexing

Composite Index Order

-- For queries filtering by email, then sorting by created_at
CREATE INDEX idx_users_email_created ON users(email, created_at);

-- For queries filtering by status, then sorting by date
CREATE INDEX idx_users_status_created ON users(status, created_at);

Partial Index

-- For queries that only look at pending/processing orders
CREATE INDEX idx_orders_active ON orders(created_at) 
WHERE status IN ('pending', 'processing');

Covering Index

-- Include frequently accessed columns
CREATE INDEX idx_orders_covering 
ON orders(customer_id, created_at) 
INCLUDE (total_amount, status);

Aggregation

-- Bad: Multiple queries
SELECT COUNT(*) FROM orders WHERE status = 'pending';
SELECT COUNT(*) FROM orders WHERE status = 'shipped';

-- Good: Single query with conditional aggregation
SELECT 
    COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending,
    COUNT(CASE WHEN status = 'shipped' THEN 1 END) as shipped
FROM orders;

Batch Operations

-- Bad: Row-by-row
INSERT INTO products (name, price) VALUES ('Product 1', 10.00);
INSERT INTO products (name, price) VALUES ('Product 2', 15.00);

-- Good: Batch insert
INSERT INTO products (name, price) VALUES 
('Product 1', 10.00),
('Product 2', 15.00),
('Product 3', 20.00);

OR vs UNION

-- Bad: Complex OR conditions
SELECT * FROM products 
WHERE (category = 'electronics' AND price < 1000)
   OR (category = 'books' AND price < 50);

-- Good: UNION for better optimization
SELECT * FROM products WHERE category = 'electronics' AND price < 1000
UNION ALL
SELECT * FROM products WHERE category = 'books' AND price < 50;

Checklist

Query Structure

Indexing

Pagination

Operations

Markdown source
---
name: sql-optimization
description: Optimize SQL queries — EXPLAIN/EXPLAIN ANALYZE, index design (composite, partial, covering), N+1 elimination, keyset pagination, query plan reading.
license: MIT
---

## Query Performance

### SELECT *

```sql
-- Bad: SELECT * anti-pattern
SELECT * FROM large_table lt
JOIN another_table at ON lt.id = at.ref_id;

-- Good: Explicit column selection
SELECT lt.id, lt.name, at.value
FROM large_table lt
JOIN another_table at ON lt.id = at.ref_id;
```

### Functions in WHERE

```sql
-- Bad: Prevents index usage
SELECT * FROM orders 
WHERE UPPER(customer_email) = 'JOHN@EXAMPLE.COM';

-- Good: Index-friendly
SELECT * FROM orders 
WHERE customer_email = 'john@example.com';
```

### Subqueries

```sql
-- Bad: Correlated subquery (runs for each row)
SELECT p.product_name, p.price
FROM products p
WHERE p.price > (
    SELECT AVG(price) FROM products p2 
    WHERE p2.category_id = p.category_id
);

-- Good: Window function
SELECT product_name, price
FROM (
    SELECT product_name, price,
           AVG(price) OVER (PARTITION BY category_id) as avg_category_price
    FROM products
) ranked
WHERE price > avg_category_price;
```

---

## JOIN Optimization

```sql
-- Bad: Inefficient JOIN with filtering in WHERE
SELECT o.*, c.name, p.product_name
FROM orders o
LEFT JOIN customers c ON o.customer_id = c.id
LEFT JOIN order_items oi ON o.id = oi.order_id
LEFT JOIN products p ON oi.product_id = p.id
WHERE o.created_at > '2024-01-01' AND c.status = 'active';

-- Good: Filter early, use INNER JOIN
SELECT o.id, o.total_amount, c.name, p.product_name
FROM orders o
INNER JOIN customers c ON o.customer_id = c.id AND c.status = 'active'
INNER JOIN order_items oi ON o.id = oi.order_id
INNER JOIN products p ON oi.product_id = p.id
WHERE o.created_at > '2024-01-01';
```

---

## Pagination

```sql
-- Bad: OFFSET becomes slow with large offsets
SELECT * FROM products 
ORDER BY created_at DESC 
LIMIT 20 OFFSET 10000;

-- Good: Cursor-based
SELECT * FROM products 
WHERE created_at < '2024-06-15 10:30:00'
ORDER BY created_at DESC 
LIMIT 20;

-- Or ID-based cursor
SELECT * FROM products 
WHERE id > 1000
ORDER BY id 
LIMIT 20;
```

---

## Indexing

### Composite Index Order

```sql
-- For queries filtering by email, then sorting by created_at
CREATE INDEX idx_users_email_created ON users(email, created_at);

-- For queries filtering by status, then sorting by date
CREATE INDEX idx_users_status_created ON users(status, created_at);
```

### Partial Index

```sql
-- For queries that only look at pending/processing orders
CREATE INDEX idx_orders_active ON orders(created_at) 
WHERE status IN ('pending', 'processing');
```

### Covering Index

```sql
-- Include frequently accessed columns
CREATE INDEX idx_orders_covering 
ON orders(customer_id, created_at) 
INCLUDE (total_amount, status);
```

---

## Aggregation

```sql
-- Bad: Multiple queries
SELECT COUNT(*) FROM orders WHERE status = 'pending';
SELECT COUNT(*) FROM orders WHERE status = 'shipped';

-- Good: Single query with conditional aggregation
SELECT 
    COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending,
    COUNT(CASE WHEN status = 'shipped' THEN 1 END) as shipped
FROM orders;
```

---

## Batch Operations

```sql
-- Bad: Row-by-row
INSERT INTO products (name, price) VALUES ('Product 1', 10.00);
INSERT INTO products (name, price) VALUES ('Product 2', 15.00);

-- Good: Batch insert
INSERT INTO products (name, price) VALUES 
('Product 1', 10.00),
('Product 2', 15.00),
('Product 3', 20.00);
```

---

## OR vs UNION

```sql
-- Bad: Complex OR conditions
SELECT * FROM products 
WHERE (category = 'electronics' AND price < 1000)
   OR (category = 'books' AND price < 50);

-- Good: UNION for better optimization
SELECT * FROM products WHERE category = 'electronics' AND price < 1000
UNION ALL
SELECT * FROM products WHERE category = 'books' AND price < 50;
```

---

## Checklist

### Query Structure

- [ ] Avoid SELECT * - select only needed columns
- [ ] Filter early in WHERE clauses
- [ ] Avoid functions in WHERE (prevents index use)
- [ ] Use INNER JOIN instead of LEFT JOIN when possible

### Indexing

- [ ] Index columns in WHERE and JOIN clauses
- [ ] Composite indexes - filter column first, then sort column
- [ ] Don't over-index (slows writes)
- [ ] Consider covering indexes for frequently accessed columns

### Pagination

- [ ] Use cursor-based pagination for large datasets
- [ ] Avoid OFFSET for deep pagination

### Operations

- [ ] Use batch INSERT/UPDATE
- [ ] Use UNION instead of complex OR