| name | sql-fundamentals |
| description | | Use when this capability is needed. |
SQL Fundamentals Core Knowledge
Deep Knowledge: Use mcp__documentation__fetch_docs with technology: sql for comprehensive documentation.
SQL Statement Categories
| Category | Statements | Purpose |
|---|
| DML | SELECT, INSERT, UPDATE, DELETE, MERGE | Data manipulation |
| DDL | CREATE, ALTER, DROP, TRUNCATE | Schema definition |
| DCL | GRANT, REVOKE | Access control |
| TCL | BEGIN, COMMIT, ROLLBACK, SAVEPOINT | Transaction control |
SELECT Statement
SELECT [DISTINCT] columns
FROM table
[JOIN other_table ON condition]
[WHERE condition]
[GROUP BY columns]
[HAVING condition]
[ORDER BY columns [ASC|DESC]]
[LIMIT n OFFSET m];
Execution Order
- FROM (and JOINs)
- WHERE
- GROUP BY
- HAVING
- SELECT
- DISTINCT
- ORDER BY
- LIMIT/OFFSET
INSERT Patterns
INSERT INTO users (name, email) VALUES ('John', 'john@example.com');
INSERT INTO users (name, email) VALUES
('John', 'john@example.com'),
('Jane', 'jane@example.com');
INSERT INTO users_backup (name, email)
SELECT name, email FROM users WHERE created_at < '2024-01-01';
INSERT INTO users (name, email) VALUES ('John', 'john@example.com')
RETURNING id, created_at;
UPDATE Patterns
UPDATE users SET name = 'John Doe' WHERE id = 1;
UPDATE users SET name = 'John', status = 'active' WHERE id = 1;
UPDATE orders SET status = 'shipped'
WHERE user_id IN (SELECT id FROM users WHERE is_premium = true);
UPDATE orders o SET status = 'vip'
FROM users u WHERE o.user_id = u.id AND u.is_premium = true;
DELETE Patterns
DELETE FROM users WHERE id = 1;
DELETE FROM orders WHERE user_id IN (
SELECT id FROM users WHERE status = 'deleted'
);
UPDATE users SET deleted_at = NOW() WHERE id = 1;
JOIN Types
| Join Type | Returns |
|---|
INNER JOIN | Only matching rows from both tables |
LEFT JOIN | All left + matching right (NULL if no match) |
RIGHT JOIN | All right + matching left (NULL if no match) |
FULL OUTER JOIN | All rows from both tables |
CROSS JOIN | Cartesian product (all combinations) |
SELECT u.name, o.total
FROM users u
INNER JOIN orders o ON o.user_id = u.id;
SELECT u.name, COALESCE(o.total, 0) as total
FROM users u
LEFT JOIN orders o ON o.user_id = u.id;
SELECT e.name as employee, m.name as manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;
Aggregations
SELECT
COUNT(*) as total,
COUNT(DISTINCT user_id) as unique_users,
SUM(amount) as total_amount,
AVG(amount) as avg_amount,
MIN(amount) as min_amount,
MAX(amount) as max_amount
FROM orders;
SELECT user_id, COUNT(*) as order_count, SUM(amount) as total
FROM orders
GROUP BY user_id;
SELECT user_id, SUM(amount) as total
FROM orders
GROUP BY user_id
HAVING SUM(amount) > 1000;
DDL - Table Definition
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100) NOT NULL,
status VARCHAR(20) DEFAULT 'active',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT chk_status CHECK (status IN ('active', 'inactive', 'deleted'))
);
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
user_id INT NOT NULL,
total DECIMAL(10, 2) NOT NULL,
CONSTRAINT fk_orders_user
FOREIGN KEY (user_id) REFERENCES users(id)
ON DELETE CASCADE
ON UPDATE CASCADE
);
ALTER TABLE
ALTER TABLE users ADD COLUMN phone VARCHAR(20);
ALTER TABLE users DROP COLUMN phone;
ALTER TABLE users ALTER COLUMN name TYPE VARCHAR(200);
ALTER TABLE users ADD CONSTRAINT uq_phone UNIQUE (phone);
ALTER TABLE users DROP CONSTRAINT uq_phone;
ALTER TABLE users RENAME COLUMN name TO full_name;
ALTER TABLE users RENAME TO customers;
Indexes
CREATE INDEX idx_users_email ON users(email);
CREATE UNIQUE INDEX idx_users_email ON users(email);
CREATE INDEX idx_orders_user_date ON orders(user_id, created_at DESC);
CREATE INDEX idx_active_users ON users(email) WHERE status = 'active';
DROP INDEX idx_users_email;
Transactions
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
SAVEPOINT after_debit;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
ROLLBACK TO after_debit;
UPDATE accounts SET balance = balance + 100 WHERE id = 3;
COMMIT;
BEGIN;
;
Isolation Levels
| Level | Dirty Read | Non-Repeatable Read | Phantom Read |
|---|
| READ UNCOMMITTED | Yes | Yes | Yes |
| READ COMMITTED | No | Yes | Yes |
| REPEATABLE READ | No | No | Yes |
| SERIALIZABLE | No | No | No |
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN;
COMMIT;
NULL Handling
SELECT * FROM users WHERE phone IS NULL;
SELECT * FROM users WHERE phone IS NOT NULL;
SELECT COALESCE(phone, 'N/A') as phone FROM users;
SELECT NULLIF(status, 'unknown') FROM users;
SELECT AVG(score) FROM tests;
SELECT COUNT(*) FROM tests;
SELECT COUNT(score) FROM tests;
Subqueries
SELECT name, (SELECT COUNT(*) FROM orders WHERE user_id = users.id) as order_count
FROM users;
SELECT * FROM users WHERE id IN (
SELECT DISTINCT user_id FROM orders WHERE total > 100
);
SELECT * FROM users u WHERE EXISTS (
SELECT 1 FROM orders o WHERE o.user_id = u.id AND o.total > 100
);
SELECT * FROM orders o1 WHERE total > (
SELECT AVG(total) FROM orders o2 WHERE o2.user_id = o1.user_id
);
Best Practices
DO
- Use parameterized queries (prevent SQL injection)
- Add indexes on WHERE/JOIN columns
- Use appropriate data types
- Define foreign keys for data integrity
- Use transactions for multiple related operations
- Use EXPLAIN to analyze query performance
DON'T
- Use SELECT * in production
- UPDATE/DELETE without WHERE clause
- Store comma-separated values in columns
- Use reserved words as identifiers
- Ignore NULL handling
When NOT to Use This Skill
- Advanced SQL (CTEs, window functions, recursive queries) - Use
sql-advanced skill
- PostgreSQL specifics (arrays, JSONB, extensions) - Use
postgresql skill
- MySQL specifics (engine selection, stored procedures) - Use
mysql skill
- Document databases - Use
mongodb for document-oriented data
- Caching - Use
redis for caching needs
Anti-Patterns
| Anti-Pattern | Problem | Solution |
|---|
| SELECT * in production | Transfers unnecessary data | Specify only needed columns |
| No WHERE on UPDATE/DELETE | Unintended changes to all rows | Always add WHERE clause |
| Missing indexes on JOIN columns | Slow queries, full table scans | Add indexes on foreign keys |
| String concatenation in SQL | SQL injection vulnerability | Use parameterized queries |
| Implicit data type conversions | Performance loss, unexpected results | Use explicit CAST |
| Storing CSV in columns | Violates 1NF, hard to query | Normalize into separate table |
| Using reserved words as identifiers | Syntax errors, portability issues | Choose different names |
Quick Troubleshooting
| Problem | Diagnostic | Fix |
|---|
| Syntax errors | Check SQL dialect | Use correct syntax for your database |
| Slow queries | EXPLAIN or EXPLAIN ANALYZE | Add indexes, rewrite query |
| Deadlocks | Check transaction logs | Reduce transaction scope, consistent ordering |
| Foreign key violation | Check referenced table data | Insert parent record first |
| Duplicate key error | Check UNIQUE constraints | Use UPSERT or handle conflict |
| NULL comparison fails | Remember NULL != NULL | Use IS NULL, IS NOT NULL |
Reference Documentation
Source: claude-dev-suite/claude-dev-suite — distributed by TomeVault.