SQL
Essential SQL commands for database queries and management
8 min read
sqldatabasequeriesmysqlpostgresql
Table of Contents
Basic Queries
Fundamental SQL commands
SELECT Statements
Query data from tables
sql
💡 Use WHERE to filter results
✅ Always specify ORDER BY for consistent results
⚡ LIMIT improves performance on large tables
Data Modification
Insert, update, and delete data
INSERT, UPDATE, DELETE
Modify table data
sql
⚠️ Always use WHERE with UPDATE/DELETE
💡 Use transactions for related operations
✅ Test with SELECT before DELETE
Joins
Combine data from multiple tables
JOIN Operations
Combine tables
sql
💡 INNER JOIN only returns matching rows
✅ LEFT JOIN includes all left table rows
⚡ Index foreign keys for better JOIN performance
Aggregation
Group and aggregate data
GROUP BY & Aggregates
Summarize data
sql
💡 GROUP BY required for non-aggregate columns
✅ HAVING filters after grouping
⚡ Window functions don't reduce rows
Table Management
Create and modify database structure
DDL Commands
Data Definition Language
sql
💡 Use appropriate data types and sizes
✅ Always define primary keys
⚡ Add indexes on frequently queried columns
Advanced Queries
Complex query patterns
Subqueries & CTEs
Advanced query techniques
sql
💡 CTEs improve readability
✅ EXISTS often faster than IN
⚡ Use indexes for subquery joins
Indexes & Performance
Index Management
Create and manage indexes to optimize query performance
📄 Codesql
💡 Indexes speed up SELECT but slow down INSERT/UPDATE
⚠️ Too many indexes can hurt performance
📌 Use EXPLAIN to verify index usage
✅ Create indexes on columns used in WHERE, JOIN, ORDER BY
Transactions
Transaction Control
Manage database transactions for data consistency and isolation
📄 Codesql
💡 Transactions ensure ACID properties
⚠️ Long transactions can cause lock contention
📌 Use appropriate isolation level for your needs
✅ Always handle transaction errors properly
Window Functions
Window Function Syntax
Perform calculations across rows while keeping individual row details
📄 Codesql
💡 Window functions don't reduce rows like GROUP BY
⚡ More efficient than self-joins for many calculations
📌 Use PARTITION BY to group calculations
✅ Frame clauses control which rows are included
Constraints & Keys
Table Constraints
Define rules and relationships to maintain data integrity
📄 Codesql
💡 Constraints enforce data integrity at database level
⚠️ Foreign keys can impact performance on large tables
📌 Name your constraints for easier management
✅ Use NOT NULL for required fields
Views
View Management
Create virtual tables based on SELECT queries for data abstraction
📄 Codesql
💡 Views simplify complex queries and provide abstraction
⚡ Materialized views cache results for better performance
📌 Use views for security by hiding sensitive columns
✅ Views are updated automatically when base tables change