xutil.dev
Login

SQL Cheatsheet

Quick reference for SQL syntax covering DDL, DML, SELECT queries, JOINs, aggregate functions, subqueries, window functions, and indexing

69 commands

CREATE TABLE

Create a table

DROP TABLE

Drop a table

ALTER TABLE ADD

Add a column to a table

ALTER TABLE DROP

Drop a column from a table

ALTER TABLE MODIFY

Modify column type

ALTER TABLE RENAME

Rename a table

TRUNCATE TABLE

Fast delete all rows from table

CREATE DATABASE

Create a database

DROP DATABASE

Drop a database

CREATE VIEW

Create a view

INSERT INTO

Insert data

INSERT INTO ... SELECT

Insert from SELECT result

UPDATE

Update data

DELETE

Delete data

UPSERT (MySQL)

Insert or update on duplicate (MySQL)

UPSERT (PostgreSQL)

Insert or update on conflict (PostgreSQL)

MERGE

Merge (upsert operation)

SELECT

Retrieve data

SELECT DISTINCT

Select distinct values

WHERE

Filter with conditions

AND / OR

Combine multiple conditions

IN

Check if value is in a list

BETWEEN

Get values within a range

LIKE

Pattern matching

IS NULL / IS NOT NULL

NULL check

ORDER BY

Sort results

LIMIT / OFFSET

Limit number of rows

CASE WHEN

Conditional expression

COALESCE

Return first non-null value

INNER JOIN

Inner join (matching rows only)

LEFT JOIN

Left outer join (keep all left rows)

RIGHT JOIN

Right outer join (keep all right rows)

FULL OUTER JOIN

Full outer join (keep all rows)

CROSS JOIN

Cross join (all combinations)

SELF JOIN

Self join (join table to itself)

NATURAL JOIN

Natural join (auto-join on same columns)

COUNT

Count rows

SUM

Calculate sum

AVG

Calculate average

MAX

Get maximum value

MIN

Get minimum value

GROUP BY

Group and aggregate

HAVING

Filter after grouping

GROUP_CONCAT (MySQL)

Concatenate values in group

STRING_AGG (PostgreSQL)

Concatenate values in group

WHERE ... IN (SELECT)

Filter by subquery result

EXISTS

Check if subquery returns rows

スカラーサブクエリ

Scalar subquery returning single value

WITH (CTE)

Define Common Table Expression

WITH RECURSIVE

Define recursive CTE

UNION

Combine results (remove duplicates)

UNION ALL

Combine results (keep duplicates)

ROW_NUMBER()

Assign row numbers

RANK()

Assign rank (gaps on ties)

DENSE_RANK()

Assign rank (no gaps on ties)

LAG()

Get value from previous row

LEAD()

Get value from next row

SUM() OVER

Calculate running total

PARTITION BY

Apply window function within partition

NTILE()

Divide rows into N equal groups

CREATE INDEX

Create an index

CREATE UNIQUE INDEX

Create a unique index

DROP INDEX

Drop an index

PRIMARY KEY

Set primary key constraint

FOREIGN KEY

Set foreign key constraint

UNIQUE

Set unique constraint

CHECK

Set check constraint

NOT NULL

Set NOT NULL constraint

DEFAULT

Set default value