Database
Updated for 2026

SQL Queries & Commands Cheatsheet 2026

Complete guide to SQL statements including SELECT queries, WHERE filters, aggregate functions, JOIN types, and DDL commands.

Target Version Compatibility

Interactive Skill Mastery

Mark commands as learned to build your customized reference tracker. Retained locally in this browser.

Level:Novice
Command Mastery Progress0 of 25 Mastered (0%)

Querying

SELECT * FROM table_name;
BeginnerBasics
Retrieve all columns and rows from a database table.

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

Console / Terminal
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:00
SELECT column1, column2 FROM table_name;
BeginnerBasics
Select specific columns to reduce query payload.

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 column1, column2 FROM table_name;

Output Example

Console / Terminal
Query OK. Affected rows: 1 (0.02 sec)
SELECT DISTINCT column_name FROM table_name;
BeginnerBasics
Retrieve only unique values, eliminating duplicate entries.

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

Console / Terminal
Query OK. Affected rows: 1 (0.02 sec)
SELECT * FROM table_name LIMIT 10;
IntermediateAdvanced
Restrict the maximum number of returned rows to 10.

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 bandwidth

Example

SELECT * FROM logs ORDER BY created_at DESC LIMIT 10;

Output Example

Console / Terminal
(Displays the 10 most recent system log records cleanly)
SELECT column AS alias_name FROM table_name;
BeginnerBasics
Assign a temporary friendly alias to a returned column.

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

Console / Terminal
Query OK. Affected rows: 1 (0.02 sec)

Filtering

SELECT * FROM table_name WHERE condition;
BeginnerBasics
Filter row records matching specific criteria.

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

Console / Terminal
Query OK. Affected rows: 1 (0.02 sec)
SELECT * FROM table_name WHERE col1 = 'val' AND col2 > 5;
BeginnerBasics
Combine multiple query conditions that must all be satisfied.

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

Console / Terminal
Query OK. Affected rows: 1 (0.02 sec)
SELECT * FROM table_name WHERE column LIKE 'A%';
BeginnerBasics
Perform wildcard searches for text patterns starting with letter A.

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

Console / Terminal
Query OK. Affected rows: 1 (0.02 sec)
SELECT * FROM table_name WHERE column IN (val1, val2);
BeginnerBasics
Select rows where column values match any item in a discrete list.

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

Console / Terminal
Query OK. Affected rows: 1 (0.02 sec)
SELECT * FROM table_name WHERE column BETWEEN 10 AND 50;
BeginnerBasics
Filter values within an inclusive numeric or date range.

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

Console / Terminal
Query OK. Affected rows: 1 (0.02 sec)

Joining

SELECT * FROM t1 INNER JOIN t2 ON t1.id = t2.id;
IntermediateAdvanced
Combine rows from two tables where there is an identical key match.

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

Console / Terminal
Query OK. Affected rows: 1 (0.02 sec)
SELECT * FROM t1 LEFT JOIN t2 ON t1.id = t2.id;
IntermediateAdvanced
Retrieve all rows from left table (t1) and matching rows from right table (t2).

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

Console / Terminal
Query OK. Affected rows: 1 (0.02 sec)
SELECT * FROM t1 RIGHT JOIN t2 ON t1.id = t2.id;
IntermediateAdvanced
Retrieve all rows from right table (t2) and matching rows from left table (t1).

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

Console / Terminal
Query OK. Affected rows: 1 (0.02 sec)
SELECT * FROM t1 FULL OUTER JOIN t2 ON t1.id = t2.id;
IntermediateAdvanced
Retrieve records when there is a match in either left or right table.

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

Console / Terminal
Query OK. Affected rows: 1 (0.02 sec)

Aggregation

SELECT COUNT(*), category FROM table GROUP BY category;
BeginnerBasics
Group records and count the quantity in each categorized group.

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_orders

Example

SELECT COUNT(*), status FROM orders GROUP BY status;

Output Example

Console / Terminal
count | status
------+-----------
1520  | completed
84    | pending
12    | cancelled
SELECT SUM(salary) FROM employees;
BeginnerBasics
Calculate the total summation of a numeric column.

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 SUM(salary) FROM employees;

Output Example

Console / Terminal
Query OK. Affected rows: 1 (0.02 sec)
SELECT AVG(price) FROM products;
BeginnerBasics
Calculate the mathematical average of values in a column.

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

Console / Terminal
Query OK. Affected rows: 1 (0.02 sec)
SELECT MAX(score), MIN(score) FROM students;
BeginnerBasics
Find the maximum and minimum values in a numeric range.

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

Console / Terminal
Query OK. Affected rows: 1 (0.02 sec)
SELECT count(*), category FROM table GROUP BY category HAVING count(*) > 5;
BeginnerBasics
Filter aggregated groups using HAVING clause criteria.

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

Console / Terminal
Query OK. Affected rows: 1 (0.02 sec)

Modifying

INSERT INTO table_name (col1, col2) VALUES (val1, val2);
BeginnerBasics
Insert a new row of data record into the specified table.

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

Console / Terminal
Query OK. Affected rows: 1 (0.02 sec)
UPDATE table_name SET col1 = 'new_val' WHERE id = 1;
BeginnerBasics
Modify columns on existing row records matching a condition.

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

Console / Terminal
Query OK. Affected rows: 1 (0.02 sec)
DELETE FROM table_name WHERE id = 10;
AdvancedRecovery
Safely delete specific rows matching a query condition.

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

Console / Terminal
Query OK. Affected rows: 1 (0.02 sec)

DDL

CREATE TABLE users ( id SERIAL PRIMARY KEY, username VARCHAR(50) UNIQUE, created_at TIMESTAMP DEFAULT NOW() );
BeginnerBasics
Create a new database table and specify columns, keys, and default constraints.

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

Console / Terminal
Query OK. Affected rows: 1 (0.02 sec)
ALTER TABLE table_name ADD column_name datatype;
BeginnerBasics
Modify an existing table structure by appending a new column.

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

Console / Terminal
Query OK. Affected rows: 1 (0.02 sec)
DROP TABLE IF EXISTS table_name;
AdvancedRecovery
Permanently delete an entire database table and its data from schema.

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

Console / Terminal
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

Error

Subquery returned more than 1 row

Solution

Ensure you use the 'IN' operator instead of '=' when comparing a query column against subquery results.

Error

Column must appear in the GROUP BY clause or be used in an aggregate function

Solution

When using GROUP BY, every selected column must either be a grouping key or wrapped inside an aggregate (COUNT, SUM, AVG, etc.).

Error

Lock wait timeout exceeded; try restarting transaction

Solution

A concurrent process has locked the requested rows. Ensure transactions are kept short, fast, and commit immediately.

Error

Duplicate key value violates unique constraint

Solution

You are attempting to insert an index key that already exists. Implement UPSERT (INSERT ... ON CONFLICT DO UPDATE) to merge.

Error

Cannot delete or update a parent row: a foreign key constraint fails

Solution

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.