Skip to main content

SQL CHEAT SheetSQL Cheat Sheet: Essential Commands, Clauses, and Patterns for Data Analysts

 Structured Query Language (SQL) is the backbone of data analysis, data engineering, and business intelligence. Whether you're querying a relational database, building ETL pipelines, or exploring datasets in Power BI, SQL is the language that lets you interact with data efficiently and precisely.

This cheat sheet is designed to be your quick-access reference for the most commonly used SQL commands, clauses, functions, and patterns. It’s ideal for beginners who want to learn fast, and for experienced analysts who need a refresher or a compact guide.

📌 What Is SQL?

SQL (Structured Query Language) is a domain-specific language used to manage and manipulate relational databases. It allows users to:

  • Retrieve data (SELECT)

  • Insert new records (INSERT)

  • Update existing data (UPDATE)

  • Delete records (DELETE)

  • Create and modify tables (CREATE, ALTER)

  • Control access and permissions (GRANT, REVOKE)

SQL is supported by most relational database systems, including:

  • Microsoft SQL Server

  • PostgreSQL

  • MySQL

  • Oracle

  • SQLite

🔍 Basic SQL Syntax

sql
SELECT column1, column2
FROM table_name
WHERE condition
ORDER BY column1 ASC;

🧠 Key Clauses

ClausePurposeExample
SELECTChoose columnsSELECT name, age FROM users
FROMSpecify tableFROM employees
WHEREFilter rowsWHERE age > 30
ORDER BYSort resultsORDER BY salary DESC
GROUP BYAggregate rowsGROUP BY department
HAVINGFilter aggregated resultsHAVING COUNT(*) > 5
LIMITRestrict number of rows (MySQL, PG)LIMIT 10
TOPRestrict rows (SQL Server)SELECT TOP 5 * FROM sales

🧩 Filtering Data

WHERE Clause

sql
SELECT * FROM orders
WHERE status = 'Shipped' AND total > 100;

BETWEEN

sql
SELECT * FROM payments
WHERE amount BETWEEN 50 AND 500;

IN

sql
SELECT * FROM customers
WHERE country IN ('Italy', 'France', 'Germany');

LIKE

sql
SELECT * FROM products
WHERE name LIKE 'A%'; -- Starts with A

🔄 Joining Tables

INNER JOIN

sql
SELECT orders.id, customers.name
FROM orders
INNER JOIN customers ON orders.customer_id = customers.id;

LEFT JOIN

sql
SELECT employees.name, departments.name
FROM employees
LEFT JOIN departments ON employees.dept_id = departments.id;

RIGHT JOIN

sql
SELECT students.name, courses.title
FROM students
RIGHT JOIN courses ON students.course_id = courses.id;

FULL OUTER JOIN

sql
SELECT *
FROM table1
FULL OUTER JOIN table2 ON table1.id = table2.id;

📊 Aggregation Functions

FunctionDescriptionExample
COUNT()Number of rowsCOUNT(*)
SUM()Total of valuesSUM(sales)
AVG()Average valueAVG(score)
MIN()Minimum valueMIN(price)
MAX()Maximum valueMAX(age)

GROUP BY

sql
SELECT department, COUNT(*) AS total_employees
FROM employees
GROUP BY department;

🧠 Subqueries

Inline Subquery

sql
SELECT name
FROM customers
WHERE id IN (SELECT customer_id FROM orders WHERE total > 500);

Correlated Subquery

sql
SELECT name
FROM employees e
WHERE salary > (SELECT AVG(salary) FROM employees WHERE dept_id = e.dept_id);

🛠️ Table Management

CREATE TABLE

sql
CREATE TABLE users (
    id INT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100),
    created_at DATE
);

ALTER TABLE

sql
ALTER TABLE users ADD COLUMN phone VARCHAR(20);

DROP TABLE

sql
DROP TABLE old_data;

🔐 Data Manipulation

INSERT

sql
INSERT INTO products (name, price)
VALUES ('Laptop', 1200);

UPDATE

sql
UPDATE orders
SET status = 'Delivered'
WHERE id = 101;

DELETE

sql
DELETE FROM users
WHERE last_login < '2023-01-01';

🧠 Window Functions

Window functions allow you to perform calculations across a set of rows related to the current row.

ROW_NUMBER

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

RANK

sql
SELECT name, RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS dept_rank
FROM employees;

