0% found this document useful (0 votes)
3 views

SQL - DAK

The document outlines a comprehensive SQL learning guide, structured into beginner, intermediate, and advanced levels. It covers core concepts such as database types, CRUD operations, SQL structure, and various types of joins, aggregations, and subqueries. Additionally, it delves into advanced topics like data modeling, performance tuning, and advanced SQL functions.

Uploaded by

Aarti Soni
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

SQL - DAK

The document outlines a comprehensive SQL learning guide, structured into beginner, intermediate, and advanced levels. It covers core concepts such as database types, CRUD operations, SQL structure, and various types of joins, aggregations, and subqueries. Additionally, it delves into advanced topics like data modeling, performance tuning, and advanced SQL functions.

Uploaded by

Aarti Soni
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

SQL Learners

Contents :
Beginner
Core Concepts:
Database Types: Relational vs. non-relational, ACID properties
Schemas and Constraints: Primary and foreign keys, unique constraints
SQL Structure: Basic syntax and query structure, comments
CRUD Operations:
SELECT Statements: Syntax, selecting columns, renaming with AS
INSERT, UPDATE, DELETE: Syntax, examples, best practices for data integrity
Data Types: Integer, float, varchar, text, date, boolean, etc.
Filtering & Sorting:
WHERE and ORDER BY clauses, DISTINCT keyword for unique records
Intermediate
Joins and Unions:
Types of Joins: Inner, left, right, full joins with examples
Self-Joins and Cross Joins: Usage and common use cases
UNION and INTERSECT: Combining query results
Aggregations and Grouping:
Aggregate Functions: SUM, COUNT, AVG, MIN, MAX
GROUP BY and HAVING: Grouping data with filters on aggregations
Subqueries and Nested Queries:
Inline Views: Using subqueries in the FROM clause
Correlated Subqueries: Syntax, examples, and performance tips
Window Functions:
Ranking Functions: ROW_NUMBER, RANK, DENSE_RANK, NTILE
PARTITION BY: Comparison with GROUP BY, partitioning data
Advanced
Data Modeling and Schema Design:
Normalization: 1NF, 2NF, 3NF, BCNF, denormalization strategies
ERD (Entity-Relationship Diagrams): Identifying relationships, building ERDs
Advanced SQL Functions:
String Functions: CHARINDEX, SUBSTRING, TRIM, REPLACE
Date Functions: DATEDIFF, DATEADD, date formatting techniques
Mathematical Functions: ROUND, CEIL, FLOOR, MOD
Performance Tuning:
Indexing Strategies: Clustered vs. non-clustered, composite indexes
Query Execution Plans: Analyzing and optimizing queries
Stored Procedures & Triggers: Benefits, syntax, examples
Transactions and Concurrency: Locking, isolation levels, data integrity

1
SQL Learners

Beginner:
Core Concepts
Database Types: Relational vs. non-relational, ACID properties
Imagine a dabba-wala system in Mumbai. Every day, hundreds of lunch boxes (data) are
sent from homes to offices. Each box has an address (identifier) and contains specific items
like chapati, sabzi, and daal (attributes). In a Relational Database, data is organized in
tables with defined relationships, just like a perfectly mapped delivery system where each
lunch box is carefully connected to a particular person. Non-relational databases, on the
other hand, are like having random boxes of food with no specific structure, perhaps useful
when you don’t need predefined relationships between data.

“Jab data mein sambandh banane ki baat aaye, toh relational database sabse accha hai!”

ACID Properties: ACID (Atomicity, Consistency, Isolation, Durability) ensures data


reliability. Think of it like the four principles of a stable friendship:
Atomicity: “Either the whole task is done or nothing happens.”
Consistency: “Rules are always followed.”
Isolation: “Tasks don’t interfere with each other.”
Durability: “Once done, it stays done!”

Schemas and Constraints: Primary and foreign keys, unique constraints


Think of a school where each student has a unique ID card (primary key). This ID helps
teachers, librarians, and others identify each student. If another database (say, library
records) uses this student ID to link the borrowed books, that’s the concept of a Foreign
Key. Constraints, like uniqueness, ensure that no two students have the same ID.

“Yeh primary key wahi hai jo data ko pehchaan deti hai aur constraints rules set karte hain.”

Example: In an employee table, the EmployeeID can be a primary key. If another table
records project assignments, it can reference EmployeeID as a foreign key, allowing the
company to trace project assignments back to specific employees.

2
SQL Learners

Beginner:
Core Concepts
SQL Structure: Basic syntax and query structure, comments
Think of SQL syntax as the way we structure our sentences when giving directions. Just as
you’d say “Please go straight, turn right, and you’ll find the café,” SQL has a structure to
fetch, insert, and manipulate data.
SQL statements have three main parts:
SELECT: To specify the data to be retrieved.
FROM: To specify the source table.
WHERE: To filter the data based on conditions.

“SQL mein baat yeh hai ki agar syntax sahi hai, toh data aapke saamne hai.”

Example:
1. To retrieve all employees who are managers:
SELECT EmployeeName FROM Employees WHERE Position = 'Manager';
2. Retrieve names and ages from the 'users' table
SELECT name, age FROM users WHERE age > 18; -- Only include users older than 18
3. Get all product names and prices from the 'products' table
SELECT product_name, price FROM products WHERE price < 100; -- Only include products
that cost less than $100.
4. Select order IDs and customer IDs from the 'orders' table
SELECT order_id, customer_id FROM orders WHERE status = 'shipped'; -- Filter to include
only shipped orders.
5. Fetch employee names and departments from the 'employees' table
SELECT employee_name, department FROM employees WHERE department = 'Sales'; -- Only
include employees in the Sales department
6. Get titles of books from the 'books' table
SELECT title FROM books WHERE published_year > 2000; -- Filter to include books published
after the year 2000.
7. Retrieve customer names and email addresses from the 'customers' table
SELECT name, email FROM customers WHERE email LIKE '%@example.com'; -- Include only
customers with an email from example.com

Adding comments is like adding mental notes to code, ensuring anyone reading can
understand your logic. Comments start with -- in SQL.

3
SQL Learners

Beginner:
CRUD Operations
CRUD operations are essential for interacting with databases:
Create (INSERT): Adding new records.
Read (SELECT): Viewing data.
Update: Modifying existing data.
Delete: Removing records.

Imagine CRUD as ordering food in a restaurant:


Create: You place a new order.
Read: You ask the waiter about your order’s status.
Update: You request to add extra spices.
Delete: You cancel an item.

“CRUD ke bina toh data management bilkul namumkin hai.”

Example:
1. Add a new user to the 'users' table
INSERT INTO users (name, age, email) VALUES ('Alice', 30, '[email protected]'); -- Insert
a user named Alice.
2. Retrieve all records from the 'users' table
SELECT *FROM users; -- Get all columns for all users
3. Update the email address for a specific user in the 'users' table
UPDATE users SET email = '[email protected]'WHERE name = 'Alice'; -- Change
Alice's email address.
4. Remove a user from the 'users' table
DELETE FROM users WHERE name = 'Alice'; -- Delete the user named Alice.

SELECT Statements: Syntax, Selecting Columns, Renaming with AS


SELECT is like selecting specific channels on TV. You choose only what you want to see! You can
even rename channels (columns) using the AS keyword to make it easier to understand.

“Jab data ko dekhna hai, toh SELECT statement kaam aata hai. Bas channel ya column ka naam
bata do!”

Example: If you want to view employee names as “Staff” and positions as “Role”:
SELECT EmployeeName AS Staff, Position AS Role FROM Employees;

4
SQL Learners

Beginner:
CRUD Operations
Data Types: Integer, Float, Varchar, Text, Date, Boolean
Data types ensure the data format is correct. Like each room has specific furniture, data types
ensure numbers go where numbers are needed, text where text is expected.

“Data types ke bina toh database ka structure hi nahi banega.”

Example of Data Types


1. Integer
Column Name: EmployeeAge Data Type: INT
Example Value: 30
Explanation: This column stores whole numbers representing the ages of employees. Only
integer values are allowed, ensuring that no text or decimal values can be inserted.
2. Varchar (Variable Character)
Column Name: EmployeeName Data Type: VARCHAR(50)
Example Value: 'Amit'
Explanation: This column can store variable-length strings, allowing for names of up to 50
characters. It ensures that names, which are textual data, are stored correctly.
3. Date
Column Name: HireDate Data Type: DATE
Example Value: '2024-11-01'
Explanation: This column stores dates in a specific format. Using the DATE type ensures that
only valid date values can be entered, facilitating accurate date comparisons and
calculations.
4. Decimal
Column Name: Salary Data Type: DECIMAL(10, 2)
Example Value: 75000.00
Explanation: This column is used for storing salary amounts. The DECIMAL type allows for
numbers with a fixed number of digits, ensuring that monetary values are accurate and
include two decimal places.
5. Boolean
Data Type: BOOLEAN
Example Value: TRUE
Explanation: This column indicates whether an employee is active (true) or inactive (false).
Using the BOOLEAN type ensures that only true/false values are accepted.

5
SQL Learners

Beginner:
CRUD Operations
Filter&Sorting :WHERE and ORDER BY Clauses, DISTINCT Keyword for Unique Records
WHERE: Filters data based on specific conditions, like selecting only vegetarian items on a menu.
ORDER BY: Sorts the results, like arranging a list of names alphabetically.
DISTINCT: Eliminates duplicate records, like removing repeated items from a list.

“WHERE aur ORDER BY se data ko bilkul apne hisaab se dekh sakte hain.”

Examples:
1. Retrieve all products that are in stock
SELECT *FROM products WHERE stock > 0; -- Only show products with stock greater than 0
2. Get all employees in the 'HR' department
SELECT *FROM employees WHERE department = 'HR'; -- Only include employees from the HR
department
3. Retrieve all customers and sort them by their last name
SELECT *FROM customers ORDER BY last_name ASC; -- Sort customers alphabetically by last
name
4. Get all orders and sort them by order date, newest first
SELECT *FROM orders ORDER BY order_date DESC; -- Sort orders in descending order by
order date
5. Retrieve unique cities from the 'customers' table
SELECT DISTINCT city FROM customers; -- Get a list of unique city names
6. Get unique product categories from the 'products' table
SELECT DISTINCT category FROM products; -- Show all distinct product categories
7. To view unique job titles of employees in the 'IT' department, sorted alphabetically
SELECT DISTINCT job_title FROM employees WHERE department = 'IT'ORDER BY job_title; --
Sort the unique job titles alphabetically

6
SQL Learners

Intermediate :
Joins & Unions :
Joins are like the bridges that connect different tables, allowing you to pull in data from multiple
sources based on common values. Imagine each table as a different department in a company—
joining them is like setting up a meeting to see everyone’s work together.

Types of Joins: Inner, Left, Right, Full Joins


Inner Join: Retrieves only matching records between two tables, like a dosti (friendship) where
only mutual friends meet.
Example: Listing only customers who have made purchases.
Left Join: Fetches all records from the left table and matching ones from the right. It’s like inviting
all of Amit's friends to a party, even if they don’t all know Rahul.
Example: Getting all employees, including those who haven’t received any bonuses.
Right Join: Similar to Left Join but keeps all records from the right table. Imagine Rahul invites
all his friends and only Amit’s mutual friends show up.
Full Join: Retrieves all records from both tables, whether they match or not, like inviting everyone
to the party, even those who don’t know each other.

“JOIN ka magic yeh hai ki sabko saath mein milata hai, bas condition sahi lagni chahiye.”

Example:
1. To get a full list of employees with their respective departments, even if some employees are not
assigned to any department:
SELECT e.EmployeeName, d.DepartmentName
FROM Employees e
FULL JOIN Departments d
ON e.DepartmentID = d.DepartmentID;

Self Joins and Cross Joins


Self Join: Joining a table with itself, like comparing each employee’s salary with every other
employee’s salary to find who earns the most.
Cross Join: Combines all rows from two tables, forming all possible pairs (like everyone meeting
everyone else at a networking event).

“Self Join toh woh hai, jaise apne aap se baat karke apna solution nikaalna.”

Example: Using a self-join to find employees who work under the same manager.
SELECT e1.EmployeeName AS Employee, e2.EmployeeName AS Manager
FROM Employees e1
JOIN Employees e2
ON e1.ManagerID = e2.EmployeeID;
UNION and INTERSECT
UNION combines results from two queries, removing7 duplicates (like merging guest lists for two
SQL Learners

Intermediate :
Joins & Unions :
Self Joins and Cross Joins
Self Join: Joining a table with itself, like comparing each employee’s salary with every other
employee’s salary to find who earns the most.
Cross Join: Combines all rows from two tables, forming all possible pairs (like everyone meeting
everyone else at a networking event).

“Self Join toh woh hai, jaise apne aap se baat karke apna solution nikaalna.”

Example: Using a self-join to find employees who work under the same manager.
SELECT e1.EmployeeName AS Employee, e2.EmployeeName AS Manager
FROM Employees e1
JOIN Employees e2
ON e1.ManagerID = e2.EmployeeID;

UNION and INTERSECT


UNION combines results from two queries, removing duplicates (like merging guest lists for two
events).
INTERSECT returns only the common records between two queries, like finding mutual friends
between two people.
Example: Combining two departments’ employee lists:
SELECT EmployeeName FROM Marketing
UNION
SELECT EmployeeName FROM Sales;

8
SQL Learners

Intermediate :
Aggregations and Grouping:
Aggregations help us summarize data, like finding out the total sales for a month or the average age of
employees.

Aggregate Functions: SUM, COUNT, AVG, MIN, MAX


SUM: Adds up all values in a column (total expenses).
COUNT: Counts records (total customers).
AVG: Calculates the average of values (average sales per month).
MIN/MAX: Finds the smallest/largest value (highest and lowest salary).

“Jab data ka ek saath analysis chahiye, tab aggregations ka jaadu chalta hai.”

Example: Finding the average salary of employees in each department:


SELECT DepartmentID, AVG(Salary)
FROM Employees
GROUP BY DepartmentID;

GROUP BY and HAVING


GROUP BY groups data based on a specified column, like categorizing expenses by department.
HAVING filters groups based on conditions, allowing us to show only specific aggregated results.

Example: Finding departments with a total salary budget over $500,000:


SELECT DepartmentID, SUM(Salary) AS TotalSalary
FROM Employees
GROUP BY DepartmentID
HAVING SUM(Salary) > 500000;

9
SQL Learners

Intermediate :
Subqueries and Nested Queries :
Subqueries are queries within queries, often used to filter results or to pass intermediate results to the
main query.

Inline Views (Subqueries in the FROM Clause)


Imagine an inline view as a temporary table created by a subquery. For instance, you could create a
temporary list of high-paying employees and then filter results based on that.

Correlated Subqueries
In correlated subqueries, each row in the main query’s result is processed using a subquery, like
checking if an employee’s salary is higher than the department’s average.

“Subqueries woh cheez hai, jo andar hi andar apna kaam kar leti hai.”

Example: Finding employees who earn more than the average salary in their department:
SELECT EmployeeName
FROM Employees e
WHERE Salary > (SELECT AVG(Salary) FROM Employees WHERE DepartmentID =
e.DepartmentID);

10
SQL Learners

Intermediate :
Window Functions :
Window functions allow us to perform calculations across rows related to the current row, like
showing a rank for each row without collapsing the data.

Ranking Functions: ROW_NUMBER, RANK, DENSE_RANK, NTILE


ROW_NUMBER: Assigns a unique number to each row.
RANK: Assigns ranks to rows but skips numbers for ties.
DENSE_RANK: Like RANK but without gaps.
NTILE: Divides rows into N buckets (useful for quartiles).

Imagine these functions as a way to sort students based on scores:


ROW_NUMBER gives each student a unique position.
RANK places students with the same score in the same rank, leaving gaps.
DENSE_RANK fills in without gaps.
NTILE(4) divides the class into top 25%, second 25%, etc.

“ROW_NUMBER aur RANK se competition aur ranking toh banti hai, chahe score barabar ho ya
na ho.”

Example: Assigning ranks to employees based on salary:


SELECT EmployeeName, Salary,
RANK() OVER (ORDER BY Salary DESC) AS SalaryRank
FROM Employees;

PARTITION BY
PARTITION BY divides data into parts before applying window functions. It’s like creating mini-
competitions in each department for top performers.

Example: Ranking employees within each department based on salary:


SELECT EmployeeName, DepartmentID, Salary,
RANK() OVER (PARTITION BY DepartmentID ORDER BY Salary DESC) AS DepartmentRank
FROM Employees;

11
SQL Learners

Advanced:
Data Modeling and Schema Design :
Normalization: Normalization organizes data into tables to minimize redundancy and dependency.
It’s like organizing your wardrobe by grouping similar items—shirts, pants, and accessories—making
everything easy to locate. Normalization has multiple forms (1NF, 2NF, 3NF, and BCNF), each
imposing stricter data separation rules.
1NF (First Normal Form): Eliminates duplicate columns and each cell has a single value. Think
of it as keeping only one shirt per hanger.
2NF (Second Normal Form): Builds on 1NF by ensuring each non-key column depends on the
table’s primary key.
3NF (Third Normal Form): Further refines the structure by removing transitive dependencies
(columns dependent on other non-key columns).
BCNF (Boyce-Codd Normal Form): Enforces stricter rules to eliminate anomalies.

“Jaise ghar mein samaan ka ek theek thak silsila hota hai, waise hi normalization database ko
organized rakhta hai!”

Example:
In a library database, normalization helps split a single “Books” table into separate tables for
“Authors,” “Publishers,” and “Genres” to reduce redundancy.
Denormalization: Sometimes, we combine tables to improve performance, like keeping all
frequently-used clothes within reach for convenience.

ERD (Entity-Relationship Diagram): ERDs visually map relationships between data entities
(tables). Imagine an ERD as a blueprint showing how data points like customers, orders, and
products are interconnected.

Example:
In a retail database, you can design an ERD to display relationships like “Customer places Order” or
“Order contains Product.”

12
SQL Learners

Advanced:
Advanced SQL Functions :
Advanced SQL functions perform complex operations on data, making data manipulation faster and
more efficient.

String Functions
String functions help manipulate text data, like finding, extracting, or replacing characters.
CHARINDEX locates the position of a substring.
SUBSTRING extracts a portion of text.
TRIM removes unnecessary spaces.
REPLACE swaps one part of a string for another.

“Jaise koi galat naam ko replace karke theek karte hain, waise hi SQL mein REPLACE function
hai.”

Example: To remove spaces in a customer name and correct any abbreviations:


SELECT TRIM(REPLACE(CustomerName, 'Mr.', '')) AS CleanName FROM Customers;

Date Functions
Date functions perform operations on date data.
DATEDIFF calculates the difference between dates.
DATEADD adds intervals to dates, like adding days or months.
DATEPART extracts specific parts (e.g., year, month) of a date.

Example: To find customers who have been active for more than 365 days:
SELECT CustomerID FROM Customers WHERE DATEDIFF(day, RegistrationDate, GETDATE()) >
365;

Mathematical Functions
Mathematical functions allow numeric calculations.
ROUND rounds numbers to a specified decimal place.
CEIL rounds up to the nearest integer.
FLOOR rounds down.
MOD finds the remainder.

Example: To calculate the final price after applying a discount:


SELECT ROUND(UnitPrice * Quantity * (1 - Discount), 2) AS FinalPrice FROM Orders;

13
SQL Learners

Advanced:
Performance Tuning :
Performance tuning is optimizing queries and indexes for efficient data retrieval, especially in large
databases.

Indexing Strategies
Indexes speed up data retrieval by creating a “map” to find records faster, much like using an index
in a book. There are:
Clustered Indexes: Sorts data rows in a table, allowing quick access based on the primary key.
Non-Clustered Indexes: Creates pointers to data, useful for frequently searched fields.
Composite Indexes: Involves multiple columns, ideal for complex queries.

“Jaise book ke index se hum page dhoondte hain, waise hi database mein indexing data ko jaldi
dhoondhne mein madad karta hai.”

Example: A composite index on CustomerID and OrderDate improves query performance when
filtering by these fields.

Query Execution Plans


Execution plans provide insights into how SQL executes queries, helping identify bottlenecks. Think of
it as reviewing your travel route to see if there’s traffic.

Example: To analyze the execution plan, you can run:


EXPLAIN SELECT * FROM Orders WHERE OrderDate = '2023-01-01';

Stored Procedures and Triggers


Stored procedures are precompiled SQL codes that automate tasks, while triggers automatically
execute actions in response to events, like keeping records in sync.

“Stored procedures woh hai jo code ko baar-baar likhne se bachata hai, aur triggers apne aap kaam
karte hain.”

Example: Using a trigger to update stock when a sale is made:


CREATE TRIGGER UpdateStock ON Sales AFTER INSERTASBEGINUPDATE Products SET Stock =
Stock - 1 WHERE ProductID = NEW.ProductID;
END;

14
SQL Learners

Advanced:
Transactions and Concurrency :
Transactions ensure that all steps in a multi-step process complete successfully or rollback entirely.

Imagine transferring money between accounts—either the whole transfer succeeds, or nothing
happens.

Locking and Isolation Levels


Locks prevent conflicts when multiple users access data, ensuring consistency. SQL offers different
isolation levels to control data visibility:
Read Uncommitted: Reads data as-is, even if a transaction is incomplete.
Read Committed: Ensures only committed data is read.
Repeatable Read: Prevents data from changing during the transaction.
Serializable: Strictest level, creating a “serial” order of operations.

“Transactions toh bank transfer jaise hain—poori tarah se complete ya poori tarah se cancel.”

Example: A bank transfer transaction:


BEGIN TRANSACTION;
UPDATE Accounts SET Balance = Balance - 500 WHERE AccountID = 1;
UPDATE Accounts SET Balance = Balance + 500 WHERE AccountID = 2;
COMMIT;

15
SQL Learners

Summary Glance :
Here's a comprehensive list of essential SQL terms, along with brief explanations for each. This will serve as a
quick reference guide to important SQL concepts and commands.

Core Concepts
1. Database: An organized collection of structured data.
2. Table: A structure within a database consisting of rows (records) and columns (fields).
3. Schema: The blueprint of a database, defining its structure, including tables, views, indexes, etc.
4. ACID Properties: Principles ensuring database transactions are reliable (Atomicity, Consistency, Isolation,
Durability).

Basic Commands and Operations


1. CRUD: Acronym for Create, Read, Update, Delete – fundamental operations in SQL.
2. SELECT: Command to retrieve data from a database.
3. INSERT: Command to add new records to a table.
4. UPDATE: Modifies existing data in a table.
5. DELETE: Removes records from a table.

Filtering and Sorting


1. WHERE: Filters records based on specific conditions.
2. ORDER BY: Sorts the result set by specified columns.
3. DISTINCT: Returns unique values in the result set, removing duplicates.

Data Types
1. Integer: Whole numbers.
2. Float: Numbers with decimals.
3. VARCHAR/Text: Variable-length character data.
4. DATE: Stores date values.
5. Boolean: Represents true or false values.

Joins and Set Operations


1. INNER JOIN: Returns records with matching values in both tables.
2. LEFT JOIN: Returns all records from the left table, and matched records from the right.
3. RIGHT JOIN: Opposite of left join, returns all records from the right table.
4. FULL JOIN: Combines all records from both tables, including non-matching rows.
5. CROSS JOIN: Produces a Cartesian product of two tables.
6. UNION: Combines the result sets of two queries, removing duplicates.
7. INTERSECT: Returns common records from two queries.

16
SQL Learners

Summary Glance :
Aggregate Functions
1. SUM: Adds up all values in a column.
2. COUNT: Counts the number of records.
3. AVG: Calculates the average of a column’s values.
4. MIN: Returns the smallest value.
5. MAX: Returns the largest value.

Grouping and Filtering Aggregates


1. GROUP BY: Groups records by specified columns for aggregation.
2. HAVING: Filters groups based on aggregate functions (like WHERE, but for grouped data).

Subqueries
1. Subquery: A query nested inside another query, often in WHERE or FROM clauses.
2. Correlated Subquery: A subquery that references columns from the outer query.

Window Functions
1. ROW_NUMBER: Assigns a unique number to each row within a partition.
2. RANK: Assigns a rank to each row, allowing ties.
3. DENSE_RANK: Ranks rows without gaps between ties.
4. NTILE: Divides rows into N equal parts or “buckets.”
5. PARTITION BY: Divides data into partitions, allowing window functions to reset for each partition.

Data Modeling and Schema Design


1. Normalization: Organizes data to reduce redundancy (1NF, 2NF, 3NF, BCNF).
2. Denormalization: Combines tables for better performance but allows redundancy.
3. Primary Key: A unique identifier for each record in a table.
4. Foreign Key: A field linking one table to another.
5. Entity-Relationship Diagram (ERD): Visual representation of entities and their relationships.

Advanced Functions
1. CHARINDEX: Finds the position of a substring within a string.
2. SUBSTRING: Extracts a portion of a string.
3. TRIM: Removes whitespace from a string.
4. REPLACE: Substitutes part of a string with another value.
5. DATEDIFF: Calculates the difference between dates.
6. DATEADD: Adds a specific time interval to a date.
7. ROUND: Rounds a number to a specified decimal place.

17
SQL Learners

Summary Glance :
Performance Tuning
1. Index: Speeds up data retrieval by creating a “map” of specific columns.
2. Clustered Index: Sorts data physically in the table, one per table.
3. Non-Clustered Index: Creates a separate structure with pointers to data.
4. Composite Index: An index on multiple columns.
5. Query Execution Plan: Visualizes how SQL processes a query, useful for optimization.

Stored Procedures and Triggers


1. Stored Procedure: A saved collection of SQL statements, useful for reuse.
2. Trigger: Automatically executes SQL code in response to certain events.

Transactions and Concurrency


1. Transaction: A sequence of operations performed as a single unit.
2. Commit: Saves all changes made in a transaction.
3. Rollback: Reverts changes if an error occurs.
4. Locking: Prevents data conflicts when multiple users access data simultaneously.
5. Isolation Levels: Define data visibility in transactions (Read Uncommitted, Read Committed, Repeatable
Read, Serializable).

Miscellaneous
1. View: A virtual table created by a query.
2. Index Scan: Scans an entire index, generally slower than seeking.
3. Index Seek: Efficiently looks up values within an index.
4. Optimizer: Determines the best query execution path.
5. Constraints: Rules enforced on data (Primary Key, Foreign Key, Unique, Check).
6. Data Integrity: Ensures data accuracy and consistency through constraints and transactions.

18
SQL Learners

Interview Questions :
Basic SQL Questions
1. What is SQL?
Answer: SQL stands for Structured Query Language. It is a standard programming language used for
managing and manipulating relational databases by performing operations such as querying, updating,
inserting, and deleting data.
2. What are the different types of SQL statements?
Answer: SQL statements are broadly categorized into:
DDL (Data Definition Language): CREATE, ALTER, DROP
DML (Data Manipulation Language): SELECT, INSERT, UPDATE, DELETE
DCL (Data Control Language): GRANT, REVOKE
TCL (Transaction Control Language): COMMIT, ROLLBACK, SAVEPOINT
3. What is a primary key?
Answer: A primary key is a column or a set of columns in a table that uniquely identifies each row in that
table. It must contain unique values and cannot contain NULL values.
4. What is a foreign key?
Answer: A foreign key is a column or set of columns that establish a link between the data in two tables. It
acts as a cross-reference between two tables, usually pointing to the primary key in another table.
5. What is a JOIN in SQL?
Answer: A JOIN clause is used to combine rows from two or more tables based on a related column
between them. Types of joins include INNER JOIN, LEFT JOIN (or LEFT OUTER JOIN), RIGHT JOIN
(or RIGHT OUTER JOIN), and FULL JOIN (or FULL OUTER JOIN).
6. Explain the difference between INNER JOIN and LEFT JOIN.
Answer:
INNER JOIN: Returns records that have matching values in both tables.
LEFT JOIN: Returns all records from the left table and the matched records from the right table. If
there is no match, NULL values are returned for columns from the right table.
7. What is a UNIQUE constraint?
Answer: The UNIQUE constraint ensures that all values in a column are different. Unlike a primary key, a
table can have multiple UNIQUE constraints, but a column under a UNIQUE constraint can contain a
NULL value.
8. How do you retrieve unique records from a table?
Answer: Use the DISTINCT keyword in a SELECT query to retrieve unique records. Example:
SELECT DISTINCT column_name FROM table_name;
9. What is a NULL value in SQL?
Answer: NULL represents a missing or undefined value in SQL. It is different from zero or an empty
string.
10. How can you check for NULL values in SQL?
Answer: Use the IS NULL or IS NOT NULL condition in the WHERE clause. Example:
SELECT * FROM table_name WHERE column_name IS NULL;

19
SQL Learners

Interview Questions :
Intermediate SQL Questions
1. What is a subquery?
Answer: A subquery is a query nested inside another query. Subqueries are often used in the WHERE
clause to filter results based on the result of another query.
2. What is a correlated subquery?
Answer: A correlated subquery is a subquery that uses values from the outer query. It is executed once for
every row processed by the outer query.
3. What are aggregate functions in SQL?
Answer: Aggregate functions perform a calculation on a set of values and return a single value. Common
aggregate functions include COUNT(), SUM(), AVG(), MIN(), and MAX().
4. What is the difference between WHERE and HAVING clause?
Answer:
WHERE: Filters records before any groupings are made.
HAVING: Filters records after the aggregation step (GROUP BY). It is typically used with aggregate
functions.
5. Explain the GROUP BY clause.
Answer: The GROUP BY clause groups rows that have the same values in specified columns into
summary rows, like “find the number of customers in each country.” It is often used with aggregate
functions.
6. How do you find the second highest salary in a table?
Answer: One common method is:
SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees);
7. What is a CTE (Common Table Expression)?
Answer: A CTE is a temporary result set that can be referenced within a SELECT, INSERT, UPDATE, or
DELETE statement. CTEs improve readability and maintainability of complex queries.
WITH CTE_name AS (
SELECT column1, column2
FROM table_name
WHERE condition)
SELECT * FROM CTE_name;
8. Explain window functions in SQL.
Answer: Window functions perform calculations across a set of table rows related to the current row,
allowing you to compute cumulative, moving, or ranking values. Examples include ROW_NUMBER(),
RANK(), DENSE_RANK(), NTILE(), LAG(), LEAD(), etc.
9. How would you update data in a table?
Answer: Use the UPDATE statement with the SET clause. Example:
UPDATE table_name
SET column_name = value
WHERE condition;

