Interview SQL Notes
Interview SQL Notes
Data Knowledge
SQL
1. What is SQL?
SQL (Structured Query Language) is a standard programming language used to
interact with databases. It is used to create, read, update, and delete (CRUD
operations) data in a database. SQL allows users to query and manipulate structured
data stored in tables.
2. What is a Database?
A database is an organized collection of data that can be easily accessed, managed,
and updated. Think of it as an electronic filing system where data is stored in tables
consisting of rows and columns.
Example of a Database:
A school database stores data about students, teachers, and classes in separate
tables.
3. What is RDBMS?
A Relational Database Management System (RDBMS) is software used to manage
and operate relational databases. In an RDBMS, data is stored in tables with
relationships between them. It ensures data integrity and supports SQL for database
operations.
Popular RDBMS software includes MySQL, PostgreSQL, SQL Server, and Oracle
Database.
1 Alice HR 50,000
2 Bob IT 70,000
Smaller range
SMALLINT 1000
integer.
Fixed-point number
DECIMAL(p, s) with precision p and 12345.67
scale s.
Approximate
FLOAT floating-point 3.14159
number.
Smaller floating-
REAL 2.71
point number.
Fixed-length string
String (Character) CHAR(n) 'Hello'
of size n.
Variable-length
VARCHAR(n) string with a max 'World'
size n.
Large variable-
TEXT 'Lorem Ipsum...'
length string.
Similar to
DATETIME, often '2024-12-10
TIMESTAMP
includes time zone 14:30:00'
info.
Stores year as a 4-
YEAR 2024
digit number.
Fixed-length binary
Binary BINARY(n) 101010
data of size n.
Variable-length
VARBINARY(n) binary data of max 1010101
size n.
Stores TRUE or
Other BOOLEAN TRUE
FALSE.
Stores JSON-
JSON '{"key":"value"}'
formatted data.
Case Insensitivity
• SQL commands are case-insensitive, meaning you can write keywords in
uppercase or lowercase.
SELECT * FROM Employees;
select * from employees;
Semicolon at the End of a Query:
Semicolon (;) is used to terminate SQL statements.
SELECT * FROM Employees;
Supports Multiple Queries:
You can run multiple SQL queries at once by separating them with
semicolons (;)
INSERT INTO Employees (EmployeeID, Name) VALUES (1, 'Alice');
INSERT INTO Employees (EmployeeID, Name) VALUES (2, 'Bob');
Syntax:
Example:
Ex.
INSERT INTO NewEmployees
SELECT * FROM Employees;
9. Subset of SQL:
SQL is divided into various subsets based on its functionality. Each subset is
designed for specific types of tasks within a database. Here's an overview of the key
subsets of SQL:
1. Filter by Equality
Subtracts
the right
SELECT 10 - 4; →
- value from
6
the left
value
Multiplies SELECT 2 * 3; →
*
two values 6
Divides the
left value by SELECT 10 / 2; →
/
the right 5
value
Returns the
remainder SELECT 10 % 3;
%
of a division →1
(modulus)
SELECT * FROM
Comparison Employees
= Equal to WHERE Salary =
Operators
50000;
SELECT * FROM
Employees
<> or != Not equal to WHERE Salary <>
50000;
SELECT * FROM
Greater
> Employees
than WHERE Age > 30;
SELECT * FROM
< Less than Employees
WHERE Age < 30;
SELECT * FROM
Greater
Employees
>= than or WHERE Age >=
equal to 30;
SELECT * FROM
Less than or Employees
<=
equal to WHERE Age <=
30;
Combines
conditions, SELECT * FROM
Employees
returns true
Logical Operators AND WHERE Age > 30
if all AND IsActive =
conditions TRUE;
are true
Combines
conditions, SELECT * FROM
returns true Employees
OR if at least WHERE Age > 30
one OR Salary >
condition is 50000;
true
SELECT * FROM
Negates a Employees
NOT
condition WHERE NOT
IsActive = TRUE;
` ` Bitwise OR
Bitwise SELECT 5 ^ 3; →
^
XOR 6
SELECT * FROM
Checks if a Employees
Set Operators IN value exists WHERE
in a list Department IN
('HR', 'Finance');
SELECT * FROM
Checks if a Employees
value does WHERE
NOT IN
not exist in Department NOT
a list IN ('HR',
'Finance');
SELECT * FROM
Employees
Checks for WHERE Name
Pattern Matching LIKE a pattern in LIKE 'A%'; →
a string Names starting
with 'A'
SELECT * FROM
Checks if a
Employees
IS NOT NULL value is not WHERE Address
NULL IS NOT NULL;
SELECT * FROM
Checks if a Employees
value is WHERE Salary
NOT BETWEEN
outside a NOT BETWEEN
range 30000 AND
60000;
12. Update:
The UPDATE statement in SQL is used to modify existing records in a table. It allows
you to update one or more columns in one or multiple rows based on specified
conditions.
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Key Points
1. Conditional Update: Use the WHERE clause to specify the rows to be updated.
2. Update All Rows: Without the WHERE clause, the UPDATE statement modifies all
rows in the table.
3. Data Types: Ensure the new values match the data type of the columns.
UPDATE Employees
SET Salary = 60000
WHERE EmployeeID = 1;
13. Delete
The DELETE statement is used to remove specific rows from a table while keeping
the table structure intact.
DELETE FROM table_name
WHERE condition;
Key Points
1. Deletes specific rows based on the condition in the WHERE clause.
2. If no WHERE clause is used, all rows in the table are deleted, but the table structure
remains.
3. It can be rolled back if used within a transaction.
4. Slower compared to TRUNCATE as it logs each row deletion.
14. Drop:
The DROP statement is used to completely remove a database object (like a table,
view, or database) from the database.
Key Points
1. Completely removes the table, including its structure and data.
2. Cannot be rolled back once executed.
3. Faster than DELETE as it doesn’t log individual row deletions.
4. Use with caution, as the table is permanently removed.
Drop a Table:
DROP TABLE Employees;
Drop a Database:
DROP DATABASE CompanyDB;
15. TRUNCATE:
The TRUNCATE statement removes all rows from a table but retains the table
structure for future use.
TRUNCATE TABLE table_name;
Key Points
1. Removes all rows from the table.
Keeps
Table Yes No Yes
Structure
Transaction
Yes No No (in most databases)
Rollback
Resets
Auto- No - Yes
Increment
Slower (logs
Speed individual row Fast Faster than DELETE
deletions)
the ALTER statement is used to modify an existing database object, such as a table,
view, stored procedure, or column. The ALTER statement allows you to make
changes without having to drop and recreate the object.
1. Add a Column:
ALTER TABLE table_name
ADD column_name datatype [constraint];
2. Modify a Column:
ALTER TABLE table_name
ALTER COLUMN column_name datatype;
3. Drop a Column:
ALTER TABLE table_name
DROP COLUMN column_name;
18. GROUP BY
The GROUP BY clause in SQL is used to group rows that have the same values in
specified columns into summary rows, like "total sales per region" or "number of
employees in each department." It is commonly used with aggregate functions like
COUNT, SUM, AVG, MAX, or MIN to perform operations on each group.
HAVING:
The HAVING clause is used to filter groups created by the GROUP BY clause. Unlike
the WHERE clause, which filters individual rows before grouping, HAVING filters
aggregated data after the grouping has been performed.
FROM table_name
GROUP BY column1
HAVING aggregate_function(column2) condition;
IMP
find duplicate records in a table
19. Join
JOIN is used to combine data from two or more tables based on a related column
between them. It allows you to retrieve data from multiple tables in a relational database
by specifying a condition that links them.
Types of Joins:
1. INNER JOIN
Combines rows from two tables where the condition matches. Rows that do not meet
the condition are excluded.
SELECT columns
FROM table1
INNER JOIN table2
ON table1.common_column = table2.common_column;
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.common_column = table2.common_column;
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.common_column = table2.common_column;
5. CROSS JOIN
Produces a Cartesian product by combining every row from the first table with every
row in the second table.
SELECT columns
FROM table1
CROSS JOIN table2;
6. SELF JOIN
A table is joined with itself. Useful for hierarchical or relational data.
Alias in SQL is a temporary name that you give to a column or table to make your
query easier to read or understand.
Distinct in SQL is used to remove duplicate values from the result of a SELECT
query. It returns only unique values.
Example: SELECT DISTINCT city FROM students;
SELECT column_name,
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE default_result
END AS alias_name
FROM table_name;
1 Ravi 85
2 Sneha 42
3 Aman 75
4 Pooja 30
Ravi 85 Distinction
Sneha 42 Fail
Aman 75 Distinction
Pooja 30 Fail
➢ CASE is used when you want to return different values based on conditions.
➢ It can be used in SELECT, WHERE, ORDER BY, or even inside aggregates.
OLAP is a system designed for analyzing large volumes of historical data to help in
decision-making and business intelligence.
It is optimized for complex queries, reporting, and data analysis, not for frequent updates.
Example: A company manager uses OLAP to view a monthly sales report by region or
product category.
Type of
Real-time, current data Historical, aggregated data
Data
Real-life Example:
• OLTP: You buy a shirt from an online store — that transaction (adding order,
updating stock) is handled by OLTP.
• OLAP: The company’s manager wants to see monthly sales trends — that analysis
is handled by OLAP.
➢ Basic Syntax:
SELECT column1
FROM table1
WHERE column2 = (
SELECT column2
FROM table2
WHERE condition
);
Example: Find employees who earn more than the average salary
Assume a table employees
1 Ravi 30000
2 Sneha 45000
3 Aman 55000
4 Pooja 25000
This query:
Types of Subqueries:
Type Description
1 UNION
2 UNION ALL
Combines all rows from both queries, including duplicates.
3 INTERSECT
Returns only common rows present in both result sets.
Returns
Removes Shows Returns
Operator Description Only
Duplicates Duplicates Difference
Common
Combines and
UNION removes Yes No No No
duplicates
Combines and
UNION ALL keeps No Yes No No
duplicates
Returns only
INTERSECT Yes No Yes No
common rows
Returns rows
EXCEPT from 1st query Yes No No Yes
not in 2nd
It’s like a function in programming — you write it once, and call it many
times.
Syntax:
AS
BEGIN
-- SQL statements
END;
Let’s create a stored procedure that returns all employees in the "Sales"
department:
AS
BEGIN
END;
EXEC GetSalesEmployees;
@DeptName VARCHAR(50)
AS
BEGIN
END;
Call it like:
• Generate reports
• Perform batch updates
• Encapsulate complex business logic
• Maintain data integrity
A Window Function performs a calculation across a set of table rows that are
related to the current row, without collapsing rows like GROUP BY does.
It lets you add extra info (like running totals, ranks, averages) while keeping
all original rows.
Syntax:
[PARTITION BY col1]
[ORDER BY col2]
1.ROW_NUMBER() Example
FROM Employees;
FROM Employees;
FROM Employees;
4. What is DENSE_RANK()
Syntax:
FROM Employees;
Think of a view as a saved SQL SELECT query that you can treat like a
table.
FROM table_name
WHERE condition;
FROM Employees
To Update a View:
FROM Employees
To Drop a View:
It’s used in database design to plan and understand the structure before
building the database.
Component Description
Entity A table in the database (e.g., Customer, Order)
Attribute A column in a table (e.g., CustomerID, Name)
Primary Key A unique identifier for each row in a table
A key in one table that links to a primary key in another
Foreign Key
table
Component Description
The connection between tables (one-to-one, one-to-
Relationship
many, many-to-many)
Component Description
Central table that stores quantitative data
Fact Table
(e.g., sales, profit)
Dimension Surrounding tables that store descriptive
Table attributes (e.g., product, time, region)
Quantit TotalA
SaleID ProductID CustomerID DateID
y mount
Dimension Tables:
1. ProductDim
| ProductID | ProductName | Category | Price |
2. CustomerDim
| CustomerID | Name | Region |
3. DateDim
| DateID | Date | Month | Year |
A CTE (Common Table Expression) is a temporary result set that you can
reference within a SELECT, INSERT, UPDATE, or DELETE statement.
Syntax:
WITH CTE_Name AS (
FROM TableName
WHERE condition
Example
WITH HighSalary AS (
FROM Employees
Output:
Name Salary
Pooja 40000
Sneha 45000
WITH RankedEmployees AS (
FROM Employees
FROM RankedEmployees
WHERE SalaryRank = 1;
Output:
SELECT *
FROM Employees
SELECT *
FROM Employees
SELECT EmployeeName,
ISNULL(ManagerID, 0) AS ManagerID
FROM Employees;
SELECT EmployeeName,
FROM Employees;
FROM Sales;
SELECT EmployeeName,
CASE
END AS ManagerInfo
FROM Employees;
FROM Employees;
--------------------------------------------------
--------------------------------------------------
-- Bad
-- Good
FROM Employees;
--------------------------------------------------
-- 2. Create Indexes
--------------------------------------------------
ON Employees (ManagerID);
--------------------------------------------------
--------------------------------------------------
--------------------------------------------------
-- 4. EXISTS Instead of IN
--------------------------------------------------
-- Bad
-- Good
WHERE EXISTS (
);
--------------------------------------------------
--------------------------------------------------
SELECT EmployeeName
--------------------------------------------------
--------------------------------------------------
-- Bad
SELECT [Link],
(SELECT [Link]
FROM Departments d
FROM Employees e;
-- Good
FROM Employees e
--------------------------------------------------
--------------------------------------------------
AS
BEGIN
FROM Employees;
END;
--------------------------------------------------
-- 8. Execution Plan
--------------------------------------------------
--------------------------------------------------
--------------------------------------------------
;WITH EmployeeCTE AS (
FROM Employees
SELECT *
FROM EmployeeCTE
--------------------------------------------------
--------------------------------------------------
Feature /
JOIN Subquery
Aspect
A query inside another
Combines rows from two
query, used to fetch
Definition or more tables based on
results for the main
a related column.
query.
Retrieves data from
Retrieves data from
Data one table and uses it
multiple tables in a single
Combination as input for another
result set.
query.
Usually faster (especially Sometimes slower,
with proper indexing) especially correlated
Performance
because SQL Server can subqueries (executed
optimize joins well. row by row).
Easier to read when Easier when you just
Readability combining multiple need to filter with one
related tables. extra condition.
Best for filtering,
Best for showing related
checking existence, or
data side by side (e.g.,
Use Case calculations (e.g.,
Employees with
salaries greater than
Department names).
average).
Feature /
JOIN Subquery
Aspect
Can be independent
Performed in a single
(non-correlated) or run
Execution execution plan (set-
multiple times
based).
(correlated).
sql SELECT
sql SELECT EmployeeName
[Link], FROM Employees
[Link] WHERE DeptID IN
Example
FROM Employees e (SELECT DeptID
JOIN Departments d ON FROM Departments
[Link] = [Link]; WHERE Location =
'NY');
INNER JOIN, LEFT Scalar subquery,
Types JOIN, RIGHT JOIN, correlated subquery,
FULL JOIN. nested subquery.
--------------------------------------------------
-- Sample Table
--------------------------------------------------
CREATE TABLE Employees (
EmpID INT,
EmpName VARCHAR(50),
Salary INT
);
--------------------------------------------------
-- 1. TOP with ORDER BY
--------------------------------------------------
SELECT TOP 1 Salary
FROM (
SELECT DISTINCT TOP 2 Salary
FROM Employees
ORDER BY Salary DESC
) AS Temp
ORDER BY Salary ASC;
--------------------------------------------------
--------------------------------------------------
-- 3. ROW_NUMBER()
--------------------------------------------------
;WITH SalaryRank AS (
SELECT Salary,
ROW_NUMBER() OVER (ORDER BY Salary DESC) AS rn
FROM (SELECT DISTINCT Salary FROM Employees) AS s
)
SELECT Salary
FROM SalaryRank
WHERE rn = 2;
--------------------------------------------------
-- 4. RANK()
--------------------------------------------------
;WITH SalaryRank AS (
SELECT Salary,
RANK() OVER (ORDER BY Salary DESC) AS rnk
FROM Employees
)
SELECT DISTINCT Salary
FROM SalaryRank
WHERE rnk = 2;
--------------------------------------------------
-- 5. OFFSET FETCH (SQL Server 2012+)
--------------------------------------------------
-- Get 2nd highest salary
SELECT DISTINCT Salary
FROM Employees
ORDER BY Salary DESC
OFFSET 1 ROW FETCH NEXT 1 ROW ONLY;
--------------------------------------------------
-- Sample Table
--------------------------------------------------
CREATE TABLE Employees (
EmpID INT,
EmpName VARCHAR(50),
Salary INT
);
--------------------------------------------------
-- 1. TOP N Salaries (Without Duplicates)
--------------------------------------------------
-- Example: Top 3 distinct salaries
--------------------------------------------------
-- 2. ROW_NUMBER() Method
--------------------------------------------------
-- Example: Top 3 salaries
;WITH SalaryRank AS (
SELECT Salary,
ROW_NUMBER() OVER (ORDER BY Salary DESC) AS rn
FROM (SELECT DISTINCT Salary FROM Employees) AS s
)
SELECT Salary
FROM SalaryRank
WHERE rn <= 3;
--------------------------------------------------
-- 3. RANK() Method (Handles ties)
--------------------------------------------------
;WITH SalaryRank AS (
SELECT Salary,
RANK() OVER (ORDER BY Salary DESC) AS rnk
FROM Employees
)
SELECT DISTINCT Salary
FROM SalaryRank
WHERE rnk <= 3;
--------------------------------------------------
-- 4. OFFSET FETCH (SQL Server 2012+)
--------------------------------------------------
-- Get Top N salaries with skip
-- Example: Skip 0 (start from highest), fetch 3 salaries
SELECT DISTINCT Salary
FROM Employees
ORDER BY Salary DESC
OFFSET 0 ROWS FETCH NEXT 3 ROWS ONLY;