LEAD / LAG

sql
SELECT name, salary,
       LAG(salary) OVER (ORDER BY salary) AS previous_salary
FROM employees;

🧠 Common Table Expressions (CTEs)

CTEs improve readability and allow recursive queries.

sql
WITH HighValueOrders AS (
    SELECT * FROM orders WHERE total > 1000
)
SELECT * FROM HighValueOrders WHERE status = 'Shipped';

🧠 Useful Patterns

Find Duplicates

sql
SELECT email, COUNT(*)
FROM users
GROUP BY email
HAVING COUNT(*) > 1;

Top N per Group

sql
SELECT *
FROM (
    SELECT *,
           ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC) AS rank
    FROM products
) ranked
WHERE rank <= 3;

🧠 Performance Tips

  • Use indexes on columns used in WHERE, JOIN, and ORDER BY

  • Avoid SELECT * in production queries

  • Use EXPLAIN or QUERY PLAN to analyze performance

  • Limit subqueries and nested joins when possible

  • Normalize data but denormalize for reporting when needed









































 Final Thoughts

SQL is a foundational skill for any data professional. Whether you're building dashboards, writing ETL scripts, or exploring datasets, knowing how to write clean, efficient SQL queries is essential.

This cheat sheet is meant to be a living reference—bookmark it, expand it, and adapt it to your database environment. With practice, you’ll be able to write queries that are not only correct, but elegant and optimized.

Comments

Popular posts from this blog

Unlocking South America's Data Potential: Trends, Challenges, and Strategic Opportunities for 2025

  Introduction South America is entering a pivotal phase in its digital and economic transformation. With countries like Brazil, Mexico, and Argentina investing heavily in data infrastructure, analytics, and digital governance, the region presents both challenges and opportunities for professionals working in Business Intelligence (BI), Data Analysis, and IT Project Management. This post explores the key data trends shaping South America in 2025, backed by insights from the World Bank, OECD, and Statista. It’s designed for analysts, project managers, and decision-makers who want to understand the region’s evolving landscape and how to position themselves for impact. 1. Economic Outlook: A Region in Transition According to the World Bank’s Global Economic Prospects 2025 , Latin America is expected to experience slower growth compared to global averages, with GDP expansion constrained by trade tensions and policy uncertainty. Brazil and Mexico remain the largest economies, with proj...

“Alive and Dead?”

 Schrödinger’s Cat, Quantum Superposition, and the Measurement Problem 1. A Thought-Experiment with Nine Lives In 1935, Austrian physicist Erwin Schrödinger devised a theatrical setup to spotlight how bizarre quantum rules look when scaled up to everyday objects[ 1 ]. A sealed steel box contains: a single radioactive atom with a 50 % chance to decay in one hour, a Geiger counter wired to a hammer, a vial of lethal cyanide, an unsuspecting cat. If the atom decays, the counter trips, the hammer smashes the vial, and the cat dies; if not, the cat survives. Quantum mechanics says the atom is in a superposition of “decayed” and “not-decayed,” so—by entanglement—the whole apparatus, cat included, must be in a superposition of ‘alive’ and ‘dead’ until an observer opens the box[ 1 ][ 2 ]. Schrödinger wasn’t condemning tabbies; he was mocking the idea that microscopic indeterminacy automatically balloons into macroscopic absurdity. 2. Superposition 101 The principle: if a quantum syste...

5 Essential Power BI Dashboards Every Data Analyst Should Know

In today’s data-driven world, Power BI has become one of the most powerful tools for data analysts and business intelligence professionals. Here are five essential Power BI dashboards every data analyst should know how to build and interpret. ## 1. Sales Dashboard Track sales performance in real-time, including: - Revenue by region - Monthly trends - Year-over-year comparison 💡 Use case: Sales teams, area managers --- ## 2. Marketing Dashboard Monitor marketing campaign effectiveness with: - Cost per click (CPC) - Conversion rate - Traffic sources 💡 Use case: Digital marketing teams --- ## 3. Human Resources (HR) Dashboard Get insights into: - Absenteeism rate - Average employee age - Department-level performance 💡 Use case: HR departments, business partners --- ## 4. Financial Dashboard Keep financial KPIs under control: - Gross operating margin (EBITDA) - Monthly cash inflow/outflow - Profitability ratios 💡 Use case: Finance and accounting teams --- ## 5. Customer Dashboard Segme...