SQL Queries & Commands Cheatsheet 2026
Complete guide to SQL statements including SELECT queries, WHERE filters, aggregate functions, JOIN types, and DDL commands.
Interactive Skill Mastery
Mark commands as learned to build your customized reference tracker. Retained locally in this browser.
Querying
When to Use
When you are exploring a table for the first time and need to examine its schema, column layout, and sample rows.
Common Mistakes
Running this query on massive production databases with millions of rows, which can cause severe performance bottlenecks.
Shortcut / Pro-Tip
F5 or Ctrl + Enter (Execute current query in most Database GUIs)Example
SELECT * FROM users;Output Example
id | username | email | created_at
---+----------+------------------+--------------------
1 | d_singh | dev@learnhub.com | 2026-07-12 09:00:00
2 | priya_s | priya@singh.com | 2026-07-12 09:15:00When to Use
Use this database statement when you need to perform actions related to 'SELECT' on your database tables.
Common Mistakes
Omitting filters (WHERE clause) or schema qualifications, causing mass modification or high performance impacts.
Shortcut / Pro-Tip
Ensure relevant indices are configured on the queried columns to boost index lookups.Example
SELECT column1, column2 FROM table_name;Output Example
Query OK. Affected rows: 1 (0.02 sec)When to Use
When filtering down rows returned from your tables based on matching column values, text patterns, or lists.
Common Mistakes
Using wildcard lookups starting with % (e.g. LIKE '%pattern') on large tables as it bypasses database indices.
Shortcut / Pro-Tip
Use indexable columns in WHERE filters to optimize search velocity.Example
SELECT DISTINCT column_name FROM table_name;Output Example
Query OK. Affected rows: 1 (0.02 sec)When to Use
When you want to fetch a small, safe sample of rows from a potentially massive table for review.
Common Mistakes
Forgetting to sort the table with ORDER BY, meaning the returned 10 rows can be random and inconsistent across queries.
Shortcut / Pro-Tip
Limit queries aggressively during local development to save network bandwidthExample
SELECT * FROM logs ORDER BY created_at DESC LIMIT 10;Output Example
(Displays the 10 most recent system log records cleanly)When to Use
Use this database statement when you need to perform actions related to 'SELECT' on your database tables.
Common Mistakes
Omitting filters (WHERE clause) or schema qualifications, causing mass modification or high performance impacts.
Shortcut / Pro-Tip
Ensure relevant indices are configured on the queried columns to boost index lookups.Example
SELECT column AS alias_name FROM table_name;Output Example
Query OK. Affected rows: 1 (0.02 sec)Filtering
When to Use
When filtering down rows returned from your tables based on matching column values, text patterns, or lists.
Common Mistakes
Using wildcard lookups starting with % (e.g. LIKE '%pattern') on large tables as it bypasses database indices.
Shortcut / Pro-Tip
Use indexable columns in WHERE filters to optimize search velocity.Example
SELECT * FROM table_name WHERE condition;Output Example
Query OK. Affected rows: 1 (0.02 sec)When to Use
When filtering down rows returned from your tables based on matching column values, text patterns, or lists.
Common Mistakes
Using wildcard lookups starting with % (e.g. LIKE '%pattern') on large tables as it bypasses database indices.
Shortcut / Pro-Tip
Use indexable columns in WHERE filters to optimize search velocity.Example
SELECT * FROM table_name WHERE col1 = 'val' AND col2 > 5;Output Example
Query OK. Affected rows: 1 (0.02 sec)When to Use
When filtering down rows returned from your tables based on matching column values, text patterns, or lists.
Common Mistakes
Using wildcard lookups starting with % (e.g. LIKE '%pattern') on large tables as it bypasses database indices.
Shortcut / Pro-Tip
Use indexable columns in WHERE filters to optimize search velocity.Example
SELECT * FROM table_name WHERE column LIKE 'A%';Output Example
Query OK. Affected rows: 1 (0.02 sec)When to Use
When filtering down rows returned from your tables based on matching column values, text patterns, or lists.
Common Mistakes
Using wildcard lookups starting with % (e.g. LIKE '%pattern') on large tables as it bypasses database indices.
Shortcut / Pro-Tip
Use indexable columns in WHERE filters to optimize search velocity.Example
SELECT * FROM table_name WHERE column IN (val1, val2);Output Example
Query OK. Affected rows: 1 (0.02 sec)When to Use
When filtering down rows returned from your tables based on matching column values, text patterns, or lists.
Common Mistakes
Using wildcard lookups starting with % (e.g. LIKE '%pattern') on large tables as it bypasses database indices.
Shortcut / Pro-Tip
Use indexable columns in WHERE filters to optimize search velocity.Example
SELECT * FROM table_name WHERE column BETWEEN 10 AND 50;Output Example
Query OK. Affected rows: 1 (0.02 sec)Joining
When to Use
When querying relational databases and you need to combine related columns from multiple tables matching on a shared key or foreign key relationship.
Common Mistakes
Creating massive Cartesian products by joining tables without specifying an ON condition, crashing DB memory allocation.
Shortcut / Pro-Tip
Use explicit table aliases (e.g. 'users u JOIN profiles p') to keep queries clean and compact.Example
SELECT * FROM t1 INNER JOIN t2 ON t1.id = t2.id;Output Example
Query OK. Affected rows: 1 (0.02 sec)When to Use
When querying relational databases and you need to combine related columns from multiple tables matching on a shared key or foreign key relationship.
Common Mistakes
Creating massive Cartesian products by joining tables without specifying an ON condition, crashing DB memory allocation.
Shortcut / Pro-Tip
Use explicit table aliases (e.g. 'users u JOIN profiles p') to keep queries clean and compact.Example
SELECT * FROM t1 LEFT JOIN t2 ON t1.id = t2.id;Output Example
Query OK. Affected rows: 1 (0.02 sec)When to Use
When querying relational databases and you need to combine related columns from multiple tables matching on a shared key or foreign key relationship.
Common Mistakes
Creating massive Cartesian products by joining tables without specifying an ON condition, crashing DB memory allocation.
Shortcut / Pro-Tip
Use explicit table aliases (e.g. 'users u JOIN profiles p') to keep queries clean and compact.Example
SELECT * FROM t1 RIGHT JOIN t2 ON t1.id = t2.id;Output Example
Query OK. Affected rows: 1 (0.02 sec)When to Use
When querying relational databases and you need to combine related columns from multiple tables matching on a shared key or foreign key relationship.
Common Mistakes
Creating massive Cartesian products by joining tables without specifying an ON condition, crashing DB memory allocation.
Shortcut / Pro-Tip
Use explicit table aliases (e.g. 'users u JOIN profiles p') to keep queries clean and compact.Example
SELECT * FROM t1 FULL OUTER JOIN t2 ON t1.id = t2.id;Output Example
Query OK. Affected rows: 1 (0.02 sec)Aggregation
When to Use
When analyzing data density to find how many items or records belong to each separate business category.
Common Mistakes
Using non-grouped columns in the SELECT statement, which violates ANSI SQL standards and causes database errors.
Shortcut / Pro-Tip
Use 'as' aliases to rename your aggregates immediately: COUNT(*) as total_ordersExample
SELECT COUNT(*), status FROM orders GROUP BY status;Output Example
count | status
------+-----------
1520 | completed
84 | pending
12 | cancelledWhen to Use
Use this database statement when you need to perform actions related to 'SELECT' on your database tables.
Common Mistakes
Omitting filters (WHERE clause) or schema qualifications, causing mass modification or high performance impacts.
Shortcut / Pro-Tip
Ensure relevant indices are configured on the queried columns to boost index lookups.Example
SELECT SUM(salary) FROM employees;Output Example
Query OK. Affected rows: 1 (0.02 sec)When to Use
Use this database statement when you need to perform actions related to 'SELECT' on your database tables.
Common Mistakes
Omitting filters (WHERE clause) or schema qualifications, causing mass modification or high performance impacts.
Shortcut / Pro-Tip
Ensure relevant indices are configured on the queried columns to boost index lookups.Example
SELECT AVG(price) FROM products;Output Example
Query OK. Affected rows: 1 (0.02 sec)When to Use
When filtering down rows returned from your tables based on matching column values, text patterns, or lists.
Common Mistakes
Using wildcard lookups starting with % (e.g. LIKE '%pattern') on large tables as it bypasses database indices.
Shortcut / Pro-Tip
Use indexable columns in WHERE filters to optimize search velocity.Example
SELECT MAX(score), MIN(score) FROM students;Output Example
Query OK. Affected rows: 1 (0.02 sec)When to Use
When filtering down rows returned from your tables based on matching column values, text patterns, or lists.
Common Mistakes
Using wildcard lookups starting with % (e.g. LIKE '%pattern') on large tables as it bypasses database indices.
Shortcut / Pro-Tip
Use indexable columns in WHERE filters to optimize search velocity.Example
SELECT count(*), category FROM table GROUP BY category HAVING count(*) > 5;Output Example
Query OK. Affected rows: 1 (0.02 sec)Modifying
When to Use
When filtering down rows returned from your tables based on matching column values, text patterns, or lists.
Common Mistakes
Using wildcard lookups starting with % (e.g. LIKE '%pattern') on large tables as it bypasses database indices.
Shortcut / Pro-Tip
Use indexable columns in WHERE filters to optimize search velocity.Example
INSERT INTO table_name (col1, col2) VALUES (val1, val2);Output Example
Query OK. Affected rows: 1 (0.02 sec)When to Use
When filtering down rows returned from your tables based on matching column values, text patterns, or lists.
Common Mistakes
Using wildcard lookups starting with % (e.g. LIKE '%pattern') on large tables as it bypasses database indices.
Shortcut / Pro-Tip
Use indexable columns in WHERE filters to optimize search velocity.Example
UPDATE table_name SET col1 = 'new_val' WHERE id = 1;Output Example
Query OK. Affected rows: 1 (0.02 sec)When to Use
When filtering down rows returned from your tables based on matching column values, text patterns, or lists.
Common Mistakes
Using wildcard lookups starting with % (e.g. LIKE '%pattern') on large tables as it bypasses database indices.
Shortcut / Pro-Tip
Use indexable columns in WHERE filters to optimize search velocity.Example
DELETE FROM table_name WHERE id = 10;Output Example
Query OK. Affected rows: 1 (0.02 sec)DDL
When to Use
Use this database statement when you need to perform actions related to 'CREATE' on your database tables.
Common Mistakes
Omitting filters (WHERE clause) or schema qualifications, causing mass modification or high performance impacts.
Shortcut / Pro-Tip
Ensure relevant indices are configured on the queried columns to boost index lookups.Example
CREATE TABLE users (
id SERIAL PRIMARY KEY,
username VARCHAR(50) UNIQUE,
created_at TIMESTAMP DEFAULT NOW()
);Output Example
Query OK. Affected rows: 1 (0.02 sec)When to Use
Use this database statement when you need to perform actions related to 'ALTER' on your database tables.
Common Mistakes
Omitting filters (WHERE clause) or schema qualifications, causing mass modification or high performance impacts.
Shortcut / Pro-Tip
Ensure relevant indices are configured on the queried columns to boost index lookups.Example
ALTER TABLE table_name ADD column_name datatype;Output Example
Query OK. Affected rows: 1 (0.02 sec)When to Use
Use this database statement when you need to perform actions related to 'DROP' on your database tables.
Common Mistakes
Omitting filters (WHERE clause) or schema qualifications, causing mass modification or high performance impacts.
Shortcut / Pro-Tip
Ensure relevant indices are configured on the queried columns to boost index lookups.Example
DROP TABLE IF EXISTS table_name;Output Example
Query OK. Affected rows: 1 (0.02 sec)SQL Best Practices
1Use Specific Column Names
Avoid SELECT * in production queries. Only fetch the exact columns you need to minimize network payload and database execution load.
2Index Highly-Searched Columns
Configure database indices on columns frequently queried in WHERE clauses, JOIN keys, and ORDER BY conditions.
3Always Use Parametrized Queries
Never concatenate strings to build raw SQL queries, protecting your database against catastrophic SQL injection attacks.
4Use EXPLAIN to Analyze Slow Queries
Prepend EXPLAIN to queries to analyze the execution path, identify table scans, and optimize your indexes.
5Keep Database Operations in Transactions
Group multi-step inserts/updates in a BEGIN ... COMMIT block to maintain transactional atomic consistency (ACID).
Common SQL Errors & Solutions
Subquery returned more than 1 row
Ensure you use the 'IN' operator instead of '=' when comparing a query column against subquery results.
Column must appear in the GROUP BY clause or be used in an aggregate function
When using GROUP BY, every selected column must either be a grouping key or wrapped inside an aggregate (COUNT, SUM, AVG, etc.).
Lock wait timeout exceeded; try restarting transaction
A concurrent process has locked the requested rows. Ensure transactions are kept short, fast, and commit immediately.
Duplicate key value violates unique constraint
You are attempting to insert an index key that already exists. Implement UPSERT (INSERT ... ON CONFLICT DO UPDATE) to merge.
Cannot delete or update a parent row: a foreign key constraint fails
You must first delete or modify dependent child rows in secondary tables before deleting the parent row record.
Common SQL Interview Questions
Q1What is the difference between INNER JOIN, LEFT JOIN, and RIGHT JOIN?
INNER JOIN returns rows only when there is a match in both tables. LEFT JOIN returns all rows from the left table and matching rows from the right table (unmatched columns are NULL). RIGHT JOIN does the reverse, returning all rows from the right table.
Q2What is the difference between WHERE and HAVING clauses?
WHERE filters raw individual row records before any groupings are executed. HAVING is used to filter aggregated groups after the GROUP BY clause is executed.
Q3What are the four core ACID properties in database systems?
Atomicity (all operations succeed or all fail), Consistency (transitions DB from one valid state to another), Isolation (concurrent executions do not interfere), and Durability (committed updates are saved permanently).
Q4What is the difference between primary keys and unique keys?
A table can have only one Primary Key, which uniquely identifies each row and cannot contain NULL values. A table can have multiple Unique Keys, which also enforce unique row records but allow NULL values.
Q5What is database normalization and why is it used?
Normalization is the process of structuring relational database columns and tables to minimize data redundancy and eliminate update/delete anomalies.
Related Resources
CSV to SQL Converter
Transform Comma-Separated Values (CSV) data into SQL INSERT statements instantly.
SQL Injection Prevention Guide
Learn secure SQL query execution patterns and real-world vulnerability prevention.
Docker Cheatsheet
Quick reference guide for managing Docker containers, images, volumes, and networks.
Database Security Essentials
Secure credentials management, vault configurations, and DB access controls.
Generated from LearnHubly Developer Cheatsheets
Access interactive sandbox tests, tools, and developer code bases at https://www.learnhubly.com