SQL CHEAT SHEET the no-cap guide to talking to databases. SELECT JOINS GROUP BY WINDOW FN CTEs SHORTCUTS INTERVIEW Qs PRACTICE LAB FREE STUDY MATERIAL BEGINNER FRIENDLY What's inside (10 pages) 01 Cover 02 Why SQL matters 03 SELECT + Filtering 04 Aggregates + GROUP BY 05 JOINs + Set ops 06 Function shortcuts 07 Subquery, CTE, Window 08 Create / Insert / Update 09 Interview quick hits 10 Practice lab LEARN-X ACADEMY GLOBAL Ready to turn data into a career? SQL is a must-have skill for data analysts, developers and BI roles. Learn it the easy way with Learn-X Academy Global. SQL COURSE OPEN FOR ENROLMENT CALL / WHATSAPP US 8778541617 www.learnxacademyglobal.com JOIN THE BATCH NOW Learn-X Academy Global | SQL Study Material | 1 / 10 www.learnxacademyglobal.com 02 Why SQL? it's literally everywhere. learn it once, flex forever. SQL = Structured Query Language The language you use to talk to databases : ask questions, add data, update stuff and delete things. Works on MySQL, PostgreSQL, SQL Server, Oracle and SQLite. Learn once, use everywhere. The core is the same in every database. Why it is a must-have skill • Needed for Data Analyst, BI, Data Engineer, Backend and QA roles • Every app (banking, shopping, social, health) runs on a database • Pairs with Excel, Power BI, Tableau and Python • English-like syntax: easy to start, hard to outgrow • Almost every data interview has an SQL round WHERE YOU WILL USE IT Data Analyst dashboards, reports, insights Backend Dev APIs, apps, user data BI Developer Power BI, Tableau, KPIs Data Engineer pipelines, warehouses SQL IN REAL LIFE Online shopping Show all orders placed last week by a customer. Banking Check a balance, then move money safely with a transaction. Social media Fetch the latest posts from the people you follow. 5 FLAVOURS OF SQL (interview fav!) Type Full form Commands Vibe DQL Data Query Language SELECT ask questions DML Data Manipulation Language INSERT UPDATE DELETE change the data DDL Data Definition Language CREATE ALTER DROP TRUNCATE build the structure DCL Data Control Language GRANT REVOKE who gets access TCL Transaction Control Language COMMIT ROLLBACK SAVEPOINT save or undo YOUR SQL ROADMAP Basics Filtering Aggregates JOINs Window Fn Projects hello_sql.sql -- your very first query. yes, it's this simple SELECT name, marks FROM students WHERE marks > 80 ORDER BY marks DESC ; try me! LEARN-X ACADEMY GLOBAL Why learn SQL with us? Every company runs on data and SQL is how you talk to it. Join our course and go from beginner to confident, step by step. CALL / WHATSAPP US 8778541617 www.learnxacademyglobal.com JOIN THE BATCH NOW Learn-X Academy Global | SQL Study Material | 2 / 10 www.learnxacademyglobal.com 03 SELECT + Filter pull exactly the data you want. nothing extra. skeleton.sql SELECT column1, column2 -- what FROM table_name -- where from WHERE condition -- filter rows ORDER BY column1 DESC -- sort LIMIT 10; -- top 10 only shortcuts.sql SELECT * FROM students; SELECT DISTINCT city FROM students; SELECT name AS student, marks + 5 AS bonus_marks FROM students; OPERATORS CHEAT TABLE LIKE WILDCARDS Operator Meaning Example = <> != equal / not equal city = 'Chennai' > < >= <= compare numbers marks >= 60 AND OR NOT combine conditions a > 5 AND b < 9 BETWEEN inside a range (inclusive) age BETWEEN 18 AND 25 IN (...) matches any in list city IN ('Chennai','Pune') IS NULL is empty (not = NULL!) phone IS NULL Pattern Finds 'A%' starts with A '%a' ends with a '%an%' contains "an" '_a%' 2nd letter is a '___' exactly 3 chars Pro tip: NULL is sneaky NULL = NULL is never true. Always use IS NULL or IS NOT NULL REAL EXAMPLES filters.sql -- students from Chennai or Pune scoring above 75, best first SELECT name, city, marks FROM students WHERE city IN ('Chennai', 'Pune') AND marks > 75 ORDER BY marks DESC LIMIT 5; -- names starting with 'A' and age between 18 and 25 SELECT * FROM students WHERE name LIKE 'A%' AND age BETWEEN 18 AND 25; SQL READS IN A DIFFERENT ORDER THAN YOU WRITE FROM WHERE GROUP BY HAVING SELECT ORDER BY LIMIT LEARN-X ACADEMY GLOBAL Stop copy-pasting. Start understanding. Our SQL course is hands-on: write real queries from day one and build skills that recruiters look for. CALL / WHATSAPP US 8778541617 www.learnxacademyglobal.com JOIN THE BATCH NOW Learn-X Academy Global | SQL Study Material | 3 / 10 www.learnxacademyglobal.com 04 Aggregates crunch numbers like an analyst. GROUP BY is the main character. AGGREGATE FUNCTIONS Function What it does Example COUNT(*) counts all rows COUNT(*) COUNT(col) counts non-NULL values COUNT(phone) COUNT(DISTINCT c) counts unique values COUNT(DISTINCT city) SUM(col) total SUM(salary) AVG(col) average AVG(marks) MIN / MAX smallest / largest MAX(salary) Golden rules • Every column in SELECT that is not aggregated must be in GROUP BY • WHERE filters rows (before grouping) • HAVING filters groups (after grouping) • Aggregates ignore NULLs (except COUNT(*) ) GROUP BY IN ACTION group_by.sql -- how many students per city? SELECT city, COUNT(*) AS total_students FROM students GROUP BY city; -- average marks per course, only courses averaging above 70 SELECT course, AVG(marks) AS avg_marks FROM students WHERE city = 'Chennai' -- filter rows first GROUP BY course HAVING AVG(marks) > 70 -- then filter groups ORDER BY avg_marks DESC ; WHERE vs HAVING (asked in every interview) WHERE HAVING Filters individual rows groups / aggregates Runs before GROUP BY after GROUP BY Can use SUM, AVG? No Yes Example WHERE salary > 30000 HAVING AVG(salary) > 30000 Handy extras GROUP_CONCAT(col) (MySQL) / STRING_AGG(col, ',') (PostgreSQL, SQL Server) joins values into one text. GROUP BY works with 2+ columns too: GROUP BY city, course LEARN-X ACADEMY GLOBAL Data analysts live in GROUP BY. Want to crack analyst interviews? Learn SQL the right way with projects and practice at Learn-X Academy Global. CALL / WHATSAPP US 8778541617 www.learnxacademyglobal.com JOIN THE BATCH NOW Learn-X Academy Global | SQL Study Material | 4 / 10 www.learnxacademyglobal.com 05 JOINs combine tables without the headache. A B INNER JOIN only matches keeps overlap A B LEFT JOIN all of A + matches keeps A rows A B RIGHT JOIN all of B + matches keeps B rows A B FULL JOIN everything from both keeps all rows joins.sql SELECT s.name, c.course_name FROM students s -- A (alias s) INNER JOIN courses c ON s.course_id = c.id; -- B (alias c) -- swap INNER for LEFT / RIGHT / FULL to change the result -- find the missing ones: students with NO course SELECT s.name FROM students s LEFT JOIN courses c ON s.course_id = c.id WHERE c.id IS NULL ; SPECIAL JOINS COMBINING RESULTS (SET OPS) special.sql -- CROSS JOIN: every row x every row SELECT * FROM sizes CROSS JOIN colors; -- SELF JOIN: table joins itself SELECT e.name AS employee, m.name AS manager FROM employees e JOIN employees m ON e.manager_id = m.id; Command Result UNION A + B, removes duplicates UNION ALL A + B, keeps duplicates (faster) INTERSECT only rows in both EXCEPT / MINUS rows in A not in B Join checklist • Join on matching keys (PK = FK) • Always use table aliases (s, c, e) • Same column count and type needed for UNION LEARN-X ACADEMY GLOBAL JOINs getting messy? Let us make them click. Join our SQL course for guided practice, real-world examples and doubt clearing. CALL / WHATSAPP US 8778541617 www.learnxacademyglobal.com JOIN THE BATCH NOW Learn-X Academy Global | SQL Study Material | 5 / 10 www.learnxacademyglobal.com 06 Function Shortcuts the cheat codes. save hours, look pro. STRING functions UPPER(x) / LOWER(x) change case LENGTH(x) [LEN in SQL Server] count characters TRIM(x) remove spaces at both ends SUBSTRING(x, start, len) cut part of a string CONCAT(a, b, ...) join text together REPLACE(x, 'old', 'new') swap text LEFT(x, n) / RIGHT(x, n) first / last n chars DATE functions CURRENT_DATE / NOW() today / now [GETDATE() in SQL Server] YEAR(d) MONTH(d) DAY(d) pick a date part EXTRACT(YEAR FROM d) standard way (PostgreSQL, MySQL) DATEDIFF(d1, d2) days between two dates DATE_ADD(d, INTERVAL 7 DAY) add time (MySQL) DATE_FORMAT(d, '%d-%m-%Y') format a date (MySQL) NUMERIC functions ROUND(x, 2) round to 2 decimals CEIL(x) / FLOOR(x) round up / down ABS(x) remove the minus sign MOD(a, b) or a % b remainder (even / odd checks) POWER(x, 2) / SQRT(x) power and square root NULL + LOGIC functions COALESCE(a, b, 'N/A') first non-NULL value IFNULL(a, 0) / ISNULL(a, 0) replace NULL (MySQL / SQL Server) NULLIF(a, b) NULL if a = b (avoids divide by 0) CAST(x AS INT) change data type CASE WHEN ... END if-else inside SQL (below) CASE WHEN = if / else for SQL functions.sql SELECT name, marks, CASE WHEN marks >= 90 THEN 'Topper' WHEN marks >= 60 THEN 'Pass' ELSE 'Needs work' END AS result, UPPER(city) AS city_caps, COALESCE(phone, 'no phone') AS contact FROM students; Note: function names vary slightly between MySQL, PostgreSQL and SQL Server. The idea stays the same. LEARN-X ACADEMY GLOBAL Functions = shortcuts = faster you. Save hours at work and level up your resume. Master SQL with Learn-X Academy Global. CALL / WHATSAPP US 8778541617 www.learnxacademyglobal.com JOIN THE BATCH NOW Learn-X Academy Global | SQL Study Material | 6 / 10 www.learnxacademyglobal.com 07 Subquery, CTE, Window the advanced stuff recruiters love to ask. SUBQUERY = query inside a query CTE = a named temp result (WITH) subquery.sql -- earn more than the average? SELECT name, salary FROM employees WHERE salary > ( SELECT AVG(salary) FROM employees ); cte.sql WITH dept_avg AS ( SELECT dept, AVG(salary) AS avg_sal FROM employees GROUP BY dept ) SELECT e.name, e.salary, d.avg_sal FROM employees e JOIN dept_avg d ON e.dept = d.dept; WINDOW FUNCTIONS: calculate across rows, keep every row Function What it gives you ROW_NUMBER() unique 1, 2, 3... no ties RANK() ties share rank, then skips DENSE_RANK() ties share rank, no skip LAG(col) / LEAD(col) previous / next row value SUM(col) OVER (...) running total NTILE(4) split rows into 4 buckets Salary ROW_NUMBER RANK DENSE_RANK 90000 1 1 1 90000 2 1 1 80000 3 3 2 70000 4 4 3 Tie at 90000: RANK jumps to 3, DENSE_RANK goes to 2. window.sql SELECT name, dept, salary, RANK() OVER ( PARTITION BY dept ORDER BY salary DESC ) AS dept_rank, SUM(salary) OVER ( ORDER BY id) AS running_total, LAG(salary) OVER ( ORDER BY id) AS prev_salary FROM employees; INTERVIEW CLASSIC: top 2 salaries in each department top_n_per_group.sql WITH ranked AS ( SELECT name, dept, salary, DENSE_RANK() OVER ( PARTITION BY dept ORDER BY salary DESC ) AS rnk FROM employees ) SELECT name, dept, salary FROM ranked WHERE rnk <= 2; LEARN-X ACADEMY GLOBAL Window functions? Interview favourite. Learn the advanced SQL that recruiters love to ask. Enrol with us and practise it hands-on. CALL / WHATSAPP US 8778541617 www.learnxacademyglobal.com JOIN THE BATCH NOW Learn-X Academy Global | SQL Study Material | 7 / 10 www.learnxacademyglobal.com 08 Create + Modify build tables, add data, change it, stay safe. CREATE TABLE with constraints INSERT / UPDATE / DELETE create.sql CREATE TABLE students ( id INT PRIMARY KEY , name VARCHAR (50) NOT NULL , email VARCHAR (100) UNIQUE , age INT CHECK (age >= 18), city VARCHAR (30) DEFAULT 'Chennai', course_id INT , FOREIGN KEY (course_id) REFERENCES courses(id) ); dml.sql INSERT INTO students (id, name, age) VALUES (1, 'Arun', 21), (2, 'Meena', 22); UPDATE students SET city = 'Madurai' WHERE id = 2; DELETE FROM students WHERE id = 1; DANGER ZONE UPDATE or DELETE without WHERE hits every row . Run a SELECT with the same WHERE first! CONSTRAINTS Constraint Meaning PRIMARY KEY unique + not null, one per table FOREIGN KEY links to a PK in another table UNIQUE no duplicate values NOT NULL value is required CHECK value must pass a rule DEFAULT auto value if none given DELETE TRUNCATE DROP Removes chosen rows all rows whole table WHERE? yes no no Rollback? yes depends* depends* Speed slower fast fast Table stays? yes yes no *depends on the database (PostgreSQL and SQL Server allow it in a transaction). ALTER, INDEX & TRANSACTIONS alter_index.sql ALTER TABLE students ADD COLUMN phone VARCHAR (15); ALTER TABLE students DROP COLUMN phone; ALTER TABLE students RENAME TO learners; CREATE INDEX idx_name ON students(name); -- index = faster searches on that column transaction.sql BEGIN ; -- start UPDATE accounts SET bal = bal - 500 WHERE id = 1; UPDATE accounts SET bal = bal + 500 WHERE id = 2; COMMIT ; -- save both -- something went wrong? ROLLBACK; (undo) LEARN-X ACADEMY GLOBAL Build it, don't just query it. From CREATE to COMMIT: learn the full database workflow with hands-on training at Learn-X Academy Global. CALL / WHATSAPP US 8778541617 www.learnxacademyglobal.com JOIN THE BATCH NOW Learn-X Academy Global | SQL Study Material | 8 / 10 www.learnxacademyglobal.com 09 Interview Quick Hits answer these and you are already ahead. TOP SQL INTERVIEW QUESTIONS Question Short answer WHERE vs HAVING WHERE filters rows before grouping. HAVING filters groups after grouping. DELETE vs TRUNCATE vs DROP DELETE removes chosen rows. TRUNCATE empties the table fast. DROP removes the table itself. UNION vs UNION ALL UNION removes duplicates. UNION ALL keeps everything and is faster. Primary key vs Foreign key PK uniquely identifies a row (no NULL). FK points to a PK in another table. RANK vs DENSE_RANK RANK skips numbers after a tie (1,1,3). DENSE_RANK does not (1,1,2). INNER vs LEFT JOIN INNER keeps only matching rows. LEFT keeps all rows from the left table. How does SQL treat NULL? NULL = unknown. NULL = NULL is not true, so use IS NULL. COUNT(col) ignores NULLs. What is normalization? Organizing data into related tables to cut duplication (1NF, 2NF, 3NF). What is an index? A lookup structure that speeds up searches but slows writes a little. CLASSIC QUERIES THEY LOVE TO ASK classics_1.sql -- 2nd highest salary SELECT MAX(salary) FROM employees WHERE salary < ( SELECT MAX(salary) FROM employees); -- duplicate emails SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1; classics_2.sql -- customers who never ordered SELECT c.name FROM customers c LEFT JOIN orders o ON c.id = o.customer_id WHERE o.id IS NULL ; -- Nth highest salary (N = 3) SELECT salary FROM ( SELECT salary, DENSE_RANK() OVER ( ORDER BY salary DESC ) r FROM employees) t WHERE r = 3; COMMON MISTAKES Forgetting WHERE UPDATE / DELETE hits the whole table. SELECT * everywhere Slow and messy. Pick only the columns you need. = NULL Use IS NULL. The = check never matches NULL. LEARN-X ACADEMY GLOBAL Interview in 3... 2... 1... Prepare with us: SQL practice, mock questions and real-world scenarios. Do not wait for the next opening, join now. CALL / WHATSAPP US 8778541617 www.learnxacademyglobal.com JOIN THE BATCH NOW Learn-X Academy Global | SQL Study Material | 9 / 10 www.learnxacademyglobal.com 10 Practice Lab reading is not enough. open your SQL editor and try these. SAMPLE TABLE: employees id name dept salary city hire_date 1 Arun IT 65000 Chennai 2022-03-14 2 Meena HR 48000 Madurai 2021-07-01 3 Karthik IT 72000 Chennai 2020-11-23 4 Divya Sales 52000 Coimbatore 2023-01-09 5 Ajay Sales 52000 Chennai 2022-09-30 EASY 1. List all employees from Chennai. 2. Show names starting with 'A', highest salary first. 3. Count how many employees are in each dept. MEDIUM 4. Find depts whose average salary is above 50000. 5. Show employees earning more than the company average. 6. Join employees with a departments table to show dept_name. HARD 7. Top 2 salaries in each dept (use DENSE_RANK). 8. Running total of salary ordered by hire_date. 9. Find the 3rd highest salary without using LIMIT. HOW TO LEVEL UP (7 day plan) D1 SELECT D2 Filter D3 GROUP BY D4 JOINs D5 Functions D6 Window D7 Mock Qs Want the answers + a mentor-style walkthrough? Bring your solutions to Learn-X Academy Global. Our SQL course takes you from zero to confident with guided practice, real examples and interview prep. LEARN-X ACADEMY GLOBAL SQL is the skill. Learn-X is the shortcut. Join Learn-X Academy Global today and start your data career with a hands-on SQL course. Beginner friendly Hands-on practice Interview prep CALL / WHATSAPP US 8778541617 www.learnxacademyglobal.com JOIN THE BATCH NOW Learn-X Academy Global | SQL Study Material | 10 / 10 www.learnxacademyglobal.com