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

Alfred Marshall – The Father of Modern Microeconomics

  Welcome back to the blog! Today we explore the life and legacy of Alfred Marshall (1842–1924) , the British economist who laid the foundations of modern microeconomics . His landmark book, Principles of Economics (1890), introduced core concepts like supply and demand , elasticity , and market equilibrium — ideas that continue to shape how we understand economics today. Who Was Alfred Marshall? Alfred Marshall was a professor at the University of Cambridge and a key figure in the development of neoclassical economics . He believed economics should be rigorous, mathematical, and practical , focusing on real-world issues like prices, wages, and consumer behavior. Marshall also emphasized that economics is ultimately about improving human well-being. Key Contributions 1. Supply and Demand Analysis Marshall was the first to clearly present supply and demand as intersecting curves on a graph. He showed how prices are determined by both what consumers are willing to pay (dem...

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...

Kickstart Your SQL Journey with Our Step-by-Step Tutorial Series

  Welcome to Data Analyst BI! If you’ve ever felt overwhelmed by rows, columns, and cryptic error messages when trying to write your first SQL query, you’re in the right place. Today we’re launching a comprehensive SQL tutorial series crafted specifically for beginners. Whether you’re just starting your data career, pivoting from another field, or simply curious about how analysts slice and dice data, these lessons will guide you from day zero to confident query builder. In each installment, you’ll find clear explanations, annotated examples, and hands-on exercises. By the end of this series, you’ll be able to: Write efficient SQL queries to retrieve and transform data Combine multiple tables to uncover relationships Insert, update, and delete records safely Design robust database schemas with keys and indexes Optimize performance for large datasets Ready to master SQL in a structured, step-by-step way? Let’s explore the full roadmap ahead. Wh...