Learn SQL in 30 Days: From Zero to Query Master
SQL (Structured Query Language) is the standard language for creating, managing, updating, and retrieving data from relational databases such as MySQL, PostgreSQL, SQL Server, and Oracle. It is widely used across industries — from software engineering to data analytics — making it one of the most in-demand technical skills in the job market . SQL is essential because nearly every application that stores data relies on a relational database backend, and SQL is the universal interface for communicating with those systems.
This 30-day learning plan takes you from absolute beginner to confident intermediate, covering database fundamentals, querying techniques, joins, aggregations, advanced operations like window functions and CTEs, and query optimization. The key rule: learn by doing, not by memorizing. Short, regular practice sessions of 20–30 minutes daily are more effective than occasional long study marathons .
Footnotes
-
30 Days of SQL - From Basic to Advanced Level - Comprehensive 30-day SQL roadmap from GeeksforGeeks covering basics through advanced topics. ↩
-
Learn SQL: A Practical Beginner Roadmap - LearnSQL.com roadmap emphasizing consistent practice and learn-by-doing methodology. ↩
SQL Course for Beginners — Full Course
30-Day SQL Learning Roadmap
Database Fundamentals & Setup
Day 1–2Install a RDBMS (MySQL or PostgreSQL). Understand what a RDBMS is, the concepts of tables, rows, columns, schemas, and primary/foreign keys."
Basic SELECT & Filtering
Day 3–5Master SELECT, FROM, WHERE, DISTINCT, ORDER BY, LIMIT, and comparison/logical operators (AND, OR, IN, BETWEEN, LIKE, IS NULL)."
Data Definition & Manipulation
Day 6–8Learn DDL (CREATE, ALTER, DROP TABLE) and DML (INSERT, UPDATE, DELETE). Understand data types and constraints."
Aggregation & Grouping
Day 9–11Master aggregate functions (COUNT, SUM, AVG, MIN, MAX), GROUP BY, and the HAVING clause. Understand the difference between WHERE and HAVING."
SQL Joins — The Core Skill
Day 12–15Learn INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN, CROSS JOIN, and SELF JOIN. Understand join conditions and multi-table queries."
Subqueries & Set Operations
Day 16–18Practice nested subqueries, correlated subqueries, EXISTS/NOT EXISTS, and set operations (UNION, INTERSECT, EXCEPT)."
CASE Statements & CTEs
Day 19–21Learn conditional logic with CASE WHEN, and write CTEs with the WITH clause for cleaner, readable queries."
Window Functions & Ranking
Day 22–25Master window functions: ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, SUM() OVER, and PARTITION BY."
Performance & Optimization
Day 26–28Understand indexes (clustered vs non-clustered), execution plans, normalization (1NF–3NF), and common optimization techniques."
Capstone Project & Review
Day 29–30Build a small end-to-end project: design a schema, load data, write analytical queries, and review all concepts covered."
Week 1: SQL Foundations (Day 1–7)
The first week establishes your fundamental understanding of how relational databases work and how to write basic queries. You'll set up your environment, understand the schema, and start pulling data.
Core SQL Command Categories
SQL commands are categorized into five sub-languages based on their purpose :
| Category | Full Form | Purpose | Key Commands |
|---|---|---|---|
| DQL | Data Query Language | Retrieving data | SELECT |
| DML | Data Manipulation Language | Modifying data | INSERT, UPDATE, DELETE |
| DDL | Data Definition Language | Defining structure | CREATE, ALTER, DROP, TRUNCATE |
| DCL | Data Control Language | Access permissions | GRANT, REVOKE |
| TCL | Transaction Control Language | Managing transactions | COMMIT, ROLLBACK, SAVEPOINT |
The Essential SELECT Syntax
1SELECT column1, column2 2FROM table_name 3WHERE condition 4GROUP BY column1 5HAVING group_condition 6ORDER BY column1 ASC/DESC 7LIMIT n;
The order of execution in SQL differs from the order of writing. SQL engines process: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT. Understanding this is critical — you cannot reference a column alias defined in SELECT inside your WHERE clause because WHERE is evaluated first .
Filtering with WHERE
The WHERE clause supports a rich set of operators:
- Comparison:
=,!=,<,>,<=,>= - Logical:
AND,OR,NOT - Pattern matching:
LIKEwith%(any characters) and_(single character) - Range:
BETWEEN x AND y,IN (val1, val2, ...) - Null handling:
IS NULL,IS NOT NULL
⏱ Time commitment: Spend ~1–2 hours per day. Write at least 5–10 queries daily on a sample database (e.g., Sakila, Northwind, or any Kaggle dataset loaded into your local RDBMS).
Footnotes
-
SQL Tutorial - GeeksforGeeks - Complete SQL reference covering DDL, DML, DCL, TCL, queries, and advanced concepts. ↩
-
30 Days of SQL - From Basic to Advanced Level - Comprehensive 30-day SQL roadmap from GeeksforGeeks covering basics through advanced topics. ↩
Setting Up Your SQL Environment
- 1Step 1
Pick PostgreSQL (open source, feature-rich) or MySQL (industry standard, lightweight). Both are free and widely supported. Download from postgresql.org or mysql.com.
- 2Step 2
Follow the official installer for your OS. During setup, set a root password and note the default port (PostgreSQL: 5432, MySQL: 3306). Verify the installation by connecting via the command-line client.
- 3Step 3
Use pgAdmin for PostgreSQL, MySQL Workbench for MySQL, or a cross-platform tool like DBeaver or DataGrip. GUI clients make it easier to visualize tables and write queries.
- 4Step 4
Download and import a sample database. Recommended options:
- Sakila (DVD rental store — great for joins, aggregations)
- Northwind (product/supplier/order data — classic for learning)
1-- Example: Creating your first table 2CREATE TABLE employees ( 3 emp_id INT PRIMARY KEY, 4 first_name VARCHAR(50), 5 last_name VARCHAR(50), 6 department VARCHAR(50), 7 salary DECIMAL(10,2), 8 hire_date DATE 9); - 5Step 5
Open your SQL client, connect to the sample database, and run:
1SELECT * FROM film LIMIT 10;You should see 10 rows of data. Congratulations — you're querying a database!
Week 2: Intermediate Queries (Day 8–14)
Now that you can retrieve and filter data, it's time to learn how to summarize, transform, and group data — the bread and butter of data analysis with SQL.
Aggregate Functions and GROUP BY
Aggregate functions collapse multiple rows into a single result row. When combined with GROUP BY, they produce one summary row per group:
1SELECT 2 department, 3 COUNT(*) AS employee_count, 4 AVG(salary) AS avg_salary, 5 MAX(salary) AS max_salary 6FROM employees 7GROUP BY department 8HAVING COUNT(*) > 5 9ORDER BY avg_salary DESC;
WHERE vs HAVING: The WHERE clause filters individual rows before aggregation; HAVING filters groups after aggregation. This is a common interview question and a frequent source of bugs .
CASE Statements for Conditional Logic
The CASE expression lets you implement if-then-else logic inside SQL queries:
1SELECT 2 product_name, 3 price, 4 CASE 5 WHEN price < 20 THEN 'Budget' 6 WHEN price BETWEEN 20 AND 50 THEN 'Mid-Range' 7 ELSE 'Premium' 8 END AS price_category 9FROM products;
Subqueries
A subquery can appear in WHERE, SELECT, or FROM clauses:
1-- Find employees earning above the company average 2SELECT first_name, last_name, salary 3FROM employees 4WHERE salary > (SELECT AVG(salary) FROM employees);
Correlated subqueries reference columns from the outer query and are evaluated once per row:
1-- Find employees earning above their department's average 2SELECT e.first_name, e.salary, e.department 3FROM employees e 4WHERE e.salary > ( 5 SELECT AVG(salary) 6 FROM employees 7 WHERE department = e.department 8);
Footnotes
-
30 Days of SQL - From Basic to Advanced Level - Comprehensive 30-day SQL roadmap from GeeksforGeeks covering basics through advanced topics. ↩
Common SQL Pitfall: NULL Comparisons
In SQL, NULL = NULL evaluates to UNKNOWN, not TRUE. Always use IS NULL or IS NOT NULL to test for null values. Writing WHERE column = NULL will return zero rows — this is one of the most common beginner mistakes in SQL. Similarly, NOT IN (subquery) can behave unexpectedly if the subquery returns any NULL values.
Week 3: Joins & Multi-Table Queries (Day 15–21)
Real-world databases consist of many related tables. JOINs are the mechanism for bringing that data together, and they represent the single most important skill for any SQL practitioner .
The SQL Join Types
JOIN Syntax and Use Cases
1-- INNER JOIN: Get all orders with customer details 2SELECT c.customer_name, o.order_date, o.total_amount 3FROM customers c 4INNER JOIN orders o ON c.customer_id = o.customer_id; 5 6-- LEFT JOIN: All customers, even those without orders 7SELECT c.customer_name, o.order_date 8FROM customers c 9LEFT JOIN orders o ON c.customer_id = o.customer_id; 10 11-- Find customers with NO orders (use LEFT JOIN + WHERE NULL) 12SELECT c.customer_name 13FROM customers c 14LEFT JOIN orders o ON c.customer_id = o.customer_id 15WHERE o.order_id IS NULL;
The LEFT JOIN + WHERE NULL pattern is a powerful technique for finding records in one table that have no match in another — often used for identifying gaps, orphaned records, or anti-join patterns.
Set Operations
Set operations combine results from multiple queries:
- UNION: Combines and removes duplicates
- UNION ALL: Combines and keeps duplicates (faster)
- INTERSECT: Returns only common rows
- EXCEPT: Returns rows in first query but not second
1-- Customers from both regions (no duplicates) 2SELECT customer_id FROM us_customers 3UNION 4SELECT customer_id FROM eu_customers; 5 6-- Products that have never been ordered 7SELECT product_id FROM products 8EXCEPT 9SELECT product_id FROM order_items;
Footnotes
-
SQL Concepts for Beginner, Intermediate, and Advanced Developers - Community-sourced breakdown of SQL skill levels and concepts. ↩
SQL Skill Distribution Across Job Roles
Average percentage of SQL sub-skills used by role (based on industry demand data)
Week 4: Advanced SQL (Day 22–30)
This is where SQL becomes truly powerful. Advanced techniques like window functions, CTEs, and optimization strategies distinguish intermediate from expert practitioners .
Window Functions
Window functions are perhaps the most transformative SQL concept to learn. Unlike aggregate functions with GROUP BY, window functions let you compute values across related rows while keeping every row in the result .
The general syntax:
1function_name() OVER ( 2 [PARTITION BY column] 3 [ORDER BY column] 4 [frame_clause] 5)
Categories of Window Functions
| Category | Functions | Description |
|---|---|---|
| Ranking | ROW_NUMBER(), RANK(), DENSE_RANK(), NTILE(n) | Assign rank or row numbers within a partition |
| Aggregate | SUM(), AVG(), COUNT(), MAX(), MIN() | Compute aggregates over a window frame |
| Value | LAG(), LEAD(), FIRST_VALUE(), LAST_VALUE() | Access values from other rows relative to current |
Practical Examples
1-- Running total of sales per customer 2SELECT 3 customer_id, 4 order_date, 5 amount, 6 SUM(amount) OVER ( 7 PARTITION BY customer_id 8 ORDER BY order_date 9 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 10 ) AS running_total 11FROM orders; 12 13-- Rank employees by salary within each department 14SELECT 15 first_name, 16 department, 17 salary, 18 DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS dept_rank 19FROM employees; 20 21-- Compare each row to the previous row (year-over-year growth) 22SELECT 23 year, 24 revenue, 25 LAG(revenue, 1) OVER (ORDER BY year) AS prev_year_revenue, 26 revenue - LAG(revenue, 1) OVER (ORDER BY year) AS yoy_growth 27FROM annual_revenue;
Common Table Expressions (CTEs)
A CTE improves readability and maintainability of complex queries by breaking them into logical blocks :
1WITH monthly_sales AS ( 2 SELECT 3 DATE_TRUNC('month', order_date) AS month, 4 SUM(amount) AS total_sales 5 FROM orders 6 GROUP BY 1 7), 8ranked_months AS ( 9 SELECT 10 month, 11 total_sales, 12 LAG(total_sales) OVER (ORDER BY month) AS prev_month_sales 13 FROM monthly_sales 14) 15SELECT 16 month, 17 total_sales, 18 ROUND((total_sales - prev_month_sales) / prev_month_sales * 100, 2) AS pct_change 19FROM ranked_months 20WHERE prev_month_sales IS NOT NULL 21ORDER BY month;
Recursive CTEs can traverse hierarchical data like org charts or category trees:
1WITH RECURSIVE org_hierarchy AS ( 2 -- Anchor: top-level managers 3 SELECT emp_id, emp_name, manager_id, 1 AS level 4 FROM employees 5 WHERE manager_id IS NULL 6 7 UNION ALL 8 9 -- Recursive: employees reporting to each level 10 SELECT e.emp_id, e.emp_name, e.manager_id, h.level + 1 11 FROM employees e 12 JOIN org_hierarchy h ON e.manager_id = h.emp_id 13) 14SELECT * FROM org_hierarchy ORDER BY level, emp_name;
Footnotes
-
Advanced SQL Query Techniques for Data Engineers - In-depth guide to window functions, recursive CTEs, and optimization techniques. ↩ ↩2 ↩3
SQL Query Optimization Process
- 1Step 1
Use
EXPLAINorEXPLAIN ANALYZEbefore your query to see how the database engine processes it. Look for:- Sequential scans (full table reads) — costly on large tables
- Index scans — efficient lookups
- Join strategies (nested loop, hash join, merge join)
1EXPLAIN ANALYZE 2SELECT e.first_name, d.department_name 3FROM employees e 4JOIN departments d ON e.dept_id = d.dept_id 5WHERE e.salary > 80000; - 2Step 2
Create indexes on columns used in
WHERE,JOIN ON, andORDER BYclauses. Understand the trade-off: indexes speed up reads but slow down writes.1-- B-tree index (default, good for equality & range) 2CREATE INDEX idx_emp_salary ON employees(salary); 3 4-- Composite index for multi-column queries 5CREATE INDEX idx_emp_dept_salary ON employees(dept_id, salary); - 3Step 3
Apply these optimization techniques:
- Replace
SELECT *with explicit column lists - Use
EXISTSinstead ofINfor large subqueries - Replace correlated subqueries with JOINs where possible
- Use
UNION ALLinstead ofUNIONwhen duplicates are acceptable - Avoid functions on indexed columns in WHERE clauses (e.g.,
WHERE UPPER(name) = 'JOHN'defeats the index)
- Replace
- 4Step 4
Compare query execution time before and after optimization:
1-- Before: Correlated subquery (slow) 2SELECT * FROM orders o WHERE EXISTS ( 3 SELECT 1 FROM customers c WHERE c.id = o.customer_id AND c.status = 'active' 4); 5 6-- After: JOIN (typically faster) 7SELECT o.* FROM orders o 8JOIN customers c ON o.customer_id = c.id 9WHERE c.status = 'active';
1-- Connect to database 2psql -U postgres -d mydb 3 4-- List all databases 5\l 6 7-- Describe table structure 8\d employees 9 10-- Show query execution plan 11EXPLAIN ANALYZE SELECT * FROM employees WHERE salary > 50000; 12 13-- Generate series (PostgreSQL-specific) 14SELECT generate_series(1, 10) AS n;
SQL Deep Dive — Common Questions & Edge Cases
The #1 SQL Practice Strategy
Solve at least 2–3 SQL problems every day on platforms like HackerRank, LeetCode, StrataScratch, or DataLemur. Start with easy problems and gradually increase difficulty. The key is consistency — 20 minutes daily beats 3 hours once a week. Practice platforms filter by topic (joins, aggregations, window functions) so you can target weak areas .
Footnotes
-
7 Best Platforms to Practice SQL - KDnuggets review of top SQL practice platforms including HackerRank, LeetCode, and StrataScratch. ↩
Beware: Accidental Data Modification
Always run UPDATE and DELETE queries with a WHERE clause in a transaction first. Before executing destructive operations, wrap them in a transaction:
1BEGIN; 2DELETE FROM employees WHERE department = 'Old Dept'; 3-- Check affected rows first! 4-- If correct: COMMIT; 5-- If wrong: ROLLBACK;
One missing WHERE clause can wipe an entire table. Always test with a SELECT that has the same WHERE condition before running DELETE or UPDATE.
30-Day SQL Study Time Allocation
Recommended daily hour distribution across topic areas
Daily Practice Resources
To reinforce each week's learning, dedicate time to hands-on practice on these platforms:
| Platform | Best For | Cost | Key Feature |
|---|---|---|---|
| HackerRank | Interview-style problems | Free (basic) | Filter by SQL topic & difficulty |
| LeetCode | Algorithmic SQL challenges | Free (basic) | 200+ database problems |
| StrataScratch | Real company SQL questions | Free (basic) | Questions from actual interviews |
| DataLemur | Data analytics SQL | Free (basic) | Focused on analytics/interview prep |
| SQLZoo | Interactive tutorials | Free | Browser-based, no setup needed |
| LearnSQL.com | Structured courses | Paid (free exercises) | Track-based learning paths |
Week 4 milestone: By Day 30, you should be able to write a multi-join query with CTEs, window functions, and conditional logic to answer a business question like "What is the month-over-month revenue growth rate for our top 10 customers by total spend?" — all in a single query.
Knowledge Check
What is the correct order of SQL query execution by the database engine?
Explore Related Topics
Teach Me Data Analysis: From Questions to Decisions
Master Class: SQL Window Functions
SQL window functions let you calculate aggregates (e.g., sums, ranks) over a defined set of rows while preserving each row’s identity, enabling running totals, moving averages, and ranking without collapsing the result set.
- Syntax follows
FUNCTION() OVER (PARTITION BY … ORDER BY … [FRAME_CLAUSE]), where PARTITION groups rows and ORDER defines their sequence. - Ranking functions differ:
ROW_NUMBER()always increments,RANK()skips numbers on ties, andDENSE_RANK()gives consecutive ranks despite ties. - The query planner processes window functions after FROM/JOIN, WHERE, GROUP BY/HAVING, then sorts by partition and order before applying the window logic.
- FRAME clauses (
ROWSorRANGE) control the exact sliding window, e.g.,ROWS BETWEEN 2 PRECEDING AND CURRENT ROW. - Because they require sorting, window functions can be costly on large tables; appropriate indexes on partition and order columns are essential.
Learn React in 30 Days: A Comprehensive Course
Learn React in 30 Days: From Zero to Production