20
SQL Learners

Interview Questions :
Intermediate SQL Questions
1. Explain the concept of indexing in SQL.
Answer: An index in SQL is a performance optimization feature that improves the speed of data retrieval
operations on a table by providing quick access to rows. However, it can slow down INSERT, UPDATE,
and DELETE operations.
2. What are views in SQL?
Answer: A view is a virtual table created by a SELECT query. It allows you to save complex queries and
simplify data retrieval.
3. Explain the difference between DELETE and TRUNCATE commands.
Answer:
DELETE: Removes specified rows from a table. It can be rolled back using a transaction.
TRUNCATE: Removes all rows from a table and cannot be rolled back. It is faster than DELETE as it
does not log individual row deletions.
4. What is a self-join?
Answer: A self-join is a regular join but the table is joined with itself. It is useful for comparing rows
within the same table.
5. Explain normalization and its types.
Answer: Normalization is the process of organizing the columns and tables of a database to reduce data
redundancy. Types include:
1NF (First Normal Form): Ensures that the table is flat (no repeating groups).
2NF (Second Normal Form): Ensures that all non-key attributes are fully functionally dependent on
the primary key.
3NF (Third Normal Form): Ensures that all the attributes are functionally dependent only on the
primary key.
BCNF (Boyce-Codd Normal Form): A stricter version of 3NF.
6. What are stored procedures and functions?
Answer:
Stored Procedure: A set of SQL statements that can be stored and reused. It may or may not return a
value.
Function: A subroutine that returns a single value. Functions are often used for calculations and must
return a value.

