Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

2 Commits

Repository files navigation

SQL Cheat Sheet

Complete Reference Guide for SQL Developers

This comprehensive cheat sheet documents commonly used SQL elements, from basic syntax to advanced concepts. Whether you're a beginner learning SQL or an experienced developer needing a quick reference, this guide has you covered.


Table of Contents

  1. What is SQL?
  2. SQL vs MySQL
  3. Installing MySQL
  4. Using MySQL
  5. SQL Keywords Reference
  6. Comments
  7. MySQL Data Types
  8. Operators
  9. Functions
  10. Wildcard Characters
  11. Keys
  12. Indexes
  13. Joins
  14. Views

What is SQL?

SQL (Structured Query Language) is the standard language for storing, manipulating, and retrieving data in relational databases. It powers the data behind most websites and applications you use daily.

How a Relational Database Works

A relational database organizes data into tables that can be linked through relationships. Here's a visual representation of how tables interact:

erDiagram
USERS ||--o{ ORDERS : places
PRODUCTS ||--o{ ORDERS : contains
USERS {
int id PK
string first_name
string last_name
string email
string address
}
PRODUCTS {
int id PK
string name
float price
int stock_count
}
ORDERS {
int id PK
int user_id FK
int product_id FK
int quantity
date order_date
}
Loading

Basic SQL Operations Flow

flowchart LR
A[Database] --> B[Table]
B --> C{SQL Query}
C -->|SELECT| D[Retrieve Data]
C -->|INSERT| E[Add Data]
C -->|UPDATE| F[Modify Data]
C -->|DELETE| G[Remove Data]
D --> H[Results Set]
Loading

Example Queries

Selecting all data from a table:

SELECT*FROM users;

This query retrieves every column and row from the users table, returning a results set like this:

idfirst_namelast_nameemailaddress
1JohnDoejohn@email.com123 Main St
2JaneSmithjane@email.com456 Oak Ave

Selecting specific columns:

SELECT first_name, last_name FROM users;

Filtering with conditions:

SELECT*FROM products WHERE stock_count <=10ORDER BY stock_count ASC;

This returns all products with low stock (10 or fewer), sorted from lowest to highest.

Inserting new data:

INSERT INTO users (first_name, last_name, address, email)
VALUES ('Tester', 'Jester', '123 Fake Street, Sheffield, United Kingdom', 'test@example.com');

SQL vs MySQL

Understanding the distinction between SQL and MySQL is crucial:

SQLMySQL
Language - defines the syntax for querying databasesDatabase System - software that implements SQL
A standard used across database systemsOne of many database management systems
Cannot be "installed" - it's a language specificationCan be installed on servers and local machines

Popular SQL Database Systems

mindmap
root((SQL Databases))
Relational
MySQL
PostgreSQL
Oracle Database
Microsoft SQL Server
Embedded
SQLite
Cloud-Based
Amazon RDS
Google Cloud SQL
Azure SQL Database
Loading

Installing MySQL

Windows Installation

The recommended method is using the official MySQL installer from the MySQL website. This provides a guided setup wizard that handles all configurations.

macOS Installation

Using Native Packages: Download the official MySQL installer for macOS from the MySQL website.

Using Homebrew (Recommended for developers):

For the latest version:

brew install mysql

For MySQL 5.7 (still widely used in production):

brew install mysql@5.7

Using MySQL

Once MySQL is installed, use a database management application to interact with your databases efficiently.

Recommended Management Tools

ToolPlatformBest For
MySQL WorkbenchWindows/Mac/LinuxOfficial Oracle tool, comprehensive features
HeidiSQLWindowsLightweight, free, open-source
Sequel PromacOSClean interface, macOS native
phpMyAdminWeb-basedServer management via browser
DBeaverCross-platformMulti-database support

Practice with Sample Databases

MySQL provides free sample databases for learning:

Example Query - Countries with Queen Elizabeth II as Head of State:

SELECT name, continent, population FROM country WHERE head_of_state ='Elisabeth II';

Example Query - Large European Countries:

SELECTcountry.name, city.nameAS capital, city.populationFROM country JOIN city ONcountry.capital=city.idWHEREcountry.continent='Europe'ANDcountry.population>50000000;

SQL Keywords Reference

A comprehensive collection of SQL keywords with descriptions and practical examples.

Data Definition Language (DDL)

KeywordDescriptionExample
CREATE TABLECreates a new table in the databaseCREATE TABLE users (id int, name varchar(255));
ALTER TABLEModifies an existing table structureALTER TABLE users ADD email varchar(255);
DROP TABLERemoves a table completelyDROP TABLE users;
TRUNCATE TABLERemoves all data but keeps table structureTRUNCATE TABLE sessions;
CREATE DATABASECreates a new databaseCREATE DATABASE websitesetup;
DROP DATABASERemoves a database entirelyDROP DATABASE websitesetup;

Examples:

Adding a column:

ALTERTABLE users ADD email_address varchar(255);

Adding a constraint:

ALTERTABLE users ADD CONSTRAINT user PRIMARY KEY (id, surname);

Adding and removing columns:

-- Add a columnALTERTABLE deals ADD approved boolean;
-- Remove a columnALTERTABLE deals DROP COLUMN approved;

Changing column data type:

ALTERTABLE users ALTER COLUMN incept_date datetime;

Data Manipulation Language (DML)

KeywordDescriptionExample
SELECTRetrieves data from tablesSELECT * FROM users;
INSERT INTOAdds new recordsINSERT INTO users VALUES (...);
UPDATEModifies existing recordsUPDATE users SET name = 'John' WHERE id = 1;
DELETERemoves recordsDELETE FROM users WHERE id = 1;

Examples:

Select with column filtering:

SELECT first_name, surname FROM users;

Insert with specific columns:

INSERT INTO cars (make, model, mileage, year)
VALUES ('Audi', 'A3', 30000, 2016);

Update specific records:

UPDATE orders SET value =19.49, quantity =2WHERE id =642;

Update multiple columns:

UPDATE cars SET mileage =23500, serviceDue =0WHERE id =45;

Delete specific records:

DELETEFROM users WHERE user_id =674;

Query Clauses and Conditions

KeywordDescriptionExample
WHEREFilters records based on conditionsWHERE quantity > 1
ORDER BYSorts results (ASC/DESC)ORDER BY name DESC
GROUP BYGroups rows for aggregationGROUP BY department
HAVINGFilters grouped resultsHAVING COUNT(*) > 5
LIMIT/TOPRestricts number of resultsLIMIT 10 or TOP 10

Examples:

WHERE clause:

SELECT*FROM orders WHERE quantity >1;

Multiple conditions with AND:

SELECT*FROM events WHERE host_country ='United Kingdom'AND host_city ='London';

OR condition:

SELECT*FROM users WHERE city ='Sheffield'OR city ='Manchester';

IN shorthand (replaces multiple OR):

-- Instead of: WHERE country = 'USA' OR country = 'UK' OR country = 'Australia'SELECT*FROM users WHERE country IN ('USA', 'United Kingdom', 'Australia');

Sorting results:

-- Ascending (A-Z, 1-10)SELECT*FROM countries ORDER BY name ASC;
-- Descending (Z-A, 10-1)SELECT*FROM products ORDER BY price DESC;

Limiting results:

-- Top N recordsSELECT TOP 5*FROM users;
-- With row numberSELECT*FROM countries WHERE ROWNUM <=10;

Advanced Query Keywords

KeywordDescriptionExample
BETWEENSelects values in a rangeWHERE price BETWEEN 10 AND 20
LIKEPattern matchingWHERE name LIKE 'J%'
INMatches any value in a listWHERE country IN ('UK', 'US')
EXISTSTests for record existenceWHERE EXISTS (subquery)
ANY/ALLCompares with subquery valuesWHERE value > ANY (subquery)
CASEConditional logic in queriesCASE WHEN ... THEN ... END
DISTINCTRemoves duplicate valuesSELECT DISTINCT country FROM users
UNIONCombines result setsSELECT ... UNION SELECT ...

Examples:

BETWEEN:

-- Within rangeSELECT*FROM stock WHERE quantity BETWEEN 100AND150;
-- Outside rangeSELECT*FROM stock WHERE quantity NOT BETWEEN 100AND150;

LIKE pattern matching:

-- Ends with 'son'SELECT*FROM users WHERE first_name LIKE'%son';
-- Contains 'son'SELECT*FROM users WHERE first_name LIKE'%son%';

ANY - compares against subquery:

SELECT name FROM products WHERE productId = ANY (
SELECT productId FROM orders WHERE quantity >5
);

ALL - must satisfy all subquery values:

SELECT first_name, surname, tasks_no FROM users WHERE tasks_no > ALL (
SELECT tasks FROM user WHERE department_id =2
);

CASE for conditional output:

SELECT first_name, surname, subscriptions,
CASE WHEN subscriptions >10 THEN 'Very active'
WHEN subscriptions BETWEEN 3AND10 THEN 'Active'
ELSE 'Inactive'
END AS activity_levels
FROM users;

UNION - combining results without duplicates:

SELECT city FROM events
UNIONSELECT city FROM subscribers;

UNION ALL - combining results with duplicates:

SELECT city FROM events
UNION ALLSELECT city FROM subscribers;

Constraint Keywords

KeywordDescriptionExample
PRIMARY KEYUnique identifier for recordsPRIMARY KEY (id)
FOREIGN KEYLinks tables togetherFOREIGN KEY (user_id) REFERENCES users(id)
UNIQUEEnsures unique valuesUNIQUE (email)
CHECKValidates data conditionsCHECK (age >= 18)
DEFAULTSets default column valueDEFAULT 'Unknown'
NOT NULLPrevents empty valuesname varchar(255) NOT NULL

Examples:

CHECK constraint during table creation:

CREATETABLEusers (
first_name varchar(255),
age int,
CHECK (age >=18)
);

Adding CHECK to existing table:

ALTERTABLE users ADD CHECK (age >=18);

UNIQUE constraint:

-- During creationCREATETABLEusers (
id intNOT NULL,
name varchar(255) NOT NULL,
UNIQUE (id)
);
-- Adding laterALTERTABLE users ADD UNIQUE (id);

DEFAULT values:

-- During creationCREATETABLEproducts (
id int,
name varchar(255) DEFAULT 'Placeholder Name',
available_from date DEFAULT GETDATE()
);
-- Modifying existing tableALTERTABLE products ALTER name SET DEFAULT 'Placeholder Name';

Removing defaults:

ALTERTABLE products ALTER COLUMN name DROP DEFAULT;

NULL Handling

KeywordDescriptionExample
IS NULLTests for NULL valuesWHERE phone IS NULL
IS NOT NULLTests for non-NULL valuesWHERE phone IS NOT NULL
-- Find users without contact numbersSELECT*FROM users WHERE contact_number IS NULL;
-- Find users with contact numbersSELECT*FROM users WHERE contact_number IS NOT NULL;

Comments

Comments explain SQL code or temporarily prevent execution. SQL supports two comment styles.

Comment Types Overview

graph LR
A[SQL Comments] --> B[Single Line]
A --> C[Multi Line]
B --> D["-- Comment text"]
C --> E["/* Comment text */"]
Loading

Single-Line Comments

Start with --. Everything after these characters on the same line is ignored.

-- Retrieve all user recordsSELECT*FROM users;
SELECT first_name, last_name FROM users; -- Only get names

Multi-Line Comments

Start with /* and end with */. Can span multiple lines.

/* This query retrieves all users who have placed orders in the last 30 days*/SELECT*FROM users WHERE last_order_date >'2024-01-01';
/* Temporarily disabled query SELECT * FROM tasks;*/

MySQL Data Types

When creating tables, each column requires a data type specification. This determines what kind of data can be stored and how it's handled.

Data Type Categories

graph TB
A[MySQL Data Types] --> B[String Types]
A --> C[Numeric Types]
A --> D[Date/Time Types]
B --> B1[CHAR/VARCHAR]
B --> B2[TEXT variants]
B --> B3[BLOB variants]
B --> B4[ENUM/SET]
C --> C1[Integer Types]
C --> C2[Decimal Types]
C --> C3[Bit Type]
D --> D1[DATE/TIME]
D --> D2[DATETIME]
D --> D3[TIMESTAMP]
Loading

String Data Types

Data TypeDescriptionMax SizeExample
CHAR(size)Fixed-length string255 charsCHAR(10) - always 10 chars
VARCHAR(size)Variable-length string65,535 charsVARCHAR(255) - up to 255 chars
TEXT(size)Long text strings65,535 bytesTEXT - articles, descriptions
TINYTEXTVery small text255 charsShort notes
MEDIUMTEXTMedium text16,777,215 charsBooks, large documents
LONGTEXTVery large text4,294,967,295 charsFull books, logs
BLOB(size)Binary large objects65,535 bytesImages, files (small)
MEDIUMBLOBMedium binary16,777,215 bytesLarger files
LONGBLOBVery large binary4,294,967,295 bytesVery large files
ENUM(a,b,c...)Single value from list65,535 valuesENUM('small','medium','large')
SET(a,b,c...)Multiple values from list64 valuesSET('red','green','blue')
BINARY(size)Fixed binary string255 bytesBinary data
VARBINARY(size)Variable binary65,535 bytesVariable binary data

String Type Examples:

-- CHAR vs VARCHARCREATETABLEusers (
country_code CHAR(2), -- Always 2 characters (US, UK, IN)
full_name VARCHAR(100) -- Variable length, up to 100
);
-- ENUM example (like radio buttons - single choice)CREATETABLEtshirts (
color ENUM('red', 'green', 'blue', 'yellow', 'purple')
);
-- SET example (like checkboxes - multiple choices)CREATETABLEuser_permissions (
permissions SET('read', 'write', 'delete', 'admin')
);

Numeric Data Types

Data TypeRange (Signed)Range (Unsigned)Example
TINYINT-128 to 1270 to 255Age (0-255)
SMALLINT-32,768 to 32,7670 to 65,535Year, count
MEDIUMINT-8,388,608 to 8,388,6070 to 16,777,215Medium counts
INT/INTEGER-2.14B to 2.14B0 to 4.29BIDs, quantities
BIGINT-9.22 quintillion to 9.22 quintillion0 to 18.44 quintillionVery large numbers
FLOAT(p)Variable precisionVariable precisionScientific data
DOUBLEHigher precisionHigher precisionFinancial calculations
DECIMAL(size,d)Exact fixed pointExact fixed pointMoney (DECIMAL(10,2))
BIT(size)Bit value (1-64 bits)N/ABoolean, flags
BOOL/BOOLEAN0 (false) or 1 (true)N/AYes/No flags

Numeric Type Examples:

-- Integer typesCREATETABLEproducts (
id INT AUTO_INCREMENT,
quantity SMALLINT,
views BIGINT
);
-- Decimal for precise calculationsCREATETABLEorders (
id INT,
amount DECIMAL(10,2), -- 10 digits total, 2 after decimal
tax_rate DECIMAL(4,2) -- 4 digits total, 2 after decimal (99.99%)
);
-- BooleanCREATETABLEusers (
is_active BOOLEAN, -- Stored as TINYINT(1)
is_verified BOOL -- Same as BOOLEAN
);

Date and Time Data Types

Data TypeFormatRangeExample
DATEYYYY-MM-DD1000-01-01 to 9999-12-31'2024-03-15'
DATETIMEYYYY-MM-DD HH:MM:SS1000-01-01 to 9999-12-31'2024-03-15 14:30:00'
TIMESTAMPUnix timestamp1970-01-01 to 2038-01-19Auto-updated
TIMEHH:MM:SS-838:59:59 to 838:59:59'14:30:00'
YEARYYYY1901 to 21552024

Date/Time Type Examples:

-- Creating tables with date typesCREATETABLEevents (
event_date DATE,
event_datetime DATETIME,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
event_time TIME,
event_year YEAR
);
-- Auto-updating timestampCREATETABLElogs (
id INT,
message TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMPONUPDATECURRENT_TIMESTAMP
);

Operators

SQL operators perform operations on data values.

Operator Categories

graph TB
A[SQL Operators] --> B[Arithmetic]
A --> C[Comparison]
A --> D[Logical]
A --> E[Bitwise]
A --> F[Compound]
B --> B1["+ - * / %"]
C --> C1["= > < >= <= <>"]
D --> D1["AND OR NOT BETWEEN IN LIKE"]
E --> E1["& | ^"]
F --> F1["+= -= *= /="]
Loading

Arithmetic Operators

Perform mathematical calculations.

-- Basic arithmeticSELECT price + tax AS total_price FROM products;
SELECT salary - deductions AS net_pay FROM employees;
SELECT quantity * price AS line_total FROM orders;
SELECT total_amount / quantity AS unit_price FROM orders;
SELECTnumber % 2AS is_even FROM numbers; -- 0 = even, 1 = odd
OperatorDescriptionExample
+AdditionSELECT 10 + 5; → 15
-SubtractionSELECT 10 - 5; → 5
*****MultiplicationSELECT 10 * 5; → 50
/DivisionSELECT 10 / 5; → 2
%Modulo (remainder)SELECT 10 % 3; → 1

Comparison Operators

Compare values and return TRUE, FALSE, or NULL.

-- Comparison examplesSELECT*FROM products WHERE price =100;
SELECT*FROM products WHERE price >50;
SELECT*FROM products WHERE quantity <10;
SELECT*FROM users WHERE age >=18;
SELECT*FROM orders WHERE amount <=1000;
SELECT*FROM users WHERE email <>'spam@example.com';
OperatorDescriptionExample
=Equal toWHERE id = 5
>Greater thanWHERE age > 21
<Less thanWHERE price < 100
>=Greater or equalWHERE quantity >= 10
<=Less or equalWHERE rating <= 5
<>Not equal toWHERE status <> 'cancelled'

Bitwise Operators

Perform operations on bit patterns.

-- Bitwise operationsSELECT5 & 3; -- 1 (0101 & 0011 = 0001)SELECT5 | 3; -- 7 (0101 | 0011 = 0111)SELECT5 ^ 3; -- 6 (0101 ^ 0011 = 0110)
OperatorDescriptionExample
&Bitwise ANDSELECT 5 & 3; → 1
|Bitwise ORSELECT 5 | 3; → 7
^Bitwise XORSELECT 5 ^ 3; → 6

Compound Operators

Shorthand for performing an operation and assignment.

-- Compound operations (used in UPDATE)UPDATE orders SET quantity +=1WHERE id =100; -- IncrementUPDATE products SET price -=5WHERE category ='sale';
UPDATE line_items SET total *=1.1; -- Add 10%UPDATE totals SET average /=2;
OperatorDescription
+=Add and assign
-=Subtract and assign
*=Multiply and assign
/=Divide and assign
%=Modulo and assign

Functions

SQL functions perform operations on data and return results.

Function Categories

graph TB
A[SQL Functions] --> B[String Functions]
A --> C[Numeric Functions]
A --> D[Date Functions]
A --> E[Aggregate Functions]
A --> F[Misc Functions]
B --> B1["CONCAT, SUBSTRING, LENGTH..."]
C --> C1["ABS, ROUND, CEIL, FLOOR..."]
D --> D1["NOW, DATEDIFF, DATE_FORMAT..."]
E --> E1["COUNT, SUM, AVG, MAX, MIN..."]
F --> F1["IF, COALESCE, CAST..."]
Loading

String Functions

Manipulate and analyze text data.

FunctionDescriptionExample
CONCAT(s1,s2,...)Joins strings togetherCONCAT('Hello',' World') → 'Hello World'
UPPER(s)Converts to uppercaseUPPER('hello') → 'HELLO'
LOWER(s)Converts to lowercaseLOWER('HELLO') → 'hello'
LENGTH(s)Returns string length in bytesLENGTH('hello') → 5
SUBSTRING(s,start,len)Extracts part of stringSUBSTRING('hello',1,2) → 'he'
TRIM(s)Removes leading/trailing spacesTRIM(' hello ') → 'hello'
REPLACE(s,old,new)Replaces substringREPLACE('hello','l','L') → 'heLLo'
LEFT(s,n)Returns n chars from leftLEFT('hello',2) → 'he'
RIGHT(s,n)Returns n chars from rightRIGHT('hello',2) → 'lo'
REVERSE(s)Reverses stringREVERSE('hello') → 'olleh'

String Function Examples:

-- ConcatenationSELECT CONCAT(first_name, '', last_name) AS full_name FROM users;
-- Pattern search positionSELECT INSTR('hello world', 'world'); -- Returns 7-- Case conversionSELECTUPPER(first_name), LOWER(last_name) FROM users;
-- PaddingSELECT LPAD('123', 5, '0'); -- '00123'SELECT RPAD('123', 5, '0'); -- '12300'-- Space removalSELECT LTRIM(' hello'); -- 'hello' (left spaces removed)SELECT RTRIM('hello '); -- 'hello' (right spaces removed)SELECTTRIM(' hello '); -- 'hello' (both sides)-- Substring extractionSELECTSUBSTRING('Hello World', 7, 5); -- 'World'

Numeric Functions

Perform mathematical operations.

FunctionDescriptionExample
ABS(n)Absolute valueABS(-5) → 5
ROUND(n,d)Round to d decimalsROUND(3.14159,2) → 3.14
CEIL(n)Round up to integerCEIL(3.1) → 4
FLOOR(n)Round down to integerFLOOR(3.9) → 3
MOD(n,m)Remainder of n/mMOD(10,3) → 1
POWER(n,m)n raised to power mPOWER(2,3) → 8
SQRT(n)Square rootSQRT(16) → 4
RAND()Random number 0-1RAND() → 0.1234...
PI()Returns πPI() → 3.141592...

Numeric Function Examples:

-- RoundingSELECT ROUND(price, 2) FROM products;
SELECT CEIL(4.2); -- 5SELECT FLOOR(4.8); -- 4-- Power and rootSELECT POWER(2, 10); -- 1024SELECT SQRT(144); -- 12-- RandomSELECT RAND(); -- Random between 0 and 1SELECT FLOOR(RAND() *100); -- Random integer 0-99-- Math constantsSELECT PI(); -- 3.14159265358979

Aggregate Functions

Perform calculations on sets of rows.

FunctionDescriptionExample
COUNT(*)Counts rowsCOUNT(*) → total records
SUM(col)Sums valuesSUM(amount) → total
AVG(col)Averages valuesAVG(price) → average
MAX(col)Highest valueMAX(salary) → highest
MIN(col)Lowest valueMIN(price) → lowest

Aggregate Function Examples:

-- Count recordsSELECTCOUNT(*) AS total_users FROM users;
SELECTCOUNT(DISTINCT country) FROM users;
-- Sum and averageSELECTSUM(amount) AS total_revenue FROM orders;
SELECTAVG(rating) AS avg_rating FROM reviews;
-- Min and maxSELECTMIN(price) AS cheapest, MAX(price) AS most_expensive FROM products;
-- Grouping aggregatesSELECT category, COUNT(*) AS count, AVG(price) AS avg_price
FROM products
GROUP BY category;

Date and Time Functions

FunctionDescriptionExample
NOW()Current date and timeNOW() → '2024-03-15 14:30:00'
CURDATE()Current dateCURDATE() → '2024-03-15'
CURTIME()Current timeCURTIME() → '14:30:00'
DATE(datetime)Extracts date partDATE('2024-03-15 14:30:00') → '2024-03-15'
YEAR(date)Extracts yearYEAR('2024-03-15') → 2024
MONTH(date)Extracts monthMONTH('2024-03-15') → 3
DAY(date)Extracts dayDAY('2024-03-15') → 15
DATEDIFF(d1,d2)Days between datesDATEDIFF('2024-03-15','2024-03-01') → 14
DATE_ADD(d, INTERVAL)Add to dateDATE_ADD('2024-03-15', INTERVAL 7 DAY)

Date Function Examples:

-- Current date/timeSELECT NOW(); -- 2024-03-15 14:30:00SELECT CURDATE(); -- 2024-03-15SELECT CURTIME(); -- 14:30:00-- Extract partsSELECT YEAR(order_date) FROM orders;
SELECT MONTHNAME(order_date) FROM orders; -- 'March'-- Date arithmeticSELECT DATEDIFF('2024-12-31', '2024-01-01'); -- 365-- Add/subtract intervalsSELECT DATE_ADD('2024-03-15', INTERVAL 30 DAY);
SELECT DATE_SUB('2024-03-15', INTERVAL 1 MONTH);
-- Format datesSELECT DATE_FORMAT('2024-03-15', '%M %d, %Y'); -- 'March 15, 2024'

Miscellaneous Functions

FunctionDescriptionExample
IF(cond,val1,val2)Conditional valueIF(age>=18,'Adult','Minor')
COALESCE(val1,val2,...)First non-null valueCOALESCE(phone,'N/A')
CAST(val AS type)Convert data typeCAST('123' AS UNSIGNED)
DATABASE()Current database nameDATABASE() → 'mydb'
VERSION()MySQL versionVERSION() → '8.0.36'

Miscellaneous Function Examples:

-- IF functionSELECT IF(price >100, 'Expensive', 'Affordable') FROM products;
-- Handle NULL valuesSELECT COALESCE(phone, email, 'No contact') FROM users;
-- Type conversionSELECT CAST('2024-03-15'ASDATE);
SELECTCONVERT('123', SIGNED INTEGER);
-- System informationSELECT DATABASE();
SELECT VERSION();
SELECTCURRENT_USER();

Wildcard Characters

Wildcards enable powerful pattern matching with the LIKE operator.

Wildcard Pattern Matching Flow

flowchart LR
A[Search String] --> B{Wildcard Pattern}
B -->|%| C[Matches any sequence<br/>of characters]
B -->|_| D[Matches exactly<br/>one character]
B -->|Charlist| E[Matches any character<br/>in the brackets]
B -->|Not Charlist| F[Matches any character<br/>NOT in brackets]
Loading

Wildcard Characters

WildcardDescriptionExample PatternMatches
%Zero or more characters'a%'Starts with 'a'
_ (underscore)Exactly one character'_at''cat', 'hat', 'bat'
[chars]Any single char in list'[abc]%'Starts with a, b, or c
[!chars]Any single char NOT in list'[!abc]%'Doesn't start with a, b, or c
[a-z]Any char in range'[a-z]%'Starts with lowercase letter

Wildcard Examples:

Using % (percent):

-- Names ending with 'son'SELECT*FROM users WHERE surname LIKE'%son';
-- Matches: Johnson, Richardson, Wilson-- Names containing 'che'SELECT*FROM users WHERE city LIKE'%che%';
-- Matches: Manchester, Rochester, Chelmsford

Using _ (underscore):

-- Cities with exactly 3 chars followed by 'chester'SELECT*FROM users WHERE city LIKE'___chester';
-- Matches: Manchester, Winchester-- Doesn't match: Rochester (only 2 chars before 'chester')

Using [charlist]:

-- Names starting with J, H, or MSELECT*FROM users WHERE first_name LIKE'[jhm]%';
-- Matches: John, Henry, Mary-- Names starting with A through LSELECT*FROM users WHERE first_name LIKE'[a-l]%';
-- Matches: Alice, Bob, Carol-- Doesn't match: Mary, Nancy, Zara-- Names NOT ending with n through sSELECT*FROM users WHERE first_name LIKE'%[!n-s]';
-- Matches: Robert, Alice-- Doesn't match: John, Carlos, James

Keys

Keys establish relationships between tables and ensure data integrity.

Key Relationships

erDiagram
CUSTOMERS ||--o{ ORDERS : "has many"
ORDERS ||--|{ ORDER_ITEMS : contains
PRODUCTS ||--o{ ORDER_ITEMS : "ordered as"
CUSTOMERS {
int customer_id PK "Primary Key"
string name
string email
}
ORDERS {
int order_id PK "Primary Key"
int customer_id FK "Foreign Key"
date order_date
}
ORDER_ITEMS {
int item_id PK "Primary Key"
int order_id FK "Foreign Key"
int product_id FK "Foreign Key"
}
PRODUCTS {
int product_id PK "Primary Key"
string name
float price
}
Loading

Primary Key

A primary key uniquely identifies each record in a table. Each table can have only ONE primary key.

Creating a primary key during table creation:

CREATETABLEusers (
id INTNOT NULL AUTO_INCREMENT,
first_name VARCHAR(255),
last_name VARCHAR(255) NOT NULL,
address VARCHAR(255),
email VARCHAR(255),
PRIMARY KEY (id)
);

Adding primary key to existing table:

ALTERTABLE users ADD PRIMARY KEY (first_name);

Composite primary key (multiple columns):

ALTERTABLE users ADD CONSTRAINT user PRIMARY KEY (id, surname);

Foreign Key

A foreign key links two tables together, creating a parent-child relationship.

Creating foreign keys during table creation:

CREATETABLEorders (
id INTNOT NULL,
user_id INT,
product_id INT,
PRIMARY KEY (id),
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (product_id) REFERENCES products(id)
);

Adding foreign key to existing table:

ALTERTABLE orders ADD FOREIGN KEY (user_id) REFERENCES users(id);

Indexes

Indexes speed up data retrieval for frequently searched columns. However, they slow down data insertion and updates because the index must be updated too.

Index Types

Index TypeDescriptionWhen to Use
Regular IndexSpeeds up searches, allows duplicatesFrequently searched columns
Unique IndexSpeeds up searches, prevents duplicatesEmail, username columns
Composite IndexIndex on multiple columnsColumns often queried together
Primary Key IndexAutomatically created for primary keysAlways exists on PK column

Creating Indexes

Standard Index (allows duplicates):

CREATEINDEXidx_lastnameON users (last_name);
-- Composite indexCREATEINDEXidx_nameON users (first_name, surname);

Unique Index (prevents duplicates):

CREATEUNIQUE INDEXidx_emailON users (email);

Dropping Indexes

ALTERTABLE users DROP INDEX idx_lastname;

Joins

JOIN clauses combine data from multiple tables based on related columns.

Join Types Visualization

graph TB
subgraph "INNER JOIN"
A1[Table A] --- C1[Matched Records] --- B1[Table B]
end
subgraph "LEFT JOIN"
A2[All of Table A] --- C2[Matched from B<br/>+ NULL for unmatched]
end
subgraph "RIGHT JOIN"
B3[All of Table B] --- C3[Matched from A<br/>+ NULL for unmatched]
end
subgraph "FULL OUTER JOIN"
A4[All of Table A] --- C4[All Records<br/>NULL where no match]
B4[All of Table B] --- C4
end
Loading

Join Types

Join TypeReturnsVisual
INNER JOINOnly matching records from both tablesIntersection of two sets
LEFT JOINAll records from left table + matching from rightComplete left circle
RIGHT JOINAll records from right table + matching from leftComplete right circle
FULL OUTER JOINAll records from both tablesBoth complete circles
CROSS JOINEvery combination of rowsCartesian product

Practical Join Example

Consider three tables: orders, users, and products.

Query joining three tables:

SELECTorders.id,
users.first_name, users.surname, products.nameAS'product name'FROM orders
INNER JOIN users ONorders.user_id=users.idINNER JOIN products ONorders.product_id=products.id;

Result set:

idfirst_namesurnameproduct name
1JohnDoeLaptop
2JaneSmithMouse
3BobWilsonKeyboard

Additional Join Examples

LEFT JOIN - All users with their orders (if any):

SELECTusers.name, orders.idAS order_id
FROM users
LEFT JOIN orders ONusers.id=orders.user_id;

Returns all users, showing NULL for order_id if they haven't ordered.

Self Join - Employees and their managers:

SELECTe.nameAS employee,
m.nameAS manager
FROM employees e
LEFT JOIN employees m ONe.manager_id=m.id;

Views

A view is a saved SQL query stored under a label in the database. It acts as a virtual table that you can query later without re-running the original query.

How Views Work

flowchart LR
A[Complex SQL Query] -->|CREATE VIEW| B[Stored View]
B -->|SELECT FROM| C[Results Set]
D[Underlying Tables] -.->|Data Source| B
E[Users/Apps] -->|Query| B
Loading

Creating Views

CREATEVIEWpriority_usersASSELECT*FROM users
WHERE country ='United Kingdom';

Using the view:

SELECT*FROM [priority_users];

Modifying Views

Update an existing view:

CREATE OR REPLACE VIEW [priority_users] ASSELECT*FROM users
WHERE country ='United Kingdom'OR country ='USA';

Deleting Views

DROPVIEW priority_users;

View Benefits

BenefitDescription
PerformanceStore expensive queries once, reuse results
SecurityExpose only specific columns to users
SimplicitySimplify complex queries for end users
ConsistencyEnsure consistent query logic across applications

Quick Reference Cards

Essential SELECT Query Structure

SELECT [DISTINCT] column1, column2, ...
FROM table_name
[JOIN other_table ON condition]
[WHERE condition]
[GROUP BY column]
[HAVING group_condition]
[ORDER BY column [ASC|DESC]]
[LIMIT count];

CRUD Operations Summary

OperationCommandExample
CreateINSERT INTOINSERT INTO users VALUES (...);
ReadSELECTSELECT * FROM users;
UpdateUPDATEUPDATE users SET name='X' WHERE id=1;
DeleteDELETEDELETE FROM users WHERE id=1;

This cheat sheet serves as a comprehensive reference for SQL development. Bookmark it for quick access during your database work.

About

This comprehensive cheat sheet documents commonly used SQL elements, from basic syntax to advanced concepts. Whether you're a beginner learning SQL or an experienced developer needing a quick reference, this guide has you covered.

Topics

Resources

Stars

3 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors