SQL - DAK
SQL - DAK
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!”
“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.
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.
“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.
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.
“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 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;
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.
“Jab data ka ek saath analysis chahiye, tab aggregations ka jaadu chalta hai.”
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.
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.
“ROW_NUMBER aur RANK se competition aur ranking toh banti hai, chahe score barabar ho ya
na ho.”
PARTITION BY
PARTITION BY divides data into parts before applying window functions. It’s like creating mini-
competitions in each department for top performers.
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.”
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.
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.
“Stored procedures woh hai jo code ko baar-baar likhne se bachata hai, aur triggers apne aap kaam
karte hain.”
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.
“Transactions toh bank transfer jaise hain—poori tarah se complete ya poori tarah se cancel.”
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).
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.
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.
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.
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.
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;
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);
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;
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;
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);
17. Retrieve products that have been sold at least three times
SELECT ProductID FROM Sales GROUP BY ProductID HAVING COUNT(*) >= 3;
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.
THE END
29