21
SQL Learners

Interview Questions :
Advanced SQL Questions
1. What is a recursive CTE?
Answer: A recursive CTE is a CTE that references itself, allowing you to loop through data. It is often used
for hierarchical data, such as organizational charts or directory structures.
WITH RECURSIVE CTE_name AS (
-- Anchor memberSELECT column1, column2
FROM table_name
WHERE condition
UNION ALL-- Recursive memberSELECT column1, column2
FROM table_name
JOIN CTE_name ON table_name.column = CTE_name.column)
SELECT * FROM CTE_name;
2. Explain the different types of indexes.
Answer:
Clustered Index: Alters the way the rows are physically stored. There can only be one clustered index
per table.
Non-Clustered Index: Creates a separate object within the table that points back to the original table
rows. Multiple non-clustered indexes can exist on a table.
Unique Index: Ensures that the values in the index key column are unique.
Composite Index: An index on two or more columns.
3. How do you optimize a slow-running query?
Answer: Steps to optimize a slow query include:
Use proper indexing.
Avoid unnecessary columns in SELECT.
Use WHERE clauses to filter data efficiently.
Optimize JOIN operations by indexing the join columns.
Use EXPLAIN to analyze and understand the query execution plan.
4. How do you optimize a slow-running query?
Answer: Steps to optimize a slow query include:
Use Proper Indexing: Ensure that relevant columns, especially those used in WHERE clauses, JOIN
conditions, and ORDER BY clauses, are indexed.
Limit Columns in SELECT: Only retrieve necessary columns to reduce the amount of data being
processed.
Avoid Correlated Subqueries: Where possible, replace correlated subqueries with JOINs or CTEs.
EXPLAIN Command: Use EXPLAIN or EXPLAIN ANALYZE to understand the query execution
plan and identify bottlenecks.
Use WHERE Clauses Efficiently: Filter data as early as possible in the query.
Optimize Joins: Ensure that the columns used in JOINs are indexed. Use INNER JOIN when possible
instead of OUTER JOIN.

