Menu

Tools

Top 100+ SQL Commands

Master essential SQL commands with examples for MySQL, PostgreSQL, Oracle, and SQL Server

112 commands

SELECT

Basics
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Retrieves data from one or more tables. The most fundamental SQL command for querying data.

Example

SELECT first_name, last_name, email
FROM employees
WHERE department = 'Sales';

Output

first_name | last_name | email
-----------|----------|------------------
John       | Smith    | john@company.com
Jane       | Doe      | jane@company.com

SELECT *

Basics
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Selects all columns from a table. Use cautiously in production as it can impact performance.

Example

SELECT * FROM products
LIMIT 5;

Output

id | name    | price  | category
---|---------|--------|----------
1  | Laptop  | 999.99 | Electronics
2  | Mouse   | 29.99  | Electronics
Pro Tip: Avoid SELECT * in production. Always specify needed columns.

WHERE

Basics
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Filters records based on specified conditions. Essential for querying specific data.

Example

SELECT * FROM orders
WHERE status = 'pending'
AND total_amount > 100;

Output

order_id | customer | total_amount | status
---------|----------|--------------|--------
1001     | Alice    | 250.00       | pending
1005     | Bob      | 175.50       | pending

ORDER BY

Basics
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Sorts the result set by one or more columns. Use ASC for ascending (default) or DESC for descending.

Example

SELECT name, price
FROM products
ORDER BY price DESC, name ASC;

Output

name         | price
-------------|--------
Laptop Pro   | 1499.99
Laptop       | 999.99
Tablet       | 599.99

LIMIT / TOP / FETCH

Basics
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Limits the number of rows returned. Syntax varies by database.

Example

-- MySQL/PostgreSQL
SELECT * FROM users LIMIT 10;

-- SQL Server
SELECT TOP 10 * FROM users;

-- Oracle
SELECT * FROM users FETCH FIRST 10 ROWS ONLY;

Output

(Returns first 10 rows)
Pro Tip: Always use LIMIT with ORDER BY for consistent results.

DISTINCT

Basics
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Returns only unique/distinct values, eliminating duplicates from the result set.

Example

SELECT DISTINCT department
FROM employees
ORDER BY department;

Output

department
-----------
Engineering
Marketing
Sales
Support

AS (Alias)

Basics
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Assigns a temporary name to a column or table for readability.

Example

SELECT 
    first_name AS "First Name",
    salary * 12 AS annual_salary
FROM employees e
WHERE e.department = 'IT';

Output

First Name | annual_salary
-----------|---------------
John       | 72000
Jane       | 84000

LIKE

Basics
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Pattern matching using wildcards. % matches any characters, _ matches single character.

Example

SELECT * FROM customers
WHERE email LIKE '%@gmail.com'
AND name LIKE 'J___';

Output

id | name | email
---|------|-------------------
5  | John | john@gmail.com
12 | Jane | jane123@gmail.com
Pro Tip: LIKE with leading % cannot use indexes efficiently.

IN

Basics
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Checks if a value matches any value in a list. Cleaner than multiple OR conditions.

Example

SELECT * FROM orders
WHERE status IN ('pending', 'processing', 'shipped');

Output

order_id | status
---------|----------
1001     | pending
1002     | shipped
1003     | processing

BETWEEN

Basics
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Selects values within a given range (inclusive).

Example

SELECT * FROM products
WHERE price BETWEEN 50 AND 200
ORDER BY price;

Output

name    | price
--------|-------
Mouse   | 59.99
Keyboard| 89.99
Monitor | 199.99

IS NULL / IS NOT NULL

Basics
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Checks for NULL values. Cannot use = or != with NULL.

Example

SELECT * FROM employees
WHERE manager_id IS NULL;

-- Find all assigned employees
SELECT * FROM employees
WHERE manager_id IS NOT NULL;

Output

id | name | manager_id
---|------|------------
1  | CEO  | NULL
Pro Tip: NULL represents unknown value, not zero or empty string.

AND / OR / NOT

Basics
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Logical operators to combine multiple conditions in WHERE clause.

Example

SELECT * FROM products
WHERE (category = 'Electronics' OR category = 'Gadgets')
AND price < 500
AND NOT discontinued;

Output

name   | category    | price
-------|-------------|-------
Mouse  | Electronics | 29.99
Tablet | Gadgets     | 399.99

OFFSET

Basics
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Skips a specified number of rows before returning results. Used for pagination.

Example

-- Page 2 with 10 items per page
SELECT * FROM products
ORDER BY id
LIMIT 10 OFFSET 10;

Output

(Returns rows 11-20)
Pro Tip: For large offsets, use keyset pagination instead.

CASE WHEN

Basics
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Conditional logic in SQL, similar to if-else statements in programming.

Example

SELECT name, price,
    CASE 
        WHEN price < 50 THEN 'Budget'
        WHEN price < 200 THEN 'Mid-range'
        ELSE 'Premium'
    END AS price_tier
