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
customerstable? - Write a query to retrieve only the
customerNameandphonefrom thecustomerstable. - How do you list all rows where
countryis 'USA' in thecustomerstable? - Write a query to find all products in the
productstable with abuyPriceless than 50. - How do you fetch all orders with a
statusof 'Shipped' from theorderstable? - Write a query to display the
productNameandquantityInStockfor all products in theproductstable. - How do you find the distinct
countryvalues in thecustomerstable? - Write a query to count the total number of customers in the
customerstable. - How do you retrieve all employees whose
jobTitleis 'Sales Rep'? - Write a query to sort the
productstable byproductNamein ascending order. - How do you fetch the
customerNameandcityof all customers located in 'Paris'? - Write a query to display the top 10 orders from the
orderstable based on theorderDate. - How do you retrieve all
officeslocated 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
orderstable? - Write a query to display the
productNameof all products in theproductstable whereproductLineis 'Classic Cars'. - How do you find the
customerNameof all customers whosecreditLimitis greater than 50,000? - Write a query to fetch all products that have a
quantityInStockbetween 10 and 100. - How do you retrieve all orders placed in the year 2003?
- Write a query to display the
employeeNumberandfirstNameof employees whose last names start with 'B'.
L1: Intermediate SQL - SOLUTION
- Queries that involve working with multiple tables, using
JOIN,GROUP BY,HAVING, and complexWHEREconditions. - Introduction to subqueries, aggregate functions, and case statements.
- Write a query to retrieve the
customerNameandcityfor customers in 'USA' and 'France'. - How do you fetch the
employeeNumber,lastName, andofficeCodeof all employees who work in the 'San Francisco' office? - Write a query to find the total number of orders for each customer using
ordersandcustomerstables. - How do you retrieve the
productName,quantityInStock, andbuyPricefor products that have been ordered more than 10 times? - Write a query to fetch the
orderNumber,status, andcustomerNamefor orders placed by a customer whosecustomerNumberis 103. - Write a query to find the total sales value (
quantityOrdered * priceEach) for each order in theorderdetailstable. - How do you find the average
quantityOrderedfor eachorderNumberin theorderdetailstable? - Write a query to list the
productLinewith the highest total revenue (quantityOrdered * priceEach) in theorderdetailstable. - Write a query to display the
employeeNumber,firstName,lastName, and the office name where the employee works by joining theemployeesandofficestables. - How do you find the customers who have never placed an order?
- Write a query to retrieve the
customerNameand the total number of orders placed by each customer (include customers who haven’t placed any orders). - Write a query to find the
productNameandquantityOrderedfor all orders where the quantity of the product ordered is greater than 50. - Retrieve the
employeeNumber,firstName, andorderNumberof employees who are assigned assales representatives to customersthat have placed an order. - Write a query to calculate the average price of products in the
productstable based onbuyPrice. - How do you fetch the top 3 most expensive products in the
productstable? - Write a query to retrieve the
customerName,orderNumber, andorderDateof 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
orderstable, 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
employeeNumberandtotalRevenue(sum ofquantityOrdered * priceEach) for each employee who processed orders in 2024. - How do you retrieve the
customerNameandorderNumberof customers who placed orders in both 2023 and 2024? - Write a query to calculate the
rankof employees based on theirsalarywithin each office, using a window function. - How do you find the top 3 products in each
productLinebased on total sales (quantityOrdered * priceEach)? - Write a query to find the
productNameand 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
customerNameand thetotal number of ordersfor 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
orderValuefor 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
productNameand thetotal revenue generatedby each product in theorderdetailstable, 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
orderDatefor each customer. - How do you display the cumulative sum of
quantityOrderedfor each order, ordered byorderDate? - Write a query to find the
employeeNumberand 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
orderstable. - 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
orderNumberfor eachcustomerNumberand the total revenue for each customer (use subqueries or joins). - How do you calculate the running total of
orderValuefor 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
employeeNumberand 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
employeestable. - Write a query to retrieve the
customerNameandcontactLastNamefor all customers in thecustomerstable. - Write a query to find the
productNameandbuyPricefor all products. - Write a query to retrieve the
employeeNumberandlastNamefor employees who have anofficeCodeof '1'. - Write a query to list the
orderNumberandorderDatefor all orders made in the year 2023. - Write a query to find the
customerNameandphoneof customers whosecontactFirstNameis 'John'. - Write a query to retrieve the
productCodeandproductNamefor products that havequantityInStockless than 50. - Write a query to fetch the
orderNumber,status, andorderDateof orders placed by customercustomerNumber = 102. - Write a query to get the
customerNameandcityfor customers located in 'Paris'. - Write a query to list all employees and their corresponding
jobTitlefrom theemployeestable. - Write a query to retrieve the
productNameandbuyPricefor products whose price is greater than $30. - Write a query to get the
orderNumberandshippedDateof orders that were shipped after '2024-01-01'. - Write a query to list the
employeeNumber,lastName, andfirstNameof all employees who report toemployeeNumber = 1143. - Write a query to get the total number of products listed in the
productstable. - Write a query to display the
productNameandquantityInStockfor all products in the 'Classic Cars' product line. - Write a query to fetch the
productName,buyPrice, andMSRPfor all products withbuyPricegreater thanMSRP. - Write a query to find all employees with the job title 'Sales Manager'.
- Write a query to list the
orderNumberandstatusfor orders placed bycustomerNumber = 103that have been shipped. - Write a query to get the
orderNumberandorderDatefor orders that are marked as 'Shipped' in theorderstable. - Write a query to find the
employeeNumberandlastNamefor employees who do not have a manager (reportsTois NULL).
- Queries that involve working with multiple tables, using
JOIN,GROUP BY,HAVING, and complexWHEREconditions. - Introduction to subqueries, aggregate functions, and case statements.
- Write a query to find the
customerName,employeeNumber, andorderNumberfor all orders placed bycustomerNumber = 1001. - How do you retrieve the
productName,quantityInStock, andbuyPricefor products in theClassic Carsproduct line, with quantity more than 10? - Write a query to display the
employeeNumberandtotal revenuegenerated by each employee (total revenue isquantityOrdered * priceEach). - Write a query to calculate the average
orderValue(quantityOrdered * priceEach) for each order in theorderdetailstable. - Write a query to retrieve the
customerNameandtotal number of ordersfor each customer who has placed at least 3 orders. - How do you find the
employeeNumber,firstName, and the totalsalaryfor each employee in theemployeestable? - Write a query to find the total sales revenue (
quantityOrdered * priceEach) for eachproductLine. - Write a query to retrieve the
productName,buyPrice, andMSRPfor products where the price is higher than the averageMSRPof all products. - Write a query to find the
customerNameand thetotal revenuefor each customer (total revenueis the sum ofquantityOrdered * priceEach). - Write a query to find the total number of orders placed by customers from the 'USA' using the
ordersandcustomerstables. - 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
productLinewith the highest total revenue (based onquantityOrdered * priceEach). - Write a query to find the
orderNumber,orderDate, and the totalorderValuefor each order in theorderstable. - 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
salaryin each office, and display theiremployeeNumber,firstName, andlastName? - Write a query to find the total number of orders placed by each customer using
ordersandcustomerstables. - Write a query to calculate the total sales amount (
quantityOrdered * priceEach) by eachproductCodefrom theorderdetailstable. - Write a query to get the
productCodeand total revenue for each product where the total revenue exceeds $1000. - How do you retrieve the
employeeNumberandtotal revenuefor each employee who has processed orders worth over $10,000? - Write a query to find the
orderNumberandorderDateof all orders where thestatusis 'Shipped' and theshipDateis 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
rankof 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
customerNameandorderNumberfor customers who have placed orders worth more than $5,000 in total. - Write a query to calculate the cumulative sum of
quantityOrderedfor 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
productNameand 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 eachproductLineandemployee, partitioned byemployeeNumber. - Write a query to find customers who have placed orders in both 2023 and 2024. Display their
customerNameandorderNumber. - Write a query to calculate the running total of the
orderValuefor each order, ordered byorderDate. - Write a query to find the
employeeNumberand 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 eachproductCodeand display only the top 3 products by revenue. - How do you find the
employeeNumberand 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 eachproductCodeusing indexes and optimized joins. - Subqueries: Write a query to retrieve the
customerNameandorderNumberof customers who placed an order where theorderDateis 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
employeestable, starting with employeeemployeeNumber = 1143. - CTE with Multiple Joins: Write a query to calculate the total revenue (
quantityOrdered * priceEach) for eachproductLine, but only includeproductsordered 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 eachproductCodewithin eachorderDatepartition, 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
customerNameand thecreditLimitof customers who have not placed any orders (include customers with NULLcustomerNumberin theorderstable). - 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, andorderstables. - Advanced Subquery: Write a query to find the
productCodeand the total revenue generated for each product where the total revenue exceeds the average revenue of all products in theorderdetailstable. - CTE with Window Functions: Write a query to display the top 3 employees with the highest total
salary, but include their total order value (joinemployeesandordersusing 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
employeestable. - Multi-Level Aggregation: Write a query to find the average
salaryfor eachjobTitlein theemployeestable and then calculate the total averagesalaryacross all job titles. - Multi-Table Aggregation: Write a query to find the
productLinewith the highest total revenue from bothordersandorderdetailstables. - 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
customerswho have placed orders but have aNULLvalue forcreditLimit. - Advanced Join and Grouping: Write a query to retrieve the
orderNumber,orderDate, and total order value for each order (useordersandorderdetails), 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 theshippedDatewhere the order was not shipped within 5 days of placing the order. - Query Optimization with Indexing: Write a query to find the
customerNameandtotal orders valuefor 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, andDELETEstatements 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
WHEREandHAVINGclauses?- 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 JOINandOUTER 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
CASEstatement 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
UNIONandUNION 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
COMMITorROLLBACK).
- 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
JOINandUNION?- 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
WITHclause (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, orDELETEstatement.
- 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
CHARandVARCHAR?- CHAR is a fixed-length string data type, while VARCHAR is a variable-length string data type.
VARCHARuses only as much space as needed, whereasCHARalways 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
DISTINCTkeyword is used. TheDISTINCTkeyword 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
UNIQUEconstraint 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
COMMITandROLLBACK?- 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
WITHclauses (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
WITHclause (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, orDELETEstatement. 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
EXPLAINin SQL?- The
EXPLAINstatement 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 INTOandINSERT?- There is no difference between
INSERT INTOandINSERTin SQL. Both are used to insert data into a table. TheINTOkeyword 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
LOCALandGLOBALtemporary 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.