22
SQL Learners

Interview Questions :
1. What is a materialized view?
Answer: A materialized view is a database object that contains the results of a query. Unlike a regular
view, which is a virtual table, a materialized view stores the data physically. It can be refreshed
periodically to ensure data is up to date. Materialized views can greatly improve performance for complex
queries that are run frequently.
2. Explain the concept of ACID properties.
Answer: ACID stands for Atomicity, Consistency, Isolation, and Durability. These properties ensure
reliable transaction processing in databases.
Atomicity: Ensures that all operations within a transaction are completed; if not, the transaction is
aborted.
Consistency: Ensures that the database remains in a consistent state before and after the transaction.
Isolation: Ensures that transactions are executed in isolation from each other.
Durability: Ensures that once a transaction has been committed, it remains so, even in the event of a
system failure.
3. What are triggers in SQL?
Answer: Triggers are special types of stored procedures that automatically execute or fire when certain
events occur, such as INSERT, UPDATE, or DELETE operations on a table. They can be used to enforce
business rules, validate input data, or maintain audit trails.
4. Explain the difference between UNION and UNION ALL.
Answer:
UNION: Combines the results of two or more SELECT statements and removes duplicate rows.
UNION ALL: Combines the results of two or more SELECT statements, including duplicate rows.
5. What is the purpose of the COALESCE function in SQL?
Answer: The COALESCE function returns the first non-null value from a list of arguments. It’s often used
to handle NULL values by providing a default value.
SELECT COALESCE(column1, 'default_value') FROM table_name;