FROM products;

Output

name   | price  | price_tier
-------|--------|----------
Mouse  | 29.99  | Budget
Laptop | 999.99 | Premium

COALESCE

Basics
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Returns the first non-NULL value from a list. Great for default values.

Example

SELECT 
    name,
    COALESCE(nickname, first_name, 'Unknown') AS display_name
FROM users;

Output

name      | display_name
----------|-------------
John Doe  | Johnny
Jane Smith| Jane

INSERT INTO

DML
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Adds new rows to a table. Can insert single or multiple rows.

Example

INSERT INTO employees (name, email, department)
VALUES ('John Doe', 'john@company.com', 'Engineering');

Output

1 row inserted.

INSERT Multiple Rows

DML
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Inserts multiple rows in a single statement for better performance.

Example

INSERT INTO products (name, price)
VALUES 
    ('Keyboard', 79.99),
    ('Mouse', 29.99),
    ('Monitor', 299.99);

Output

3 rows inserted.
Pro Tip: Batch inserts are much faster than individual inserts.

INSERT SELECT

DML
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Inserts data from one table into another using a SELECT query.

Example

INSERT INTO orders_archive
SELECT * FROM orders
WHERE order_date < '2024-01-01';

Output

1523 rows inserted.

UPDATE

DML
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Modifies existing records in a table. Always use WHERE to avoid updating all rows.

Example

UPDATE employees
SET salary = salary * 1.10,
    updated_at = CURRENT_TIMESTAMP
WHERE department = 'Engineering';

Output

25 rows updated.
Pro Tip: Always test UPDATE with SELECT first to verify affected rows.

UPDATE with JOIN

DML
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Updates records based on data from another table.

Example

-- MySQL
UPDATE orders o
JOIN customers c ON o.customer_id = c.id
SET o.shipping_address = c.address
WHERE o.shipping_address IS NULL;

Output

47 rows updated.

DELETE

DML
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Removes rows from a table. Use WHERE clause to avoid deleting all data.

Example

DELETE FROM sessions
WHERE expires_at < CURRENT_TIMESTAMP;

Output

156 rows deleted.
Pro Tip: Consider using soft delete (is_deleted flag) instead.

DELETE with JOIN

DML
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Deletes rows based on conditions in related tables.

Example

-- MySQL
DELETE o FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE c.status = 'inactive';

Output

23 rows deleted.

UPSERT (INSERT ON CONFLICT)

DML
🐬 MySQL
🐘 PostgreSQL
πŸ”· SQL Server

What It Does

Inserts a row or updates if it already exists. Syntax varies by database.

Example

-- PostgreSQL
INSERT INTO users (email, name)
VALUES ('john@email.com', 'John')
ON CONFLICT (email) 
DO UPDATE SET name = EXCLUDED.name;

Output

1 row upserted.
Pro Tip: MySQL uses ON DUPLICATE KEY UPDATE syntax.

MERGE

DML
πŸ…ΎοΈ Oracle
πŸ”· SQL Server
🐘 PostgreSQL

What It Does

Standard SQL UPSERT. Performs insert, update, or delete based on conditions.

Example

MERGE INTO target_table t
USING source_table s ON t.id = s.id
WHEN MATCHED THEN UPDATE SET t.name = s.name
WHEN NOT MATCHED THEN INSERT (id, name) VALUES (s.id, s.name);

Output

100 rows merged.

REPLACE INTO

DML
🐬 MySQL

What It Does

MySQL-specific: Deletes existing row and inserts new one if duplicate key exists.

Example

REPLACE INTO settings (key, value)
VALUES ('theme', 'dark');

Output

1 row affected.
Pro Tip: REPLACE deletes then inserts, losing any unspecified column data.

CREATE TABLE

DDL
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Creates a new table with specified columns and constraints.

Example

CREATE TABLE employees (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(255) UNIQUE,
    salary DECIMAL(10,2) DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Output

Table created.

CREATE TABLE AS

DDL
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Creates a new table from the result of a SELECT query.

Example

CREATE TABLE high_value_customers AS
SELECT * FROM customers
WHERE total_purchases > 10000;

Output

Table created with 523 rows.

ALTER TABLE ADD

DDL
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Adds a new column to an existing table.

Example

ALTER TABLE employees
ADD COLUMN phone VARCHAR(20),
ADD COLUMN address TEXT;

Output

Table altered.

ALTER TABLE MODIFY

DDL
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Changes the data type or constraints of an existing column.

Example

-- MySQL
ALTER TABLE products
MODIFY COLUMN price DECIMAL(12,2) NOT NULL;

-- PostgreSQL
ALTER TABLE products
ALTER COLUMN price TYPE DECIMAL(12,2);

Output

Table altered.

ALTER TABLE DROP

DDL
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Removes a column from an existing table.

Example

ALTER TABLE employees
DROP COLUMN temporary_notes;

Output

Table altered.
Pro Tip: Dropping columns is irreversible. Always backup first.

ALTER TABLE RENAME

DDL
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Renames a table or column.

Example

-- Rename table
ALTER TABLE users RENAME TO customers;

-- Rename column (MySQL)
ALTER TABLE customers
RENAME COLUMN name TO full_name;

Output

Table altered.

DROP TABLE

DDL
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Permanently deletes a table and all its data.

Example

DROP TABLE IF EXISTS temp_data;

Output

Table dropped.
Pro Tip: Use IF EXISTS to avoid errors if table does not exist.

TRUNCATE TABLE

DDL
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Removes all rows from a table quickly. Cannot rollback in some databases.

Example

TRUNCATE TABLE log_entries;

Output

Table truncated.
Pro Tip: TRUNCATE is faster than DELETE but cannot be rolled back in MySQL.

CREATE DATABASE

DDL
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Creates a new database.

Example

CREATE DATABASE IF NOT EXISTS ecommerce
CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;

Output

Database created.

DROP DATABASE

DDL
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Permanently deletes an entire database and all its objects.

Example

DROP DATABASE IF EXISTS test_db;

Output

Database dropped.
Pro Tip: Extremely dangerous! Ensure backups exist before dropping.

CREATE SCHEMA

DDL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Creates a logical container for database objects. Used for organization.

Example

CREATE SCHEMA IF NOT EXISTS analytics;

CREATE TABLE analytics.user_events (
    id SERIAL PRIMARY KEY,
    event_type VARCHAR(50)
);

Output

Schema created.

COMMENT ON

DDL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle

What It Does

Adds descriptive comments to database objects for documentation.

Example

COMMENT ON TABLE employees IS 'Stores employee information';
COMMENT ON COLUMN employees.salary IS 'Monthly salary in USD';

Output

Comment added.

PRIMARY KEY

Constraints
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Uniquely identifies each row in a table. Cannot contain NULL values.

Example

CREATE TABLE orders (
    order_id INT PRIMARY KEY,
    customer_id INT,
    order_date DATE
);

-- Composite primary key
CREATE TABLE order_items (
    order_id INT,
    product_id INT,
    PRIMARY KEY (order_id, product_id)
);

Output

Table created with primary key.

FOREIGN KEY

Constraints
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Links two tables together, ensuring referential integrity.

Example

CREATE TABLE orders (
    id INT PRIMARY KEY,
    customer_id INT,
    FOREIGN KEY (customer_id) 
        REFERENCES customers(id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

Output

Table created with foreign key.
Pro Tip: Use ON DELETE CASCADE carefully - it deletes child rows automatically.

UNIQUE

Constraints
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Ensures all values in a column are different. Allows one NULL.

Example

CREATE TABLE users (
    id INT PRIMARY KEY,
    email VARCHAR(255) UNIQUE,
    username VARCHAR(50) UNIQUE
);

Output

Table created with unique constraints.

NOT NULL

Constraints
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Ensures a column cannot have NULL value.

Example

CREATE TABLE products (
    id INT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    price DECIMAL(10,2) NOT NULL DEFAULT 0
);

Output

Table created.

CHECK

Constraints
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Validates that values in a column meet a specific condition.

Example

CREATE TABLE employees (
    id INT PRIMARY KEY,
    age INT CHECK (age >= 18 AND age <= 100),
    salary DECIMAL(10,2) CHECK (salary > 0)
);

Output

Table created with check constraints.
Pro Tip: MySQL only enforces CHECK constraints from version 8.0.16+

DEFAULT

Constraints
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Sets a default value for a column when none is provided.

Example

CREATE TABLE articles (
    id INT PRIMARY KEY,
    status VARCHAR(20) DEFAULT 'draft',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    views INT DEFAULT 0
);

Output

Table created with defaults.

ADD CONSTRAINT

Constraints
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Adds a constraint to an existing table.

Example

ALTER TABLE orders
ADD CONSTRAINT fk_customer
FOREIGN KEY (customer_id) REFERENCES customers(id);

ALTER TABLE products
ADD CONSTRAINT chk_price CHECK (price >= 0);

Output

Constraint added.

DROP CONSTRAINT

Constraints
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Removes a constraint from a table.

Example

ALTER TABLE orders
DROP CONSTRAINT fk_customer;

-- MySQL syntax
ALTER TABLE orders
DROP FOREIGN KEY fk_customer;

Output

Constraint dropped.

INNER JOIN

Joins
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Returns rows that have matching values in both tables.

Example

SELECT o.order_id, c.name, o.total
FROM orders o
INNER JOIN customers c ON o.customer_id = c.id;

Output

order_id | name  | total
---------|-------|-------
1001     | Alice | 250.00
1002     | Bob   | 175.50

LEFT JOIN

Joins
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Returns all rows from left table and matched rows from right table. NULLs for no match.

Example

SELECT c.name, o.order_id
FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id;

Output

name  | order_id
------|----------
Alice | 1001
Bob   | 1002
Charlie | NULL
Pro Tip: Use LEFT JOIN to find records without related data.

RIGHT JOIN

Joins
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Returns all rows from right table and matched rows from left table.

Example

SELECT e.name, d.department_name
FROM employees e
RIGHT JOIN departments d ON e.dept_id = d.id;

Output

name | department_name
-----|----------------
John | Engineering
NULL | Marketing

FULL OUTER JOIN

Joins
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Returns all rows when there is a match in either table.

Example

SELECT c.name, o.order_id
FROM customers c
FULL OUTER JOIN orders o ON c.id = o.customer_id;

Output

name    | order_id
--------|----------
Alice   | 1001
NULL    | 1005
Charlie | NULL
Pro Tip: MySQL does not support FULL OUTER JOIN directly.

CROSS JOIN

Joins
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Returns Cartesian product - every combination of rows from both tables.

Example

SELECT sizes.name, colors.name
FROM sizes
CROSS JOIN colors;

Output

size  | color
------|------
Small | Red
Small | Blue
Large | Red
Large | Blue
Pro Tip: Be careful - this can produce very large result sets!

SELF JOIN

Joins
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Joins a table to itself. Useful for hierarchical or comparative queries.

Example

SELECT e.name AS employee,
       m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;

Output

employee | manager
---------|--------
John     | Alice
Alice    | NULL
Bob      | Alice

NATURAL JOIN

Joins
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle

What It Does

Automatically joins tables on columns with the same name.

Example

SELECT * FROM orders
NATURAL JOIN customers;

Output

(Joins on matching column names)
Pro Tip: Avoid NATURAL JOIN - explicit JOINs are clearer and safer.

Multiple JOINs

Joins
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Combines data from three or more tables in a single query.

Example

SELECT o.order_id, c.name, p.product_name
FROM orders o
JOIN customers c ON o.customer_id = c.id
JOIN order_items oi ON o.id = oi.order_id
JOIN products p ON oi.product_id = p.id;

Output

order_id | name  | product_name
---------|-------|-------------
1001     | Alice | Laptop
1001     | Alice | Mouse

COUNT

Aggregates
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Returns the number of rows matching the query. COUNT(*) includes NULLs.

Example

SELECT 
    COUNT(*) AS total_orders,
    COUNT(DISTINCT customer_id) AS unique_customers
FROM orders;

Output

total_orders | unique_customers
-------------|------------------
1523         | 456

SUM

Aggregates
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Calculates the total of a numeric column.

Example

SELECT 
    SUM(total_amount) AS revenue,
    SUM(quantity) AS items_sold
FROM orders
WHERE order_date >= '2024-01-01';

Output

revenue    | items_sold
-----------|----------
125430.50  | 3421

AVG

Aggregates
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Calculates the average of a numeric column. Ignores NULL values.

Example

SELECT 
    AVG(salary) AS avg_salary,
    AVG(age) AS avg_age
FROM employees
WHERE department = 'Engineering';

Output

avg_salary | avg_age
-----------|--------
85000.00   | 32.5

MIN / MAX

Aggregates
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Returns the minimum or maximum value in a column.

Example

SELECT 
    MIN(price) AS cheapest,
    MAX(price) AS most_expensive,
    MAX(order_date) AS last_order
FROM products;

Output

cheapest | most_expensive | last_order
---------|----------------|------------
9.99     | 2499.99        | 2024-01-15

GROUP BY

Aggregates
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Groups rows sharing a property to calculate aggregates per group.

Example

SELECT 
    department,
    COUNT(*) AS employee_count,
    AVG(salary) AS avg_salary
FROM employees
GROUP BY department
ORDER BY employee_count DESC;

Output

department  | employee_count | avg_salary
------------|----------------|----------
Engineering | 45             | 92000.00
Sales       | 32             | 68000.00

HAVING

Aggregates
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Filters groups after GROUP BY. Like WHERE but for aggregated data.

Example

SELECT 
    customer_id,
    COUNT(*) AS order_count,
    SUM(total) AS total_spent
FROM orders
GROUP BY customer_id
HAVING COUNT(*) >= 5 AND SUM(total) > 1000;

Output

customer_id | order_count | total_spent
------------|-------------|------------
101         | 12          | 3450.00
205         | 8           | 2100.50
Pro Tip: HAVING filters after grouping, WHERE filters before.

GROUP_CONCAT / STRING_AGG

Aggregates
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Concatenates values from multiple rows into a single string.

Example

-- MySQL
SELECT department, GROUP_CONCAT(name) AS members
FROM employees GROUP BY department;

-- PostgreSQL
SELECT department, STRING_AGG(name, ', ') AS members
FROM employees GROUP BY department;

Output

department | members
-----------|------------------
Sales      | Alice, Bob, Charlie

ROLLUP

Aggregates
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Creates subtotals and grand totals for grouped data.

Example

SELECT 
    department, 
    job_title,
    SUM(salary) AS total_salary
FROM employees
GROUP BY ROLLUP(department, job_title);

Output

department | job_title | total_salary
-----------|-----------|-------------
Sales      | Manager   | 150000
Sales      | Rep       | 200000
Sales      | NULL      | 350000
NULL       | NULL      | 850000

CUBE

Aggregates
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Creates subtotals for all combinations of grouped columns.

Example

SELECT 
    region, 
    product,
    SUM(sales) AS total
FROM sales_data
GROUP BY CUBE(region, product);

Output

(All possible subtotal combinations)

GROUPING SETS

Aggregates
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Defines specific grouping combinations for aggregation.

Example

SELECT department, year, SUM(revenue)
FROM sales
GROUP BY GROUPING SETS (
    (department),
    (year),
    (department, year)
);

Output

(Custom grouping combinations)

CONCAT

Functions
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Joins two or more strings together.

Example

SELECT CONCAT(first_name, ' ', last_name) AS full_name
FROM employees;

-- PostgreSQL alternative
SELECT first_name || ' ' || last_name AS full_name
FROM employees;

Output

full_name
-----------
John Smith
Jane Doe

SUBSTRING / SUBSTR

Functions
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Extracts a portion of a string.

Example

SELECT 
    SUBSTRING(phone, 1, 3) AS area_code,
    SUBSTRING(email, POSITION('@' IN email) + 1) AS domain
FROM contacts;

Output

area_code | domain
----------|----------
555       | gmail.com
212       | yahoo.com

UPPER / LOWER

Functions
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Converts string to uppercase or lowercase.

Example

SELECT 
    UPPER(name) AS upper_name,
    LOWER(email) AS lower_email
FROM users;

Output

upper_name | lower_email
-----------|------------------
JOHN DOE   | john@example.com

TRIM / LTRIM / RTRIM

Functions
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Removes leading/trailing spaces or specified characters.

Example

SELECT 
    TRIM('  Hello World  ') AS trimmed,
    LTRIM('  Left') AS left_trimmed,
    RTRIM('Right  ') AS right_trimmed;

Output

trimmed     | left_trimmed | right_trimmed
------------|--------------|-------------
Hello World | Left         | Right

LENGTH / LEN

Functions
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Returns the length of a string in characters.

Example

SELECT name, LENGTH(name) AS name_length
FROM products
WHERE LENGTH(name) > 20;

Output

name                    | name_length
------------------------|------------
Professional Laptop Pro | 23

REPLACE

Functions
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Replaces occurrences of a substring with another string.

Example

SELECT REPLACE(phone, '-', '') AS clean_phone
FROM contacts;

UPDATE urls SET path = REPLACE(path, 'http://', 'https://');

Output

clean_phone
-----------
5551234567

CAST / CONVERT

Functions
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Converts a value from one data type to another.

Example

SELECT 
    CAST(price AS INT) AS rounded_price,
    CAST(quantity AS VARCHAR(10)) AS qty_text,
    CAST('2024-01-15' AS DATE) AS order_date
FROM orders;

Output

rounded_price | qty_text | order_date
--------------|----------|------------
99            | 5        | 2024-01-15

NULLIF

Functions
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Returns NULL if two expressions are equal, otherwise returns the first.

Example

-- Avoid division by zero
SELECT 
    revenue / NULLIF(orders_count, 0) AS avg_order_value
FROM sales;

Output

avg_order_value
---------------
45.50
NULL
Pro Tip: Great for avoiding division by zero errors.

NOW / CURRENT_TIMESTAMP

Functions
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Returns the current date and time.

Example

SELECT 
    NOW() AS current_datetime,
    CURRENT_DATE AS today,
    CURRENT_TIME AS current_time;

Output

current_datetime        | today      | current_time
------------------------|------------|-------------
2024-01-15 14:30:45     | 2024-01-15 | 14:30:45

DATE_ADD / DATE_SUB

Functions
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Adds or subtracts intervals from dates.

Example

-- MySQL
SELECT DATE_ADD(NOW(), INTERVAL 7 DAY) AS next_week;

-- PostgreSQL
SELECT NOW() + INTERVAL '7 days' AS next_week;

Output

next_week
-------------------
2024-01-22 14:30:45

EXTRACT / DATEPART

Functions
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Extracts a specific part from a date (year, month, day, etc.).

Example

SELECT 
    EXTRACT(YEAR FROM order_date) AS year,
    EXTRACT(MONTH FROM order_date) AS month
FROM orders;

Output

year | month
-----|------
2024 | 1
2024 | 2

ROUND / FLOOR / CEIL

Functions
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Rounds numeric values to specified precision.

Example

SELECT 
    ROUND(price, 2) AS rounded,
    FLOOR(price) AS floored,
    CEIL(price) AS ceiling
FROM products;

Output

price   | rounded | floored | ceiling
--------|---------|---------|--------
99.456  | 99.46   | 99      | 100

Scalar Subquery

Subqueries
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

A subquery that returns a single value, used in SELECT or WHERE.

Example

SELECT 
    name,
    salary,
    (SELECT AVG(salary) FROM employees) AS company_avg
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);

Output

name | salary  | company_avg
-----|---------|------------
John | 95000   | 75000
Jane | 110000  | 75000

IN Subquery

Subqueries
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Checks if a value exists in the results of a subquery.

Example

SELECT * FROM products
WHERE category_id IN (
    SELECT id FROM categories
    WHERE name LIKE 'Electronics%'
);

Output

id | name   | category_id
---|--------|------------
1  | Laptop | 5
2  | Phone  | 5

EXISTS

Subqueries
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Tests for existence of rows in a subquery. More efficient than IN for large datasets.

Example

SELECT c.name
FROM customers c
WHERE EXISTS (
    SELECT 1 FROM orders o
    WHERE o.customer_id = c.id
    AND o.total > 1000
);

Output

name
-----
Alice
Bob
Pro Tip: EXISTS stops at first match, making it faster than IN for large tables.

NOT EXISTS

Subqueries
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Returns true if subquery returns no rows. Great for finding missing data.

Example

SELECT c.name
FROM customers c
WHERE NOT EXISTS (
    SELECT 1 FROM orders o
    WHERE o.customer_id = c.id
);

Output

name
--------
Charlie
Diana

ANY / SOME

Subqueries
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Compares a value to any value in a subquery result.

Example

SELECT name, salary
FROM employees
WHERE salary > ANY (
    SELECT salary FROM employees
    WHERE department = 'Sales'
);

Output

name | salary
-----|-------
John | 85000

ALL

Subqueries
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Compares a value to all values in a subquery result.

Example

SELECT name, salary
FROM employees
WHERE salary > ALL (
    SELECT salary FROM employees
    WHERE department = 'Sales'
);

Output

name | salary
-----|--------
CEO  | 250000

Correlated Subquery

Subqueries
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

A subquery that references columns from the outer query. Executes once per row.

Example

SELECT e.name, e.salary, e.department
FROM employees e
WHERE e.salary = (
    SELECT MAX(salary)
    FROM employees
    WHERE department = e.department
);

Output

name | salary | department
-----|--------|----------
John | 95000  | Engineering
Jane | 80000  | Sales
Pro Tip: Correlated subqueries can be slow. Consider JOINs instead.

WITH (CTE)

Subqueries
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Common Table Expression - defines a temporary named result set for better readability.

Example

WITH high_value_orders AS (
    SELECT customer_id, SUM(total) AS total_spent
    FROM orders
    GROUP BY customer_id
    HAVING SUM(total) > 10000
)
SELECT c.name, h.total_spent
FROM customers c
JOIN high_value_orders h ON c.id = h.customer_id;

Output

name  | total_spent
------|------------
Alice | 15430.00
Bob   | 12500.50
Pro Tip: CTEs make complex queries readable and maintainable.

CREATE INDEX

Indexes
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Creates an index to speed up data retrieval. Essential for query performance.

Example

CREATE INDEX idx_customer_email
ON customers(email);

CREATE INDEX idx_orders_date
ON orders(order_date DESC);

Output

Index created.
Pro Tip: Index columns used in WHERE, JOIN, and ORDER BY clauses.

CREATE UNIQUE INDEX

Indexes
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Creates an index that enforces uniqueness of values.

Example

CREATE UNIQUE INDEX idx_users_email
ON users(email);

Output

Unique index created.

Composite Index

Indexes
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

An index on multiple columns. Order matters for query optimization.

Example

CREATE INDEX idx_orders_customer_date
ON orders(customer_id, order_date);

Output

Composite index created.
Pro Tip: Put most selective column first. Index works left-to-right.

DROP INDEX

Indexes
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Removes an index from a table.

Example

-- MySQL
DROP INDEX idx_customer_email ON customers;

-- PostgreSQL
DROP INDEX idx_customer_email;

Output

Index dropped.

SHOW INDEXES

Indexes
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Displays information about existing indexes on a table.

Example

-- MySQL
SHOW INDEX FROM orders;

-- PostgreSQL
SELECT * FROM pg_indexes WHERE tablename = 'orders';

Output

Table  | Key_name          | Column_name
-------|-------------------|------------
orders | PRIMARY           | id
orders | idx_customer_date | customer_id

Partial Index

Indexes
🐘 PostgreSQL

What It Does

An index on a subset of rows, defined with a WHERE clause.

Example

-- PostgreSQL
CREATE INDEX idx_active_users
ON users(email)
WHERE is_active = true;

Output

Partial index created.
Pro Tip: Great for tables where you only query a subset of data.

EXPLAIN / EXPLAIN ANALYZE

Indexes
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Shows the execution plan for a query. Essential for query optimization.

Example

EXPLAIN ANALYZE
SELECT * FROM orders
WHERE customer_id = 123
ORDER BY order_date DESC;

Output

Index Scan on orders_customer_id_idx
  rows=15 time=0.045ms
Pro Tip: Always EXPLAIN slow queries before adding indexes.

BEGIN / START TRANSACTION

Transactions
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Starts a new transaction. Changes are not committed until explicit COMMIT.

Example

BEGIN;
-- or
START TRANSACTION;

Output

Transaction started.

COMMIT

Transactions
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Saves all changes made during the current transaction permanently.

Example

BEGIN;

UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;

COMMIT;

Output

Transaction committed.

ROLLBACK

Transactions
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Undoes all changes made during the current transaction.

Example

BEGIN;

DELETE FROM important_data WHERE id = 1;
-- Oops, wrong deletion!
ROLLBACK;

Output

Transaction rolled back.
Pro Tip: ROLLBACK undoes everything since BEGIN.

SAVEPOINT

Transactions
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Creates a point within a transaction to which you can roll back.

Example

BEGIN;

INSERT INTO orders VALUES (1, 'pending');
SAVEPOINT order_created;

INSERT INTO order_items VALUES (1, 101, 2);
-- Error occurred
ROLLBACK TO order_created;

COMMIT;

Output

Savepoint created.

SET TRANSACTION

Transactions
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Configures transaction properties like isolation level.

Example

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
-- or
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

Output

Transaction isolation set.
Pro Tip: Higher isolation = more consistency but lower concurrency.

LOCK TABLE

Transactions
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Explicitly locks a table to prevent concurrent access.

Example

LOCK TABLE inventory IN EXCLUSIVE MODE;

UPDATE inventory SET quantity = quantity - 1 WHERE product_id = 123;

COMMIT;

Output

Table locked.
Pro Tip: Use sparingly - locks can cause deadlocks and bottlenecks.

CREATE VIEW

Views
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Creates a virtual table based on a SELECT query. Simplifies complex queries.

Example

CREATE VIEW active_customers AS
SELECT c.id, c.name, c.email, COUNT(o.id) AS order_count
FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id
WHERE c.is_active = true
GROUP BY c.id, c.name, c.email;

Output

View created.

CREATE OR REPLACE VIEW

Views
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Creates a view or replaces it if it already exists.

Example

CREATE OR REPLACE VIEW monthly_sales AS
SELECT 
    DATE_TRUNC('month', order_date) AS month,
    SUM(total) AS revenue
FROM orders
GROUP BY DATE_TRUNC('month', order_date);

Output

View created or replaced.

DROP VIEW

Views
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Deletes a view from the database.

Example

DROP VIEW IF EXISTS old_report;

Output

View dropped.

Updatable View

Views
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

A view that allows INSERT, UPDATE, DELETE operations on underlying table.

Example

CREATE VIEW us_customers AS
SELECT * FROM customers
WHERE country = 'USA'
WITH CHECK OPTION;

-- Can insert/update through view
INSERT INTO us_customers (name, country)
VALUES ('John', 'USA');

Output

View is updatable.
Pro Tip: WITH CHECK OPTION ensures modifications match view criteria.

Materialized View

Views
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

A view that stores query results physically. Must be refreshed manually or on schedule.

Example

-- PostgreSQL
CREATE MATERIALIZED VIEW sales_summary AS
SELECT product_id, SUM(quantity) AS total_sold
FROM order_items
GROUP BY product_id;

-- Refresh data
REFRESH MATERIALIZED VIEW sales_summary;

Output

Materialized view created.
Pro Tip: Use for expensive queries that dont need real-time data.

REFRESH MATERIALIZED VIEW

Views
🐘 PostgreSQL
πŸ…ΎοΈ Oracle

What It Does

Updates the stored data in a materialized view with current query results.

Example

-- PostgreSQL
REFRESH MATERIALIZED VIEW CONCURRENTLY sales_summary;

Output

Materialized view refreshed.
Pro Tip: CONCURRENTLY allows reads during refresh but requires unique index.

UNION

Advanced
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Combines results from multiple SELECT statements. Removes duplicates by default.

Example

SELECT name, email FROM customers
UNION
SELECT name, email FROM suppliers
ORDER BY name;

Output

name   | email
-------|------------------
Alice  | alice@example.com
Bob    | bob@supplier.com
Pro Tip: Use UNION ALL to keep duplicates (faster).

UNION ALL

Advanced
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Combines results without removing duplicates. Faster than UNION.

Example

SELECT product_id FROM orders_2023
UNION ALL
SELECT product_id FROM orders_2024;

Output

(All rows from both tables, including duplicates)

INTERSECT

Advanced
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Returns only rows that appear in both result sets.

Example

SELECT customer_id FROM orders_january
INTERSECT
SELECT customer_id FROM orders_february;

Output

customer_id
-----------
101
205
Pro Tip: MySQL does not support INTERSECT. Use INNER JOIN instead.

EXCEPT / MINUS

Advanced
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Returns rows from first query that are not in second query.

Example

-- PostgreSQL, SQL Server
SELECT email FROM all_users
EXCEPT
SELECT email FROM unsubscribed_users;

-- Oracle
SELECT email FROM all_users
MINUS
SELECT email FROM unsubscribed_users;

Output

(Emails of subscribed users only)

ROW_NUMBER()

Advanced
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Assigns a unique sequential number to each row within a partition.

Example

SELECT 
    name,
    department,
    salary,
    ROW_NUMBER() OVER (
        PARTITION BY department 
        ORDER BY salary DESC
    ) AS rank
FROM employees;

Output

name | department | salary | rank
-----|------------|--------|-----
John | Eng        | 95000  | 1
Jane | Eng        | 85000  | 2
Bob  | Sales      | 80000  | 1

RANK() / DENSE_RANK()

Advanced
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Assigns ranking with gaps (RANK) or without gaps (DENSE_RANK) for ties.

Example

SELECT 
    name,
    score,
    RANK() OVER (ORDER BY score DESC) AS rank,
    DENSE_RANK() OVER (ORDER BY score DESC) AS dense_rank
FROM students;

Output

name | score | rank | dense_rank
-----|-------|------|----------
Alex | 95    | 1    | 1
Bob  | 95    | 1    | 1
Cara | 90    | 3    | 2

LAG() / LEAD()

Advanced
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Access data from previous (LAG) or next (LEAD) row without self-join.

Example

SELECT 
    order_date,
    total,
    LAG(total) OVER (ORDER BY order_date) AS prev_total,
    total - LAG(total) OVER (ORDER BY order_date) AS change
FROM daily_sales;

Output

order_date | total | prev_total | change
-----------|-------|------------|-------
2024-01-01 | 1500  | NULL       | NULL
2024-01-02 | 1800  | 1500       | 300
Pro Tip: Great for calculating running differences and comparisons.

SUM() OVER / Running Total

Advanced
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Calculates running totals using window functions.

Example

SELECT 
    order_date,
    amount,
    SUM(amount) OVER (ORDER BY order_date) AS running_total,
    SUM(amount) OVER () AS grand_total
FROM orders;

Output

order_date | amount | running_total | grand_total
-----------|--------|---------------|------------
2024-01-01 | 100    | 100           | 850
2024-01-02 | 150    | 250           | 850

PIVOT

Advanced
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

Rotates rows into columns for cross-tabulation reports.

Example

-- SQL Server
SELECT *
FROM (
    SELECT product, month, revenue
    FROM sales
) AS src
PIVOT (
    SUM(revenue)
    FOR month IN ([Jan], [Feb], [Mar])
) AS pvt;

Output

product | Jan   | Feb   | Mar
--------|-------|-------|------
Laptop  | 5000  | 6000  | 5500
Mouse   | 500   | 450   | 600
Pro Tip: Use CASE WHEN for PIVOT in MySQL/PostgreSQL.

Recursive CTE

Advanced
🐬 MySQL
🐘 PostgreSQL
πŸ…ΎοΈ Oracle
πŸ”· SQL Server

What It Does

CTEs that reference themselves. Perfect for hierarchical data like org charts.

Example

WITH RECURSIVE org_tree AS (
    SELECT id, name, manager_id, 1 AS level
    FROM employees
    WHERE manager_id IS NULL
    
    UNION ALL
    
    SELECT e.id, e.name, e.manager_id, ot.level + 1
    FROM employees e
    JOIN org_tree ot ON e.manager_id = ot.id
)
SELECT * FROM org_tree;

Output

id | name | manager_id | level
---|------|------------|------
1  | CEO  | NULL       | 1
2  | VP   | 1          | 2
3  | Mgr  | 2          | 3
Pro Tip: Use for tree structures, bill of materials, path finding.

πŸ“š DBMS Concepts Every Developer Should Know

β€’ ACID Properties: Atomicity, Consistency, Isolation, Durability - guarantees for transactions

β€’ Normalization: Process of organizing data (1NF, 2NF, 3NF) to reduce redundancy

β€’ Indexes: Data structures that speed up queries at the cost of write performance

β€’ Primary vs Foreign Key: PK uniquely identifies rows; FK creates relationships

β€’ Stored Procedures: Precompiled SQL code stored in the database

β€’ Triggers: Automatic actions executed on INSERT, UPDATE, DELETE

πŸ’‘ SQL Best Practices

  • β€’ Always use parameterized queries to prevent SQL injection
  • β€’ Use EXPLAIN to understand query performance
  • β€’ Index columns used in WHERE, JOIN, and ORDER BY
  • β€’ Prefer explicit JOINs over implicit (comma-separated) joins