0% found this document useful (0 votes)
60 views6 pages

? SQL Cheat Sheet

This SQL cheat sheet provides shortcuts and powerful methods for various SQL operations, including filtering, aggregations, joins, string functions, conditional logic, data modification, performance optimization, and miscellaneous tips. It includes examples for each method to illustrate their usage. The document emphasizes best practices such as using aliases for readability, avoiding SELECT *, and leveraging CTEs for complex queries.

Uploaded by

k3509835
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views6 pages

? SQL Cheat Sheet

This SQL cheat sheet provides shortcuts and powerful methods for various SQL operations, including filtering, aggregations, joins, string functions, conditional logic, data modification, performance optimization, and miscellaneous tips. It includes examples for each method to illustrate their usage. The document emphasizes best practices such as using aliases for readability, avoiding SELECT *, and leveraging CTEs for complex queries.

Uploaded by

k3509835
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

📝 SQL Cheat Sheet: Shortcuts & Powerful Methods by Topic

1. Filtering & Conditions


Shortcut /
Situation Explanation Example
Method
Check for Instead of multiple WHERE age IN (20,
IN
multiple values ORs 25, 30)
Instead of multiple WHERE name NOT
Negate condition NOT IN
NOT ORs IN ('Ram', 'Jai')
Check NULL or IS NULL / IS WHERE address IS
Proper null checks
NOT NULL NOT NULL NOT NULL
% and _
% = any number of WHERE name LIKE
Pattern matching wildcards with
chars, _= single char 'R%'
LIKE
Compact OR for REGEXP or Regex pattern `WHERE name
multiple LIKEs RLIKE (MySQL) matching REGEXP '^(Ram
Use BETWEEN WHERE age
Simplify Boolean
instead of >= Range filtering BETWEEN 18 AND
Expressions
AND <= 25
SELECT
Replace multiple Use COALESCE For conditional
COALESCE(col1,
OR conditions or CASE expressions
col2, 'NA')

2. Aggregations & Grouping


Shortcut /
Situation Explanation Example
Method
Remove DISTINCT Returns SELECT DISTINCT
Shortcut /
Situation Explanation Example
Method
duplicates unique values branch FROM students
Group and
Filter GROUP BY branch
filter grouped HAVING
aggregates HAVING COUNT(*) > 5
data
SELECT branch,
Multiple
Combine Avoid multiple COUNT(*), AVG(age)
aggregates in
aggregates queries FROM students GROUP
one go
BY branch
Use SUM(CASE WHEN
Conditional Count with
SUM(CASE age>18 THEN 1 ELSE 0
aggregates conditions
WHEN ...) END)

3. Joins & Subqueries


Shortcut /
Situation Explanation Example
Method
Use CROSS
JOIN or
Cross join For Cartesian SELECT * FROM A
comma-
simplification product CROSS JOIN B
separated
tables
SELECT s.name FROM
Join without
Use table Shorten students s JOIN dept
repeating table
aliases queries d ON s.branch =
name
d.code
Replace Use JOIN More efficient SELECT s.name FROM
subquery with instead of IN or sometimes students s JOIN
join subqueries department d ON
Shortcut /
Situation Explanation Example
Method
s.branch =
d.dept_code
WHERE EXISTS
Faster for
Use EXISTS (SELECT 1 FROM
Exists check correlated
instead of IN orders o WHERE
subqueries
o.student_id = s.roll)

4. String & Date Functions


Situation Shortcut / Method Explanation Example
Combine SELECT
Concatenate
CONCAT() multiple CONCAT(first_name,
strings
strings ' ', last_name)
Extract SUBSTRING() or Extract part SUBSTRING(name,
substring LEFT() / RIGHT() of string 1, 3)
Case WHERE
Use LOWER() or Normalize
insensitive LOWER(name) =
UPPER() case
search 'ram'
Get current NOW() or Get system
SELECT NOW()
date/time CURRENT_TIMESTAMP datetime
Difference DATEDIFF(day,
Date
DATEDIFF() between start_date,
difference
dates end_date)

5. Conditional Logic
Shortcut /
Situation Explanation Example
Method
CASE WHEN CASE WHEN age >= 18
If-else in Conditional
THEN ELSE THEN 'Adult' ELSE 'Minor'
queries expressions
END END AS age_group
Return first COALESCE(phone, 'No
Null handling COALESCE()
non-null Phone')
Simplify Nested CASE
For complex
multiple or IF() IF(score > 50, 'Pass', 'Fail')
logic
conditions (MySQL)

6. Data Modification
Shortcut /
Situation Explanation Example
Method
Insert Insert many INSERT INTO students
multiple Multi-row insert rows in one (name, age) VALUES
rows query ('Jai', 18), ('Ram', 21)
INSERT ... ON
INSERT INTO
Upsert DUPLICATE KEY Insert or
students ... ON
(insert or UPDATE (MySQL) update in one
DUPLICATE KEY UPDATE
update) or MERGE (SQL step
age=VALUES(age)
Server)

7. Performance & Optimization


Shortcut /
Situation Explanation Example
Method
Avoid Use Indexes Speed up queries CREATE INDEX
scanning full idx_age ON
Shortcut /
Situation Explanation Example
Method
table students(age)
Limit output Return only few SELECT * FROM
LIMIT
for testing rows students LIMIT 5
Get query Understand query EXPLAIN SELECT *
EXPLAIN
execution plan performance FROM students
Use EXISTS Faster for large WHERE EXISTS
EXISTS
over IN datasets (SELECT 1 FROM ...)

8. Miscellaneous
Shortcut /
Situation Explanation Example
Method
Swap two Use CASE or UPDATE t SET col1 =
Reassign values in
columns or temporary col2, col2 = col1
update
values variables (using temp)
Rename
SELECT name AS
Use of aliases AS columns/tables
student_name
for clarity
Comment your
Comments -- or /* ... */ -- This is a comment
SQL code
SELECT name FROM
Combine Combine results
UNION A UNION SELECT
result sets from queries
name FROM B

Bonus Tips:
 Use Aliases for Readability: Always alias long table names to
shorter forms, especially in joins.
 Avoid SELECT *: Select only the columns you need for better
performance.
 Use CTEs (WITH clause) for readability: Break down complex
queries into named logical parts.
 Use CASE over multiple IF for portability: CASE is ANSI SQL
standard and works in all databases.

You might also like