Content
Follow these SQL best practices to write maintainable, efficient, and secure queries.
Formatting and Readability
-- Use consistent capitalization
SELECT
customer_name,
order_date,
total_amount
FROM orders
WHERE status = 'completed'
ORDER BY order_date DESC;
Use Meaningful Aliases
SELECT
c.name AS customer_name,
COUNT(o.id) AS order_count
FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id
GROUP BY c.id;
Always Use WHERE with UPDATE/DELETE
-- Always include WHERE to avoid disasters
UPDATE products SET price = 99.99 WHERE id = 123;
DELETE FROM logs WHERE created_at < '2024-01-01';
Use Parameterized Queries
-- Prevent SQL injection
-- Bad: "SELECT * FROM users WHERE id = " + userId
-- Good: "SELECT * FROM users WHERE id = ?"
Comment Complex Logic
-- Calculate customer lifetime value
-- Includes only completed orders from last 2 years
SELECT customer_id, SUM(total) as ltv
FROM orders
WHERE status = 'completed'
AND order_date > DATE_SUB(NOW(), INTERVAL 2 YEAR)
GROUP BY customer_id;
Avoid Nested Queries When Possible
-- Use JOINs or CTEs instead of deeply nested subqueries
Test with LIMIT First
-- Test query results before running on full dataset
SELECT * FROM large_table WHERE condition LIMIT 10;
Use Transactions for Related Changes
START TRANSACTION;
-- Multiple related operations
COMMIT;
Write Better SQL with AI2sql
AI2sql follows best practices automatically. Generate clean, efficient SQL from plain English.