6. Explain the RANK, DENSE_RANK, and ROW_NUMBER functions in SQL.


Answer:
ROW_NUMBER: Assigns a unique sequential integer to rows within a partition of a result set,
starting at 1.
RANK: Assigns a rank to each row within a partition, with gaps in ranking if there are ties.
DENSE_RANK: Similar to RANK, but without gaps in the ranking.
7. How do you handle duplicates in SQL?
Answer:
Use the DISTINCT keyword in a SELECT statement to remove duplicates.
Use the GROUP BY clause to group and aggregate data, effectively removing duplicates.
Use the ROW_NUMBER function combined with CTEs to identify and remove duplicates.

23
SQL Learners

Interview Questions :
1. What is the difference between CHAR and VARCHAR data types?
Answer:
CHAR: Fixed-length string. If the string is shorter than the specified length, it is padded with spaces.
VARCHAR: Variable-length string. It can store up to the specified length, and no padding is applied.
2. Explain the concept of partitioning in SQL.
Answer: Partitioning refers to dividing a large table into smaller, more manageable pieces called
partitions. This can improve query performance and manageability. Partitioning types include range
partitioning, list partitioning, and hash partitioning.
3. What are the differences between OLTP and OLAP systems?
Answer:
OLTP (Online Transaction Processing): Used for day-to-day transactional systems. These systems
support a large number of short online transactions.
OLAP (Online Analytical Processing): Used for data analysis and decision-making. These systems
are optimized for complex queries and typically involve large volumes of data.
4. How do you implement recursive queries in SQL?
Answer: Recursive queries are implemented using Common Table Expressions (CTEs) with the WITH
RECURSIVE clause. These are often used to handle hierarchical or tree-structured data.
5. What is the use of the EXPLAIN command in SQL?
Answer: The EXPLAIN command provides information about how a SQL query will be executed, showing
the execution plan. This helps in understanding and optimizing query performance.
6. Explain database normalization and denormalization.
Answer:
Normalization: The process of structuring a relational database in accordance with a series of normal
forms to reduce data redundancy and improve data integrity.
Denormalization: The process of combining tables to reduce the complexity of database queries. It
may involve adding redundant data to achieve faster read times.
7. How do you retrieve the current date and time in SQL?
Answer: Use the CURRENT_TIMESTAMP function to retrieve the current date and time. Alternatively,
functions like GETDATE() in SQL Server or SYSDATE in Oracle can be used.
8. What is a CROSS JOIN in SQL?
Answer: A CROSS JOIN produces the Cartesian product of the two tables involved. It pairs each row from
the first table with every row from the second table.
9. Explain the difference between COUNT(*) and COUNT(column_name).
Answer:
COUNT(*): Counts all rows in a table, including rows with NULL values.
COUNT(column_name): Counts only the rows where the specified column is not NULL.
10. What is the significance of the HAVING clause in SQL?
Answer: The HAVING clause is used to filter groups of rows created by the GROUP BY clause. It is
similar to the WHERE clause, but HAVING works after the aggregation is performed.

24
SQL Learners

Interview Questions :
1. Explain the difference between OLAP and OLTP databases.
Answer:
OLAP (Online Analytical Processing): Designed for query-intensive operations like data mining and
analytical querying, typically in a data warehouse environment. It supports complex queries with
many joins.
OLTP (Online Transaction Processing): Designed for transactional systems where speed and data
integrity are essential. It supports a large number of short online transactions.
2. What is an execution plan and how do you analyze it?
Answer: An execution plan is a detailed plan of how SQL Server will execute a query. You can use the
EXPLAIN command to generate an execution plan. Analyzing the execution plan helps in identifying
slow-running queries and understanding their performance bottlenecks.
3. Explain the concept of data warehouse.
Answer: A data warehouse is a centralized repository for storing large volumes of structured data from
various sources. It is used for reporting and data analysis and is a core component of business intelligence.
Data in a warehouse is typically denormalized.
4. What is ETL in SQL?
Answer: ETL stands for Extract, Transform, Load. It is the process of extracting data from different
sources, transforming it into a format suitable for analysis, and loading it into a data warehouse.
5. What is a surrogate key in SQL?
Answer: A surrogate key is an artificially generated key used in a database to uniquely identify a row. It is
usually an integer and is generated by the database system rather than being derived from the application
data.

