This repository contains a collection of SQL queries and interview questions commonly asked in technical interviews. The questions are categorized based on their difficulty levels and cover a wide range of SQL concepts, from basic to advanced.
- Introduction
- Prerequisites
- Repository Structure
- Categories of Questions
- Theory - Common Interview Questions
- Contributing
- License
This repository serves as a practical guide for learning SQL and preparing for SQL-related interview questions. The questions range from basic SQL syntax to complex queries involving database optimization, transactions, joins, subqueries, and advanced SQL techniques.
- Before starting with the practice set, you have to download and set mysql sample database "classicmodels", click here to download
- Download diagram of classicmodels db - click here
- For more info go to - Mysql
- Part 1
- L0: Basic SQL queries and concepts.
- L1: Intermediate SQL queries covering joins, aggregation, and subqueries.
- L2: Advanced SQL queries involving performance optimization, window functions, and more complex scenarios.
- Part 2
- Same as Part 1 with different queries.
- L3: For Ultra Pro Max Student/Developer 😅
- Theory: SQL theory questions including database design, normalization, transactions, indexing, etc.
L0: Basic SQL - SOLUTION
- Questions related to basic SQL commands such as
SELECT
,INSERT
,UPDATE
, andDELETE
. - Queries related to basic data manipulation and retrieval from simple tables.
- How do you display all columns and rows from the
customers
table? - Write a query to retrieve only the
customerName
andphone
from thecustomers
table. - How do you list all rows where
country
is 'USA' in thecustomers
table? - Write a query to find all products in the
products
table with abuyPrice
less than 50. - How do you fetch all orders with a
status
of 'Shipped' from theorders
table? - Write a query to display the
productName
andquantityInStock
for all products in theproducts
table. - How do you find the distinct
country
values in thecustomers
table? - Write a query to count the total number of customers in the
customers
table. - How do you retrieve all employees whose
jobTitle
is 'Sales Rep'? - Write a query to sort the
products
table byproductName
in ascending order. - How do you fetch the
customerName
andcity
of all customers located in 'Paris'? - Write a query to display the top 10 orders from the
orders
table based on theorderDate
. - How do you retrieve all
offices
located in the USA? - Write a query to display all employees who work in the office located in 'San Francisco'.
- How do you calculate the total number of orders placed in the
orders
table? - Write a query to display the
productName
of all products in theproducts
table whereproductLine
is 'Classic Cars'. - How do you find the
customerName
of all customers whosecreditLimit
is greater than 50,000? - Write a query to fetch all products that have a
quantityInStock
between 10 and 100. - How do you retrieve all orders placed in the year 2003?
- Write a query to display the
employeeNumber
andfirstName
of employees whose last names start with 'B'.
L1: Intermediate SQL - SOLUTION
- Queries that involve working with multiple tables, using
JOIN
,GROUP BY
,HAVING
, and complexWHERE
conditions. - Introduction to subqueries, aggregate functions, and case statements.
- Write a query to retrieve the
customerName
andcity
for customers in 'USA' and 'France'. - How do you fetch the
employeeNumber
,lastName
, andofficeCode
of all employees who work in the 'San Francisco' office? - Write a query to find the total number of orders for each customer using
orders
andcustomers
tables. - How do you retrieve the
productName
,quantityInStock
, andbuyPrice
for products that have been ordered more than 10 times? - Write a query to fetch the
orderNumber
,status
, andcustomerName
for orders placed by a customer whosecustomerNumber
is 103. - Write a query to find the total sales value (
quantityOrdered * priceEach
) for each order in theorderdetails
table. - How do you find the average
quantityOrdered
for eachorderNumber
in theorderdetails
table? - Write a query to list the
productLine
with the highest total revenue (quantityOrdered * priceEach
) in theorderdetails
table. - Write a query to display the
employeeNumber
,firstName
,lastName
, and the office name where the employee works by joining theemployees
andoffices
tables. - How do you find the customers who have never placed an order?
- Write a query to retrieve the
customerName
and the total number of orders placed by each customer (include customers who haven’t placed any orders). - Write a query to find the
productName
andquantityOrdered
for all orders where the quantity of the product ordered is greater than 50. - Retrieve the
employeeNumber
,firstName
, andorderNumber
of employees who are assigned assales representatives to customers
that have placed an order. - Write a query to calculate the average price of products in the
products
table based onbuyPrice
. - How do you fetch the top 3 most expensive products in the
products
table? - Write a query to retrieve the
customerName
,orderNumber
, andorderDate
of all orders that have a status of 'Shipped'. - How do you display the total number of products sold for each
productLine
? - Write a query to find employees who report directly to the employee with
employeeNumber = 1143
. - Write a query to calculate the total number of orders in the
orders
table, grouped bystatus
. - List employees with their manager’s name.
- Complex SQL queries including window functions, common table expressions (CTEs), transactions, stored procedures, and optimization techniques.
- In-depth questions on database performance, indexing, normalization, and advanced joins.
- Write a query to find the
employeeNumber
andtotalRevenue
(sum ofquantityOrdered * priceEach
) for each employee who processed orders in 2024. - How do you retrieve the
customerName
andorderNumber
of customers who placed orders in both 2023 and 2024? - Write a query to calculate the
rank
of employees based on theirsalary
within each office, using a window function. - How do you find the top 3 products in each
productLine
based on total sales (quantityOrdered * priceEach
)? - Write a query to find the
productName
and the total quantity ordered for each product where the product has been ordered more than 5 times in the last 6 months. - How do you find the
customerName
and thetotal number of orders
for each customer who placed orders worth more than $10,000? - Write a query to display the
employeeNumber
,firstName
,lastName
, and their total orders value using a window function (include all employees). - Write a query to calculate the average
orderValue
for eachproductLine
(orderValue is the sum ofquantityOrdered * priceEach
). - How do you find the employees who have processed more than 10 orders and have the highest total order value within their office?
- Write a query to find the
productName
and thetotal revenue generated
by each product in theorderdetails
table, sorted in descending order. - How do you find customers who have never placed an order and list them alongside their
customerNumber
? - Write a query to calculate the difference between the first and last
orderDate
for each customer. - How do you display the cumulative sum of
quantityOrdered
for each order, ordered byorderDate
? - Write a query to find the
employeeNumber
and their rank based on the total number of orders they have processed, usingRANK()
orDENSE_RANK()
window function. - Write a query to find the product(s) that have been ordered in every single order in the
orders
table. - How do you calculate the total revenue from all orders processed by employees from the 'Boston' office in the last quarter?
- Write a query to display the highest
orderNumber
for eachcustomerNumber
and the total revenue for each customer (use subqueries or joins). - How do you calculate the running total of
orderValue
for all orders placed after '2024-01-01' using a window function? - Write a query to find the employee who has processed the most revenue, and display their
employeeNumber
,firstName
, andlastName
. - How do you retrieve the
employeeNumber
and their corresponding office with the highest number of orders? Display it alongside the total number of orders processed by each employee.
- Questions related to basic SQL commands such as
SELECT
,INSERT
,UPDATE
, andDELETE
. - Queries related to basic data manipulation and retrieval from simple tables.
- Write a query to get all columns from the
employees
table. - Write a query to retrieve the
customerName
andcontactLastName
for all customers in thecustomers
table. - Write a query to find the
productName
andbuyPrice
for all products. - Write a query to retrieve the
employeeNumber
andlastName
for employees who have anofficeCode
of '1'. - Write a query to list the
orderNumber
andorderDate
for all orders made in the year 2023. - Write a query to find the
customerName
andphone
of customers whosecontactFirstName
is 'John'. - Write a query to retrieve the
productCode
andproductName
for products that havequantityInStock
less than 50. - Write a query to fetch the
orderNumber
,status
, andorderDate
of orders placed by customercustomerNumber = 102
. - Write a query to get the
customerName
andcity
for customers located in 'Paris'. - Write a query to list all employees and their corresponding
jobTitle
from theemployees
table. - Write a query to retrieve the
productName
andbuyPrice
for products whose price is greater than $30. - Write a query to get the
orderNumber
andshippedDate
of orders that were shipped after '2024-01-01'. - Write a query to list the
employeeNumber
,lastName
, andfirstName
of all employees who report toemployeeNumber = 1143
. - Write a query to get the total number of products listed in the
products
table. - Write a query to display the
productName
andquantityInStock
for all products in the 'Classic Cars' product line. - Write a query to fetch the
productName
,buyPrice
, andMSRP
for all products withbuyPrice
greater thanMSRP
. - Write a query to find all employees with the job title 'Sales Manager'.
- Write a query to list the
orderNumber
andstatus
for orders placed bycustomerNumber = 103
that have been shipped. - Write a query to get the
orderNumber
andorderDate
for orders that are marked as 'Shipped' in theorders
table. - Write a query to find the
employeeNumber
andlastName
for employees who do not have a manager (reportsTo
is NULL).
- Queries that involve working with multiple tables, using
JOIN
,GROUP BY
,HAVING
, and complexWHERE
conditions. - Introduction to subqueries, aggregate functions, and case statements.
- Write a query to find the
customerName
,employeeNumber
, andorderNumber
for all orders placed bycustomerNumber = 1001
. - How do you retrieve the
productName
,quantityInStock
, andbuyPrice
for products in theClassic Cars
product line, with quantity more than 10? - Write a query to display the
employeeNumber
andtotal revenue
generated by each employee (total revenue isquantityOrdered * priceEach
). - Write a query to calculate the average
orderValue
(quantityOrdered * priceEach
) for each order in theorderdetails
table. - Write a query to retrieve the
customerName
andtotal number of orders
for each customer who has placed at least 3 orders. - How do you find the
employeeNumber
,firstName
, and the totalsalary
for each employee in theemployees
table? - Write a query to find the total sales revenue (
quantityOrdered * priceEach
) for eachproductLine
. - Write a query to retrieve the
productName
,buyPrice
, andMSRP
for products where the price is higher than the averageMSRP
of all products. - Write a query to find the
customerName
and thetotal revenue
for each customer (total revenue
is the sum ofquantityOrdered * priceEach
). - Write a query to find the total number of orders placed by customers from the 'USA' using the
orders
andcustomers
tables. - How do you retrieve the list of employees working in the 'San Francisco' office? List their
employeeNumber
,firstName
, andlastName
. - Write a query to retrieve the
productLine
with the highest total revenue (based onquantityOrdered * priceEach
). - Write a query to find the
orderNumber
,orderDate
, and the totalorderValue
for each order in theorders
table. - Write a query to list all customers from 'USA' who have placed orders after '2024-01-01'.
- How do you find the employee with the highest
salary
in each office, and display theiremployeeNumber
,firstName
, andlastName
? - Write a query to find the total number of orders placed by each customer using
orders
andcustomers
tables. - Write a query to calculate the total sales amount (
quantityOrdered * priceEach
) by eachproductCode
from theorderdetails
table. - Write a query to get the
productCode
and total revenue for each product where the total revenue exceeds $1000. - How do you retrieve the
employeeNumber
andtotal revenue
for each employee who has processed orders worth over $10,000? - Write a query to find the
orderNumber
andorderDate
of all orders where thestatus
is 'Shipped' and theshipDate
is in the year 2023.
- Complex SQL queries including window functions, common table expressions (CTEs), transactions, stored procedures, and optimization techniques.
- In-depth questions on database performance, indexing, normalization, and advanced joins.
- Write a query to calculate the
rank
of products based on total revenue (quantityOrdered * priceEach
) using a window function and partition byproductLine
. - How do you calculate the total revenue (
quantityOrdered * priceEach
) for each employee, and rank them based on the total revenue generated? - Write a query to retrieve the
customerName
andorderNumber
for customers who have placed orders worth more than $5,000 in total. - Write a query to calculate the cumulative sum of
quantityOrdered
for eachorderNumber
, ordered byorderDate
. - Write a recursive query to find the hierarchical structure of employees reporting to the employee with
employeeNumber = 1143
. - Write a query to calculate the average order value (
quantityOrdered * priceEach
) for eachproductLine
, excluding products with a total order value of less than $1,000. - Write a query to display the
employeeNumber
,firstName
, andtotal sales
(sum ofquantityOrdered * priceEach
) for each employee using a window function. - Write a query to find the
productName
and total revenue for each product, and rank products by revenue within each product line. - Write a query to calculate the total revenue (
quantityOrdered * priceEach
) for eachproductLine
andemployee
, partitioned byemployeeNumber
. - Write a query to find customers who have placed orders in both 2023 and 2024. Display their
customerName
andorderNumber
. - Write a query to calculate the running total of the
orderValue
for each order, ordered byorderDate
. - Write a query to find the
employeeNumber
and their rank based on the total number of orders processed, using theRANK()
function. - Write a query to find all products that were ordered in every order placed in 2024.
- Write a query to find the employee who processed the highest revenue and display their
employeeNumber
,firstName
, andlastName
. - Write a query to display the total number of orders placed by customers from each
country
, and order the result by the number of orders. - Write a query to calculate the total revenue (
quantityOrdered * priceEach
) for eachproductCode
and display only the top 3 products by revenue. - How do you find the
employeeNumber
and total revenue generated for each employee who has processed more than 10 orders? - Write a query to find the product(s) with the highest total revenue for each product line.
- Write a query to calculate the average order value per customer, excluding customers who have placed fewer than 3 orders.
- Write a query to find the total number of orders and total revenue for each product line, grouped by year.
- These are expert-level questions designed to challenge your skills with advanced SQL concepts
- including performance optimization, complex joins, subqueries, recursive queries, CTEs with multiple joins, and advanced data manipulation techniques.
- Performance Optimization: Write a query to find the total revenue (
quantityOrdered * priceEach
) for eachproductCode
using indexes and optimized joins. - Subqueries: Write a query to retrieve the
customerName
andorderNumber
of customers who placed an order where theorderDate
is later than the most recent order placed bycustomerNumber = 103
. - Recursive Query: Write a recursive query to find the hierarchical structure of employees (manager-subordinate relationship) in the
employees
table, starting with employeeemployeeNumber = 1143
. - CTE with Multiple Joins: Write a query to calculate the total revenue (
quantityOrdered * priceEach
) for eachproductLine
, but only includeproducts
ordered in the last 6 months. Use a CTE to organize the query. - Window Function with Partitioning: Write a query to calculate the running total of revenue (
quantityOrdered * priceEach
) for eachproductCode
within eachorderDate
partition, sorted byorderDate
. - Self-Join: Write a query to find all employees who report to the same manager and list their
employeeNumber
,firstName
, andlastName
. - Query Optimization: Write a query to find the top 5 customers who spent the most in total, optimizing the query by indexing appropriate columns and using joins to calculate the total revenue.
- Handling NULLs: Write a query to find the
customerName
and thecreditLimit
of customers who have not placed any orders (include customers with NULLcustomerNumber
in theorders
table). - Advanced Aggregation: Write a query to calculate the average order value for each customer, but exclude customers who have placed less than 3 orders.
- Join Multiple Tables: Write a query to list the
employeeName
,officeLocation
, and the total value of orders processed by the employee, joining theemployees
,offices
, andorders
tables. - Advanced Subquery: Write a query to find the
productCode
and the total revenue generated for each product where the total revenue exceeds the average revenue of all products in theorderdetails
table. - CTE with Window Functions: Write a query to display the top 3 employees with the highest total
salary
, but include their total order value (joinemployees
andorders
using a CTE and window function). - Recursive CTE: Write a recursive CTE to display the entire hierarchy of the sales representatives and their managers in the
employees
table. - Multi-Level Aggregation: Write a query to find the average
salary
for eachjobTitle
in theemployees
table and then calculate the total averagesalary
across all job titles. - Multi-Table Aggregation: Write a query to find the
productLine
with the highest total revenue from bothorders
andorderdetails
tables. - Dynamic Query Generation: Write a query to dynamically generate the total order value for each
customerNumber
, where the calculation formula (quantityOrdered * priceEach
) is customizable in the query. - Dealing with Data Inconsistencies: Write a query to identify
customers
who have placed orders but have aNULL
value forcreditLimit
. - Advanced Join and Grouping: Write a query to retrieve the
orderNumber
,orderDate
, and total order value for each order (useorders
andorderdetails
), but only include orders with products from a specificproductLine
. - Data Anomalies Detection: Write a query to find any discrepancies between the order date (
orderDate
) and theshippedDate
where the order was not shipped within 5 days of placing the order. - Query Optimization with Indexing: Write a query to find the
customerName
andtotal orders value
for each customer who placed orders greater than $5,000, optimizing the query performance by suggesting appropriate indexes.
- Performance Optimization: Focusing on indexes and optimized joins.
- Recursive Queries: Useful for hierarchical data like employee-manager relationships.
- CTEs (Common Table Expressions): Organizing complex queries, especially with multiple joins and aggregations.
- Window Functions: Running totals, rankings, etc., with partitioning.
- Advanced Joins: Self-joins, joins across multiple tables.
- Subqueries: Writing nested queries for advanced filtering and calculation.
- Handling NULLs: Dealing with missing data while fetching relevant results.
- Data Anomalies: Identifying inconsistencies and fixing potential issues in business logic.
These expert-level questions will challenge you to think critically about query optimization, complex data retrieval, and efficient handling of large datasets. They will also help you prepare for interviews at top tech companies.
some of the most common SQL theory questions that are frequently asked in interviews. These questions test your understanding of SQL concepts, queries, optimization, and the relational database model.
-
What is SQL?
- SQL (Structured Query Language) is a domain-specific language used for managing and manipulating relational databases. It is used to query, update, insert, and delete data from a database.
-
What are the different types of SQL commands?
- DML (Data Manipulation Language):
SELECT
,INSERT
,UPDATE
,DELETE
. - DDL (Data Definition Language):
CREATE
,ALTER
,DROP
,TRUNCATE
. - DCL (Data Control Language):
GRANT
,REVOKE
. - TCL (Transaction Control Language):
COMMIT
,ROLLBACK
,SAVEPOINT
.
- DML (Data Manipulation Language):
-
What is a primary key?
- A primary key is a unique identifier for a record in a database table. It ensures that each record is unique and not null.
-
What is a foreign key?
- A foreign key is a field in one table that uniquely identifies a row of another table. It establishes and enforces a link between the data in two tables.
-
What is normalization?
- Normalization is the process of organizing the attributes and tables of a database to minimize redundancy and dependency. It divides large tables into smaller ones and defines relationships between them.
-
What is denormalization?
- Denormalization is the process of combining tables to reduce the complexity of queries and increase query performance, often at the cost of additional storage and redundancy.
-
What are the types of joins in SQL?
- INNER JOIN: Returns only matching rows from both tables.
- LEFT JOIN (or LEFT OUTER JOIN): Returns all rows from the left table and matched rows from the right table.
- RIGHT JOIN (or RIGHT OUTER JOIN): Returns all rows from the right table and matched rows from the left table.
- FULL JOIN (or FULL OUTER JOIN): Returns all rows when there is a match in either left or right table.
- CROSS JOIN: Returns the Cartesian product of both tables.
-
What is an index in SQL?
- An index is a database object that improves the speed of data retrieval operations on a table. It works similarly to an index in a book, allowing faster access to specific rows.
-
What is a subquery?
- A subquery is a query nested inside another query. It can be used in
SELECT
,INSERT
,UPDATE
, andDELETE
statements to provide intermediate results for the main query.
- A subquery is a query nested inside another query. It can be used in
-
What is a view in SQL?
- A view is a virtual table based on the result set of a SQL query. It does not store data physically but presents the data from one or more tables in a structured way.
-
What is a stored procedure?
- A stored procedure is a precompiled collection of SQL statements that can be executed as a unit. It can accept parameters and return results, improving performance and reusability.
-
What is a trigger in SQL?
- A trigger is a set of SQL statements that automatically execute or fire when a specified event (like
INSERT
,UPDATE
,DELETE
) occurs on a table or view.
- A trigger is a set of SQL statements that automatically execute or fire when a specified event (like
-
What is the difference between
WHERE
andHAVING
clauses?- WHERE is used to filter records before aggregation (used in
SELECT
,UPDATE
,DELETE
). - HAVING is used to filter records after aggregation (used with
GROUP BY
).
- WHERE is used to filter records before aggregation (used in
-
What is the difference between
DELETE
,TRUNCATE
, andDROP
?- DELETE: Removes specific rows from a table based on a condition and can be rolled back.
- TRUNCATE: Removes all rows from a table without logging individual row deletions and cannot be rolled back.
- DROP: Deletes a table, its structure, and its data permanently.
-
What is the difference between
INNER JOIN
andOUTER JOIN
?- INNER JOIN returns only matching rows from both tables.
- OUTER JOIN returns matched rows from both tables, plus unmatched rows from one or both tables (can be
LEFT
,RIGHT
, orFULL
).
-
What are aggregate functions in SQL?
- Aggregate functions perform calculations on a set of values and return a single value. Common aggregate functions include
COUNT()
,SUM()
,AVG()
,MIN()
,MAX()
.
- Aggregate functions perform calculations on a set of values and return a single value. Common aggregate functions include
-
What is a self join?
- A self join is a join where a table is joined with itself. This is useful for hierarchical or recursive relationships within the same table.
-
What is a
CASE
statement in SQL?- The CASE statement is used to add conditional logic to SQL queries. It is like an IF-ELSE statement that returns specific values based on conditions.
-
What is the difference between
UNION
andUNION ALL
?- UNION combines the result sets of two or more queries and removes duplicates.
- UNION ALL combines the result sets and keeps all duplicates.
-
What is a composite key?
- A composite key is a primary key that consists of two or more columns to uniquely identify a record in a table.
-
What is ACID in database systems?
- ACID stands for Atomicity, Consistency, Isolation, and Durability. It ensures that database transactions are processed reliably and protects against system failures.
-
What is a transaction in SQL?
- A transaction is a sequence of SQL operations that are executed as a single unit of work. A transaction must be completed in full, or not at all (i.e., using
COMMIT
orROLLBACK
).
- A transaction is a sequence of SQL operations that are executed as a single unit of work. A transaction must be completed in full, or not at all (i.e., using
-
What is the difference between
JOIN
andUNION
?- JOIN combines rows from two or more tables based on a related column.
- UNION combines the result sets of two or more queries into a single result set (only returns unique rows).
-
What is a database normalization form (1NF, 2NF, 3NF, BCNF)?
- 1NF (First Normal Form): Eliminates duplicate columns and ensures atomicity (each column contains unique values).
- 2NF (Second Normal Form): Eliminates partial dependencies, where non-key columns depend on only part of the primary key.
- 3NF (Third Normal Form): Eliminates transitive dependencies (non-key columns should not depend on other non-key columns).
- BCNF (Boyce-Codd Normal Form): A stricter version of 3NF where every determinant is a candidate key.
-
What is a deadlock in SQL, and how can it be prevented?
- A deadlock occurs when two or more transactions are blocked, each waiting for the other to release resources. It can be prevented by using transaction isolation levels and applying proper locking strategies.
-
What is the difference between
RANK()
andDENSE_RANK()
?- RANK() assigns ranks with gaps when there are ties.
- DENSE_RANK() assigns ranks without gaps, even when there are ties.
-
What is a
WITH
clause (Common Table Expressions, CTE)?- The WITH clause is used to define a temporary result set (CTE) that can be referenced within a
SELECT
,INSERT
,UPDATE
, orDELETE
statement.
- The WITH clause is used to define a temporary result set (CTE) that can be referenced within a
-
What are the different types of indexes in SQL?
- Unique Index: Ensures that no two rows have the same values in certain columns.
- Composite Index: An index on multiple columns.
- Full-Text Index: Used for text searching.
- Clustered Index: The data is physically ordered on the disk based on the index key.
- Non-Clustered Index: An index that is separate from the data and helps speed up queries.
-
What is a surrogate key?
- A surrogate key is an artificial key used to uniquely identify a record, often implemented as an auto-incremented field.
-
Explain the concept of sharding in databases.
- Sharding is a technique of horizontally partitioning a large database into smaller, more manageable pieces called shards. Each shard is stored on a separate server or cluster.
-
What is a relational database?
- A relational database is a type of database that stores data in tables (relations). Each table consists of rows and columns, where each row represents a record, and each column represents an attribute of the record.
-
What are database constraints, and why are they important?
- Constraints are rules enforced on data in a table to ensure data integrity. Common types of constraints include
NOT NULL
,UNIQUE
,CHECK
,DEFAULT
,PRIMARY KEY
, andFOREIGN KEY
.
- Constraints are rules enforced on data in a table to ensure data integrity. Common types of constraints include
-
What is the difference between
CHAR
andVARCHAR
?- CHAR is a fixed-length string data type, while VARCHAR is a variable-length string data type.
VARCHAR
uses only as much space as needed, whereasCHAR
always uses the defined length.
- CHAR is a fixed-length string data type, while VARCHAR is a variable-length string data type.
-
What is referential integrity?
- Referential integrity ensures that relationships between tables are maintained consistently. It means that foreign keys in a table must correspond to valid primary keys in another table.
-
Explain the concept of data consistency in a database.
- Data consistency means that the data stored in a database is accurate, reliable, and follows the defined rules or constraints at all times.
-
What are the different types of indexing in SQL, and how do they differ?
- Clustered Index: Data is physically ordered based on the index key.
- Non-clustered Index: A separate structure that points to the data rows, allowing faster access.
- Unique Index: Ensures that no two rows have the same values in the indexed column(s).
- Composite Index: Indexing on multiple columns.
-
How does SQL Server handle duplicate rows in a query result?
- By default, SQL removes duplicate rows in the query result unless the
DISTINCT
keyword is used. TheDISTINCT
keyword eliminates duplicate rows from the output.
- By default, SQL removes duplicate rows in the query result unless the
-
What are the potential problems caused by poor indexing?
- Poor indexing can result in slow query performance, increased I/O operations, and long query times, especially with large datasets. Too many indexes can also slow down write operations like
INSERT
,UPDATE
, andDELETE
.
- Poor indexing can result in slow query performance, increased I/O operations, and long query times, especially with large datasets. Too many indexes can also slow down write operations like
-
What is query optimization, and why is it important?
- Query optimization is the process of improving the efficiency of a query by reducing its execution time. It is important to ensure that the database performs well even with large datasets and complex queries.
-
What is the difference between a
UNIQUE
constraint and aPRIMARY KEY
?- Both UNIQUE and PRIMARY KEY ensure uniqueness, but a PRIMARY KEY also implicitly enforces
NOT NULL
. A table can have only one PRIMARY KEY, but it can have multiple UNIQUE constraints.
- Both UNIQUE and PRIMARY KEY ensure uniqueness, but a PRIMARY KEY also implicitly enforces
-
What is a rollback, and when is it used?
- A rollback undoes all changes made by a transaction. It is used in cases of errors or when a transaction violates database rules.
-
What are the different isolation levels in SQL?
- The isolation levels define the visibility of changes made by one transaction to other transactions. They are:
- READ UNCOMMITTED
- READ COMMITTED
- REPEATABLE READ
- SERIALIZABLE
- The isolation levels define the visibility of changes made by one transaction to other transactions. They are:
-
What is a deadlock, and how can it be resolved in SQL?
- A deadlock occurs when two transactions are waiting on each other to release resources, causing a standstill. It can be resolved by using a timeout, retrying the transaction, or implementing proper locking mechanisms.
-
What is the difference between
COMMIT
andROLLBACK
?- COMMIT makes all changes made during the transaction permanent. ROLLBACK undoes all changes made during the transaction.
-
What is a transaction log?
- A transaction log is a record of all the changes made to the database. It ensures that the database can be recovered to a consistent state after a failure.
-
What is a Materialized View?
- A Materialized View is a physical copy of a query result stored in a table format. Unlike regular views, materialized views store the result of a query for faster access and can be refreshed periodically.
-
What is a recursive query?
- A recursive query is a query that refers to itself. In SQL, recursive queries are often implemented using
WITH
clauses (CTEs) to handle hierarchical data, like organizational charts or category structures.
- A recursive query is a query that refers to itself. In SQL, recursive queries are often implemented using
-
Explain the difference between
RANK()
,ROW_NUMBER()
, andDENSE_RANK()
.- ROW_NUMBER() assigns a unique number to each row.
- RANK() assigns ranks to rows with gaps if there are ties.
- DENSE_RANK() assigns ranks without gaps, even with ties.
-
What is a
WITH
clause (Common Table Expressions, CTE), and how is it different from a subquery?- A CTE is a temporary result set that is defined within the execution scope of a
SELECT
,INSERT
,UPDATE
, orDELETE
statement. It is more readable and reusable than a subquery, which is nested within a query.
- A CTE is a temporary result set that is defined within the execution scope of a
-
What is the purpose of
EXPLAIN
in SQL?- The
EXPLAIN
statement is used to analyze and display the execution plan of a query. It helps identify performance bottlenecks and optimize queries by showing how the SQL engine will execute them.
- The
-
What is the difference between 3NF and BCNF?
- 3NF (Third Normal Form) ensures that there are no transitive dependencies, meaning non-key columns should not depend on other non-key columns. BCNF (Boyce-Codd Normal Form) is a stricter version of 3NF, where every determinant must be a candidate key.
-
What are candidate keys and alternate keys?
- Candidate keys are columns that can uniquely identify a record. A primary key is selected from the candidate keys. Alternate keys are the candidate keys not chosen as the primary key.
-
What is an ER diagram?
- An Entity-Relationship (ER) diagram is a visual representation of the database structure, showing entities (tables), attributes (columns), and relationships between entities.
-
What is the difference between
INSERT INTO
andINSERT
?- There is no difference between
INSERT INTO
andINSERT
in SQL. Both are used to insert data into a table. TheINTO
keyword is optional.
- There is no difference between
-
What are the various types of relationships in database design?
- The types of relationships include:
- One-to-One (1:1): Each record in one table is related to one record in another table.
- One-to-Many (1:M): Each record in one table can relate to multiple records in another table.
- Many-to-Many (M:M): Multiple records in one table can relate to multiple records in another table.
- The types of relationships include:
-
What is query execution plan?
- The query execution plan is the strategy that the database query optimizer uses to execute a SQL query. It shows the steps involved in processing the query, including how tables are accessed, joined, and filtered.
-
What is denormalization, and when would you use it?
- Denormalization is the process of combining tables to reduce the complexity of queries and improve performance, particularly in cases where read-heavy operations are more common than write operations.
-
What are window functions, and how are they different from aggregate functions?
- Window functions perform calculations across a set of table rows that are related to the current row, without collapsing the result set like aggregate functions.
-
What is sharding in databases, and how does it work?
- Sharding is a method of partitioning large databases into smaller, more manageable pieces called shards, which are stored across different servers to improve performance and scalability.
-
What is the difference between a
LOCAL
andGLOBAL
temporary table in SQL?- A LOCAL temporary table is visible only to the session that created it and is dropped automatically when the session ends. A GLOBAL temporary table is visible to all sessions, but its data is session-specific.
We welcome contributions to this repository! To contribute, please follow these steps:
- Fork this repository.
- Create a new branch (
git checkout -b feature/your-feature
). - Add your changes or new questions.
- Commit your changes (
git commit -m 'Add new SQL question'
). - Push to the branch (
git push origin feature/your-feature
). - Open a pull request.
If you have any suggestions or questions, feel free to open an issue.
This project is licensed under the MIT License - see the LICENSE file for details.
- Thanks to all contributors who have shared their knowledge and questions!
- Special thanks to classicmodels database for providing sample database queries for practice.