sql optimization

query optimization:
  [1] use EXPLAIN to analyze query plan
      <terminal>sqlite3 database.db "EXPLAIN QUERY PLAN SELECT * FROM users WHERE age > 25"</terminal>

  [2] check indexes
      <terminal>sqlite3 database.db ".indexes"</terminal>

  [3] use appropriate indexes
      CREATE INDEX idx_users_age ON users(age);

  [4] avoid SELECT *
      SELECT id, name FROM users;

  [5] use LIMIT for large datasets
      SELECT * FROM users LIMIT 1000;

common patterns:

joins:
  SELECT u.name, o.order_date
  FROM users u
  INNER JOIN orders o ON u.id = o.user_id
  WHERE o.order_date > '2024-01-01';

aggregations:
  SELECT category, COUNT(*) as count,
         AVG(price) as avg_price,
         SUM(quantity) as total_quantity
  FROM sales
  GROUP BY category
  HAVING COUNT(*) > 10
  ORDER BY total_quantity DESC;

window functions:
  SELECT date, sales,
         SUM(sales) OVER (ORDER BY date) as cumulative_sales,
         AVG(sales) OVER (ORDER BY date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) as moving_avg
  FROM daily_sales;
