SQL Complete Guide
SQL Complete Guide
01 Introduction to SQL
What is SQL?
SQL (Structured Query Language) is a standard programming language used to store, manipulate, and
retrieve data from relational databases. It was developed by IBM in the 1970s and has become the
backbone of virtually all database systems.
💡 SQL is NOT case-sensitive. SELECT = select = Select. However, writing SQL keywords in
UPPERCASE is the widely followed convention.
employees
emp_id name dept_id salary hire_date manager_id
101 Arjun 10 55000 2020-03-15 NULL
Sharma
Page 1 of 28
SQL Complete Guide | Interview & Placement Preparation
departments
dept_id dept_name location
10 Engineering Hyderabad
20 Marketing Mumbai
30 HR Bangalore
40 Finance Delhi
projects
proj_id proj_name emp_id budget
P001 Website Revamp 101 150000
P002 SEO Campaign 102 80000
P003 Mobile App 103 200000
P004 HR Portal 104 60000
P005 Data Pipeline 105 300000
Page 2 of 28
SQL Complete Guide | Interview & Placement Preparation
CREATE TABLE
Used to create a new table in the database.
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
dept_id INT,
salary DECIMAL(10, 2),
hire_date DATE,
manager_id INT
);
Constraints
Constraints enforce rules on table columns.
Page 3 of 28
SQL Complete Guide | Interview & Placement Preparation
ALTER TABLE
Modify the structure of an existing table.
-- Add a new column
ALTER TABLE employees ADD COLUMN email VARCHAR(150);
-- Rename a column
ALTER TABLE employees RENAME COLUMN email TO work_email;
-- Drop a column
ALTER TABLE employees DROP COLUMN work_email;
Page 4 of 28
SQL Complete Guide | Interview & Placement Preparation
💡 Always use WHERE in UPDATE. Without it, EVERY row gets updated — a very common interview
gotcha!
Page 5 of 28
SQL Complete Guide | Interview & Placement Preparation
Basic SELECT
-- Select all columns
SELECT * FROM employees;
-- NOT condition
SELECT * FROM employees WHERE NOT dept_id = 30;
Comparison Operators
Operator Meaning Example
= Equal to WHERE salary = 55000
!= or <> Not equal to WHERE dept_id != 30
> Greater than WHERE salary > 60000
< Less than WHERE salary < 50000
>= Greater than or equal WHERE salary >= 55000
<= Less than or equal WHERE salary <= 72000
Page 6 of 28
SQL Complete Guide | Interview & Placement Preparation
💡 LIKE wildcards: % means any number of characters. _ means exactly one character.
-- SQL Server
SELECT TOP 5 * FROM employees ORDER BY salary DESC;
Page 7 of 28
SQL Complete Guide | Interview & Placement Preparation
Aggregate Functions
Function Description Example
COUNT(*) Total rows SELECT COUNT(*) FROM
employees
COUNT(col) Rows where col is not SELECT COUNT(manager_id)
NULL FROM employees
SUM(col) Total of numeric column SELECT SUM(salary) FROM
employees
AVG(col) Average of numeric SELECT AVG(salary) FROM
column employees
MAX(col) Highest value SELECT MAX(salary) FROM
employees
MIN(col) Lowest value SELECT MIN(salary) FROM
employees
Page 8 of 28
SQL Complete Guide | Interview & Placement Preparation
WHERE HAVING
Filters rows BEFORE grouping Filters groups AFTER grouping
Cannot use aggregate functions Can use aggregate functions
e.g. WHERE salary > 50000 e.g. HAVING AVG(salary) > 60000
Page 9 of 28
SQL Complete Guide | Interview & Placement Preparation
Joins combine rows from two or more tables based on a related column. Mastering JOINs is the single
most important SQL skill for interviews.
💡 Employees with dept_id = 40 (Finance) would NOT appear — dept 40 has no employees.
Employees with NULL dept_id also won't appear.
Page 10 of 28
SQL Complete Guide | Interview & Placement Preparation
FROM employees e
FULL OUTER JOIN departments d ON e.dept_id = d.dept_id;
Page 11 of 28
SQL Complete Guide | Interview & Placement Preparation
Page 12 of 28
SQL Complete Guide | Interview & Placement Preparation
A subquery is a SELECT statement inside another SELECT, INSERT, UPDATE, or DELETE. They are
extremely common in interviews.
Subquery in WHERE
-- Find employees who earn more than the average salary
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
Subquery with IN
-- Employees who have at least one project
SELECT name FROM employees
WHERE emp_id IN (SELECT emp_id FROM projects);
Correlated Subquery
A correlated subquery references the outer query. It runs once per row in the outer query.
-- Employees who earn more than their department's average salary
SELECT name, salary, dept_id
FROM employees e
WHERE salary > (
SELECT AVG(salary)
Page 13 of 28
SQL Complete Guide | Interview & Placement Preparation
FROM employees
WHERE dept_id = e.dept_id -- refers to outer query
);
💡 EXISTS is often faster than IN for large tables because it stops searching as soon as one match is
found.
Page 14 of 28
SQL Complete Guide | Interview & Placement Preparation
String Functions
Function Description Example Result
UPPER(s) Converts to UPPER('arjun') ARJUN
uppercase
LOWER(s) Converts to LOWER('RAVI') ravi
lowercase
LENGTH(s) Number of characters LENGTH('Priya') 5
TRIM(s) Remove TRIM(' hello ') hello
leading/trailing
spaces
LTRIM(s) Remove leading LTRIM(' hi') hi
spaces
RTRIM(s) Remove trailing RTRIM('hi ') hi
spaces
SUBSTRING(s,p,n) Extract part of string SUBSTRING('Arjun',1,3) Arj
CONCAT(s1,s2) Join strings together CONCAT('SQL',' Guide') SQL
Guide
REPLACE(s,f,r) Replace part of string REPLACE('SQL SQL 2025
2024','2024','2025')
INSTR(s,sub) Position of substring INSTR('Hello','ll') 3
LPAD(s,n,p) Pad left to length n LPAD('5',3,'0') 005
RPAD(s,n,p) Pad right to length n RPAD('5',3,'0') 500
-- Practical examples
SELECT UPPER(name), LENGTH(name) FROM employees;
SELECT CONCAT(name, ' (Dept: ', dept_id, ')') AS label FROM employees;
SELECT name, SUBSTRING(name, 1, INSTR(name,' ')-1) AS first_name FROM
employees;
Numeric Functions
Function Description Example Result
ROUND(n,d) Round to d decimal ROUND(55678.567, 2) 55678.57
places
CEIL(n) Round up to nearest CEIL(55.2) 56
integer
FLOOR(n) Round down to FLOOR(55.9) 55
nearest integer
Page 15 of 28
SQL Complete Guide | Interview & Placement Preparation
Date Functions
Function Description Example
NOW() Current date and SELECT NOW()
time
CURDATE() Current date only SELECT CURDATE()
YEAR(d) Extract year YEAR(hire_date)
MONTH(d) Extract month (1– MONTH(hire_date)
12)
DAY(d) Extract day of DAY(hire_date)
month
DATEDIFF(d1,d2) Days between two DATEDIFF(NOW(), hire_date)
dates
DATE_ADD(d,INTERVAL) Add time to a date DATE_ADD(hire_date,
INTERVAL 1 YEAR)
DATE_FORMAT(d,fmt) Format a date as DATE_FORMAT(hire_date,'%d-
string %m-%Y')
Page 16 of 28
SQL Complete Guide | Interview & Placement Preparation
Window functions perform calculations across a set of rows related to the current row — without
collapsing rows like GROUP BY does. They are very popular in mid-to-senior level interviews.
Example (scores
Function Ties Handling
100,100,90)
ROW_NUMBER() No ties — unique sequential 1, 2, 3
number
RANK() Ties get same rank; next rank 1, 1, 3
skips
DENSE_RANK() Ties get same rank; next rank is 1, 1, 2
consecutive
Page 17 of 28
SQL Complete Guide | Interview & Placement Preparation
Page 18 of 28
SQL Complete Guide | Interview & Placement Preparation
💡 Both SELECT statements in a UNION must have the same number of columns with compatible
data types.
Page 19 of 28
SQL Complete Guide | Interview & Placement Preparation
-- Multiple CTEs
WITH
dept_avg AS (
SELECT dept_id, AVG(salary) AS avg_sal FROM employees GROUP BY dept_id
),
above_avg AS (
SELECT [Link], [Link], e.dept_id
FROM employees e
JOIN dept_avg da ON e.dept_id = da.dept_id
WHERE [Link] > da.avg_sal
)
SELECT [Link], d.dept_name, [Link]
FROM above_avg a
JOIN departments d ON a.dept_id = d.dept_id;
UNION ALL
Page 20 of 28
SQL Complete Guide | Interview & Placement Preparation
-- Drop a view
DROP VIEW emp_dept_view;
Page 21 of 28
SQL Complete Guide | Interview & Placement Preparation
-- Unique index
CREATE UNIQUE INDEX idx_emp_name ON employees(name);
-- Drop an index
DROP INDEX idx_salary ON employees;
💡 Indexes speed up SELECT but slow down INSERT/UPDATE/DELETE. Use them on columns
frequently used in WHERE, JOIN, and ORDER BY clauses.
Page 22 of 28
SQL Complete Guide | Interview & Placement Preparation
These are the most frequently asked SQL questions across companies like TCS, Infosys, Wipro,
Amazon, Flipkart, and startups.
Page 23 of 28
SQL Complete Guide | Interview & Placement Preparation
Page 24 of 28
SQL Complete Guide | Interview & Placement Preparation
Page 25 of 28
SQL Complete Guide | Interview & Placement Preparation
Transactions (TCL)
A transaction is a group of SQL operations that execute as a single unit. Either all succeed, or none do
(ACID principle).
START TRANSACTION;
-- If everything is correct:
COMMIT;
Keys in SQL
Key Type Description Example
Primary Key Uniquely identifies each row; emp_id in employees
NOT NULL + UNIQUE
Foreign Key Links to Primary Key in another dept_id references
table departments
Candidate Key Columns that could be a primary emp_id, email (both
key unique)
Composite Key Primary key made of 2+ columns student_id + subject_id
Unique Key Ensures column values are email VARCHAR
unique; can be NULL UNIQUE
Super Key Any set of columns that uniquely emp_id, or emp_id+name
identifies a row
Page 26 of 28
SQL Complete Guide | Interview & Placement Preparation
Normal
Rule Fixes
Form
1NF No repeating groups; each cell has Stores multiple values in
atomic value one column
2NF Must be 1NF + No partial Attributes depending on
dependency on PK part of composite PK
3NF Must be 2NF + No transitive Column A → B → C
dependencies (should be A → C directly)
BCNF Stricter 3NF; every determinant Overlapping candidate
must be a candidate key keys
Page 27 of 28
SQL Complete Guide | Interview & Placement Preparation
-- CREATE TABLE
CREATE TABLE table_name (col1 datatype constraints, col2 datatype ...);
-- Common patterns
SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM
employees); -- 2nd max
SELECT * FROM employees WHERE salary BETWEEN 50000 AND 80000;
SELECT dept_id, COUNT(*) FROM employees GROUP BY dept_id HAVING COUNT(*) > 2;
SELECT name FROM employees WHERE emp_id NOT IN (SELECT emp_id FROM projects);
-- Window functions
RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC)
LAG(salary, 1) OVER (ORDER BY hire_date)
SUM(salary) OVER (PARTITION BY dept_id)
-- CTE
WITH cte_name AS (SELECT ...) SELECT * FROM cte_name;
Page 28 of 28