Database
Query Performance Analysis
QueryValidateExpert
What you will learn
- EXPLAIN (without ANALYZE) shows the PLAN; EXPLAIN ANALYZE RUNS the query + measures. Use ANALYZE only on test data
- Look for 'Seq Scan' on large tables โ usually means missing index. 'Index Scan' with low selectivity can also be slow
- Compare planned rows vs actual rows โ if planner is off by 10ร, stats are stale. Run ANALYZE to refresh
Description
Use EXPLAIN to understand query execution plans.
Test Scenario
-- Analyze query execution
EXPLAIN QUERY PLAN
SELECT p.name, SUM(oi.quantity) as total_sold
FROM products p
JOIN order_items oi ON p.id = oi.product_id
GROUP BY p.id;
-- Look for:
-- SCAN = full table scan (slow)
-- SEARCH = index lookup (fast)
-- USING INDEX = index being used
-- Create index to improve:
CREATE INDEX idx_order_items_product ON order_items(product_id);Testing Tips
- โขEXPLAIN shows query plan
- โขLook for SCAN vs SEARCH
- โขIndexes improve SEARCH operations
// Playwright API Testing - Databaseimport { test, expect } from '@playwright/test';test('Database query via API', async ({ request }) => {const response = await request.post('/api/database/query', {data: {sql: 'SELECT * FROM users WHERE id = ?',params: [1]}});expect(response.ok()).toBeTruthy();const { rows } = await response.json();expect(rows.length).toBeGreaterThan(0);});
Challenge ID: sql-explain-analyze
2 frameworks available