sql-best-practices
Skill266 starsChanged 10 months agoApache-2.0View on GitHub
SQL development best practices for writing efficient, secure, and maintainable database queries
In this repository264 other files it gives its agents.
- accessibility-a11ySkill
- alpine-jsSkill
- analytics-data-analysisSkill
- android-developmentSkill
- angular-developmentSkill
- angularSkill
- anime-jsSkill
- anthropic-claude-developmentSkill
- api-developmentSkill
- apollo-graphqlSkill
- aspnet-coreSkill
- astroSkill
- auth0-authenticationSkill
- autogen-developmentSkill
- automl-hyperparameter-optimizationSkill
- aws-developmentSkill
- azureSkill
- backend-developmentSkill
- bash-scriptingSkill
- beautifulsoup-parsingSkill
- bitbucket-workflowSkill
- blazorSkill
- blender-python-addonSkill
- blockchainSkill
- bootstrapSkill
- business-central-developmentSkill
- cheerio-parsingSkill
- chrome-extension-developmentSkill
- ci-cd-best-practicesSkill
- clean-architectureSkill
- clean-codeSkill
- clerk-authenticationSkill
- cloudflare-developmentSkill
- computer-vision-opencvSkill
- convexSkill
- cppSkill
- c-sharpSkill
- cssSkill
- cypressSkill
- data-analysis-jupyterSkill
- data-analystSkill
- data-jupyter-pythonSkill
- deep-learning-pythonSkill
- deep-learning-pytorchSkill
- deep-learningSkill
- deno-typescriptSkill
- design-systemsSkill
- devopsSkill
- django-pythonSkill
- django-rest-api-developmentSkill
- dockerSkill
- dotnetSkill
- drizzle-ormSkill
- drupal-developmentSkill
- elasticsearch-best-practicesSkill
- electron-developmentSkill
- elixirSkill
- embedded-stm32Skill
- esbuild-bundlerSkill
- ethereumSkill
- The first 60 shown.
The file
Show its rules and text
We split this skill into the rules it gives an agent
47 rules. About 0 are common, 41 are distinctive, and 6 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈41
Distinctive · estimate
This author's own choices. Worth a look.
6
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 10
Write clear, readable SQL with consistent formatting and meaningful aliases
- Distinctive: line 13
Use transactions appropriately for data integrity
- Distinctive: line 14
Document complex queries with inline comments
- Distinctive: line 20
Use uppercase for SQL keywords (SELECT, FROM, WHERE, JOIN)
- Distinctive: line 21
Place each major clause on a new line for readability
- Very specific: line 22
Use meaningful table aliases (e.g., customers AS c not customers AS x)
- Very specific: line 41
Avoid SELECT * in production code.
- Very specific: line 42
Use column aliases to clarify output: SELECT first_name AS "First Name"
- Distinctive: line 43
Consider the order of columns in SELECT for logical grouping
- Distinctive: line 47
Place most restrictive conditions first in WHERE clauses
- Very specific: line 48
Use appropriate operators: prefer IN over multiple OR conditions
- Very specific: line 49
Use EXISTS instead of IN for subqueries when checking existence
- Distinctive: line 50
Avoid functions on indexed columns in WHERE clauses when possible
- Distinctive: line 51
Use parameterized queries to prevent SQL injection
- Distinctive: line 72
Always use explicit JOIN syntax instead of implicit joins in WHERE
- Distinctive: line 75
Use appropriate join types based on data requirements
- Distinctive: line 94
Create indexes on columns used in WHERE, JOIN, and ORDER BY clauses
- Distinctive: line 95
Consider composite indexes for multi-column queries
- Distinctive: line 96
Avoid over-indexing; each index adds write overhead
- Distinctive: line 98
Use covering indexes for frequently executed queries
- Distinctive: line 102
Use EXPLAIN/EXPLAIN ANALYZE to understand query execution plans
- Distinctive: line 104
Use pagination for large result sets
- Distinctive: line 105
Avoid correlated subqueries when possible.
- Distinctive: line 106
Consider query caching for frequently executed queries
- Distinctive: line 119
Use appropriate aggregate functions (COUNT, SUM, AVG, etc.)
- Distinctive: line 120
Consider window functions for running totals and rankings
- Distinctive: line 133
Keep transactions as short as possible
- Distinctive: line 134
Use appropriate isolation levels for your use case
- Distinctive: line 135
Always include error handling with ROLLBACK
- Distinctive: line 136
Avoid user interaction during open transactions
- Distinctive: line 137
Use savepoints for complex multi-step operations
- Distinctive: line 153
Always use parameterized queries or prepared statements
- Distinctive: line 154
Never concatenate user input directly into SQL strings
- Distinctive: line 169
Always specify column names explicitly
- Distinctive: line 170
Use bulk inserts for multiple rows when possible
- Distinctive: line 171
Consider using MERGE/UPSERT for insert-or-update scenarios
- Distinctive: line 182
Always include a WHERE clause (unless intentionally updating all rows)
- Distinctive: line 183
Test UPDATE queries with SELECT first
- Distinctive: line 184
Consider using transactions for critical updates
- Distinctive: line 188
Always include a WHERE clause
- Distinctive: line 189
Use soft deletes (status flags) for recoverable data
- Distinctive: line 190
Consider CASCADE effects on related tables
- Distinctive: line 194
Use snake_case for table and column names
- Distinctive: line 195
Use singular nouns for table names (customer, not customers)
- Very specific: line 197
Use descriptive names: order_total not ot
- Distinctive: line 203
Document stored procedures with purpose, parameters, and examples
- Distinctive: line 212
Use TRY-CATCH blocks where supported
≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
SQL Best Practices
Core Principles
- Write clear, readable SQL with consistent formatting and meaningful aliases
- Prioritize query performance through proper indexing and optimization
- Implement security best practices to prevent SQL injection
- Use transactions appropriately for data integrity
- Document complex queries with inline comments
Query Writing Standards
Formatting and Style
- Use uppercase for SQL keywords (SELECT, FROM, WHERE, JOIN)
- Place each major clause on a new line for readability
- Use meaningful table aliases (e.g.,
customers AS cnotcustomers AS x) - Indent subqueries and nested conditions consistently
- Align column lists and conditions for visual clarity
SELECT
c.customer_id,
c.customer_name,
o.order_date,
o.total_amount
FROM customers AS c
INNER JOIN orders AS o ON c.customer_id = o.customer_id
WHERE o.order_date >= '2024-01-01'
AND o.status = 'completed'
ORDER BY o.order_date DESC;Column Selection
- Avoid
SELECT *in production code; explicitly list required columns - Use column aliases to clarify output:
SELECT first_name AS "First Name" - Consider the order of columns in SELECT for logical grouping
Filtering and Conditions
- Place most restrictive conditions first in WHERE clauses
- Use appropriate operators: prefer
INover multipleORconditions - Use
EXISTSinstead ofINfor subqueries when checking existence - Avoid functions on indexed columns in WHERE clauses when possible
- Use parameterized queries to prevent SQL injection
-- Preferred: Use EXISTS for existence checks
SELECT c.customer_name
FROM customers AS c
WHERE EXISTS (
SELECT 1 FROM orders AS o
WHERE o.customer_id = c.customer_id
AND o.order_date > '2024-01-01'
);
-- Avoid: Function on indexed column
WHERE YEAR(order_date) = 2024
-- Preferred: Range comparison
WHERE order_date >= '2024-01-01' AND order_date < '2025-01-01'Join Best Practices
- Always use explicit JOIN syntax instead of implicit joins in WHERE
- Specify join type explicitly (INNER, LEFT, RIGHT, FULL OUTER)
- Order joins from largest to smallest table when possible
- Use appropriate join types based on data requirements
- Be cautious with CROSS JOINs; ensure they are intentional
-- Explicit join (preferred)
SELECT c.name, o.order_id
FROM customers AS c
INNER JOIN orders AS o ON c.customer_id = o.customer_id;
-- Avoid implicit join
SELECT c.name, o.order_id
FROM customers c, orders o
WHERE c.customer_id = o.customer_id;Performance Optimization
Indexing Guidelines
- Create indexes on columns used in WHERE, JOIN, and ORDER BY clauses
- Consider composite indexes for multi-column queries
- Avoid over-indexing; each index adds write overhead
- Regularly analyze and maintain indexes
- Use covering indexes for frequently executed queries
Query Optimization
- Use EXPLAIN/EXPLAIN ANALYZE to understand query execution plans
- Limit result sets with TOP/LIMIT when full results are not needed
- Use pagination for large result sets
- Avoid correlated subqueries when possible; use JOINs instead
- Consider query caching for frequently executed queries
-- Pagination example
SELECT product_id, product_name, price
FROM products
ORDER BY product_id
LIMIT 20 OFFSET 40;Aggregation Best Practices
- Filter before grouping when possible (WHERE vs HAVING)
- Use appropriate aggregate functions (COUNT, SUM, AVG, etc.)
- Consider window functions for running totals and rankings
-- Efficient: Filter before aggregation
SELECT category_id, COUNT(*) AS product_count
FROM products
WHERE active = true
GROUP BY category_id
HAVING COUNT(*) > 10;Transaction Management
- Keep transactions as short as possible
- Use appropriate isolation levels for your use case
- Always include error handling with ROLLBACK
- Avoid user interaction during open transactions
- Use savepoints for complex multi-step operations
BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;
IF @@ERROR <> 0
ROLLBACK TRANSACTION;
ELSE
COMMIT TRANSACTION;Security Best Practices
- Always use parameterized queries or prepared statements
- Never concatenate user input directly into SQL strings
- Apply principle of least privilege for database users
- Audit and log sensitive data access
- Encrypt sensitive data at rest and in transit
-- Use parameterized queries (pseudo-code)
PREPARE stmt FROM 'SELECT * FROM users WHERE username = ?';
EXECUTE stmt USING @username;Data Modification Best Practices
INSERT Operations
- Always specify column names explicitly
- Use bulk inserts for multiple rows when possible
- Consider using MERGE/UPSERT for insert-or-update scenarios
INSERT INTO customers (customer_name, email, created_at)
VALUES
('John Doe', 'john@example.com', CURRENT_TIMESTAMP),
('Jane Smith', 'jane@example.com', CURRENT_TIMESTAMP);UPDATE Operations
- Always include a WHERE clause (unless intentionally updating all rows)
- Test UPDATE queries with SELECT first
- Consider using transactions for critical updates
DELETE Operations
- Always include a WHERE clause
- Use soft deletes (status flags) for recoverable data
- Consider CASCADE effects on related tables
Naming Conventions
- Use snake_case for table and column names
- Use singular nouns for table names (customer, not customers)
- Prefix primary keys with table name:
customer_id - Use descriptive names:
order_totalnotot - Prefix boolean columns appropriately:
is_active,has_shipped
Documentation
- Comment complex business logic within queries
- Document stored procedures with purpose, parameters, and examples
- Maintain a data dictionary for table and column descriptions
- Version control database schema changes
Error Handling
- Implement proper error handling in stored procedures
- Log errors with sufficient context for debugging
- Return meaningful error messages to calling applications
- Use TRY-CATCH blocks where supported
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