25
SQL Learners

Practical Questions :
1.Get the second-highest salary of employees
SELECT MAX(Salary) AS SecondHighestSalary FROM Employees WHERE Salary < (SELECT
MAX(Salary) FROM Employees);

2. Find employees with salaries higher than the average salary


SELECT Name, Salary FROM Employees WHERE Salary > (SELECT AVG(Salary) FROM
Employees);

3.Find the department with the maximum number of employees


SELECT DepartmentID, COUNT(*) AS NumEmployees FROM Employees GROUP BY DepartmentID
ORDER BY NumEmployees DESC LIMIT 1;

4. List the top 3 highest-paid employees in each department


SELECT *
FROM (
SELECT Name, DepartmentID, Salary,
ROW_NUMBER() OVER(PARTITION BY DepartmentID ORDER BY Salary DESC) AS Rank
FROM Employees
) AS Ranked
WHERE Rank <= 3;

5. Identify duplicate records in a table


SELECT Column1, Column2, COUNT(*) FROM TableName GROUP BY Column1, Column2 HAVING
COUNT(*) > 1;

6. Find employees who joined on the same date


SELECT JoinDate, COUNT(*) AS NumEmployees
FROM Employees
GROUP BY JoinDate
HAVING COUNT(*) > 1;

7. Select rows where column values are consecutive integers


SELECT ColumnValue
FROM (
SELECT ColumnValue, LAG(ColumnValue) OVER(ORDER BY ColumnValue) AS PrevValue
FROM TableName
) AS ConsecutiveCheck
WHERE ColumnValue = PrevValue + 1;

26
SQL Learners

Practical Questions :
8.Find the nth highest salary in a table
SELECT Salary
FROM Employees
ORDER BY Salary DESC
LIMIT 1 OFFSET n-1;

9. Retrieve the top 3 departments with the highest total salaries


SELECT DepartmentID, SUM(Salary) AS TotalSalary
FROM Employees
GROUP BY DepartmentID
ORDER BY TotalSalary DESC
LIMIT 3;

10.Find customers who have placed more than three orders


SELECT CustomerID
FROM Orders
GROUP BY CustomerID
HAVING COUNT(*) > 3;

11. Display each employee’s salary as a percentage of the department’s total salary
SELECT Name, DepartmentID, Salary,
(Salary / SUM(Salary) OVER(PARTITION BY DepartmentID)) * 100 AS SalaryPercentage
FROM Employees;

12. Identify customers who have never placed an order


SELECT CustomerID
FROM Customers
WHERE CustomerID NOT IN (SELECT CustomerID FROM Orders);

13. Retrieve the employees with the minimum salary in each department
SELECT *FROM ( SELECT Name, DepartmentID, Salary, RANK() OVER(PARTITION BY
DepartmentID ORDER BY Salary ASC) AS Rank FROM Employees
) AS Ranked WHERE Rank = 1;

27
SQL Learners

Practical Questions :
14. Find the longest consecutive days of attendance
SELECT EmployeeID, COUNT(*) AS ConsecutiveDays
FROM (
SELECT EmployeeID, AttendanceDate,
ROW_NUMBER() OVER(PARTITION BY EmployeeID ORDER BY AttendanceDate) - AttendanceDate AS
Grouping
FROM Attendance )
AS ConsecutiveGroups
GROUP BY EmployeeID, Grouping
ORDER BY ConsecutiveDays
DESC LIMIT 1;

15. Count the number of orders placed by each customer each month
SELECT CustomerID,
YEAR(OrderDate) AS Year,
MONTH(OrderDate) AS Month,
COUNT(*) AS OrdersCount
FROM Orders
GROUP BY CustomerID, YEAR(OrderDate), MONTH(OrderDate);

16. Find products that were never sold


SELECT ProductID FROM Products WHERE ProductID NOT IN (SELECT ProductID FROM Sales);

17. Retrieve products that have been sold at least three times
SELECT ProductID FROM Sales GROUP BY ProductID HAVING COUNT(*) >= 3;

18. Calculate the cumulative total of sales per month


SELECT Month, SUM(Sales) OVER(ORDER BY Month) AS CumulativeSales FROM MonthlySales;

19.Find employees who were promoted more than once


SELECT EmployeeID FROM Promotions GROUP BY EmployeeID HAVING COUNT(*) > 1;

20. Calculate the median salary of each department


SELECT DepartmentID, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY Salary) AS
MedianSalary
FROM Employees
GROUP BY DepartmentID;

28
SQL Learners

Practical Questions :
Additional Questions
21. Find users who log in consecutively for seven days.
22. List products with their total sales by year.
23. Find the average order value for each customer.
24. Count orders that contain more than three products.
25. List departments with more than 10 employees.
26. Find managers who have a higher salary than any of their employees.
27. Calculate monthly revenue growth rate.
28. Display a 3-day moving average of daily sales.
29. Identify top 5 customers by order count in the last year.
30. Retrieve order details where customers ordered on consecutive days.
31. Find products bought by at least 50% of customers.
32. Identify suppliers who have never supplied certain categories.
33. Calculate the retention rate of customers month over month.
34. Find the top 3 employees by sales in each region.
35. Identify days with record-high sales.
36. List products with increasing sales trend for 3 consecutive months.
37. Calculate the ratio of total sales by gender in each region.
38. Find customers who bought all products in a category.
39. Rank products by revenue per year.
40. Identify employees who have never taken leave in the last year.

Each question is a great practice for honing your SQL skills. If you'd like solutions for any of these questions or
need additional explanations, feel free to ask. on [email protected]

These are my posts containing More SQL QUESTIONs with solutions to practice, learn and grow.

Post 1 & Post 2

THE END
29

You might also like