100 Must-Know SQL Interview Questions: 1. What Is and What Is It Used For?
100 Must-Know SQL Interview Questions: 1. What Is and What Is It Used For?
🟣 SQL interview questions and answers to help you prepare for your next technical interview in 2024.
60 stars 15 forks Branches Tags Activity
Star Notifications
You can also find all 100 answers here 👉 [Link] - SQL
Core Components
DDL (Data Definition Language): Used for defining and modifying the structure of the database.
DML (Data Manipulation Language): Deals with adding, modifying, and removing data in the database.
DCL (Data Control Language): Manages the permissions and access rights of the database.
TCL (Transaction Control Language): Governs the transactional management of the database, such as commits or rollbacks.
Data Manipulation: Insert, update, or delete records from tables. Powerful features like Joins and Subqueries enable complex
operations.
Data Integrity: Ensure data conform to predefined rules. Techniques like foreign keys, constraints, and triggers help maintain the
integrity of the data.
[Link] 1/19
4/10/25, 3:56 PM GitHub - Devinterview-io/sql-interview-questions: 🟣 SQL interview questions and answers to help you prepare for your next techni…
Data Consistency: Enforce ACID properties (Atomicity, Consistency, Isolation, Durability) in database transactions.
Data Backups and Recovery: Perform database backups and ensure data is restorable in case of loss.
Data Normalization: Design databases for efficient storage and reduce data redundancy.
Indices and Performance Tuning: Optimize queries for faster data retrieval.
-- Create a database
CREATE DATABASE Company;
-- Create tables
CREATE TABLE Department (
DeptID INT PRIMARY KEY AUTO_INCREMENT,
DeptName VARCHAR(50) NOT NULL
);
-- Insert data
INSERT INTO Department (DeptName) VALUES ('Engineering');
INSERT INTO Department (DeptName) VALUES ('Sales');
[Link] 2/19
4/10/25, 3:56 PM GitHub - Devinterview-io/sql-interview-questions: 🟣 SQL interview questions and answers to help you prepare for your next techni…
FROM Employee
JOIN Department ON [Link] = [Link];
Top-Level Differences
SQL: Primarily designed for structured (structured, semi-structured) data — data conforming to a predefined schema.
NoSQL: Suited for unstructured or semi-structured data that evolves gradually, thereby supporting flexible schemas.
SQL: Employs SQL (Structured Query Language) for data modification and retrieval.
NoSQL: Offers various APIs (like the document and key-value store interfaces) for data operations; the use of structured query
languages can vary across different NoSQL implementations.
SQL: Often provides ACID (Atomicity, Consistency, Isolation, Durability) compliance to ensure data integrity.
NoSQL: Databases are oftentimes optimized for high performance and horizontal scalability, with potential trade-offs in
consistency.
Document Stores
Key-Value Stores
Graph Databases
Auto-Incrementing IDs
[Link] 3/19
4/10/25, 3:56 PM GitHub - Devinterview-io/sql-interview-questions: 🟣 SQL interview questions and answers to help you prepare for your next techni…
SQL: Often, each entry is assigned a unique auto-incrementing ID.
NoSQL: The generation of unique IDs can be driven by external systems or even specific to individual documents within a
collection.
Transaction Support
SQL: Transactions (a series of operations that execute as a single unit) are standard.
NoSQL: The concept and features of transactions can be more varied based on the specific NoSQL implementation.
Scalability
SQL: Typically scales vertically, i.e., by upgrading hardware.
NoSQL: Is often designed to scale horizontally, using commodity hardware across distributed systems.
Data Flexibility
SQL: Enforces a predefined, rigid schema, making it challenging to accommodate evolving data structures.
NoSQL: Supports dynamic, ad-hoc schema updates for maximum flexibility.
[Link] 4/19
4/10/25, 3:56 PM GitHub - Devinterview-io/sql-interview-questions: 🟣 SQL interview questions and answers to help you prepare for your next techni…
Data Definition Language (DDL)
DDL commands are for managing the structure of the database, including tables and constraints.
GRANT: Assign permission to specified users or roles for specific database objects.
REVOKE: Withdraw or remove these permissions previously granted.
[Link] 5/19
4/10/25, 3:56 PM GitHub - Devinterview-io/sql-interview-questions: 🟣 SQL interview questions and answers to help you prepare for your next techni…
Data Transformation: Creating new fields via operations such as concatenation or mathematical calculations.
Data Validation: Verifying data against defined criteria.
Data Reporting: Generating formatted outputs for business reporting needs.
Data Consolidation: Bringing together information from multiple tables or databases.
Data Export: Facilitating the transfer of query results to other systems or for data backup.
Beyond these functions, proper utilization of the other components ensures efficiency and consistency working with relational
databases.
SELECT
[Link],
[Link],
[Link],
[Link],
[Link],
[Link],
[Link]
FROM
((Orders
INNER JOIN Customers ON [Link] = [Link])
INNER JOIN Employees ON [Link] = [Link])
INNER JOIN OrderDetails ON [Link] = [Link]
WHERE Clause
The WHERE clause is primarily used to filter records before they are grouped or aggregated. It's typically employed with non-
aggregated fields or raw data.
HAVING Clause
Conversely, the HAVING clause filters data after the grouping step, often in conjunction with aggregate functions like SUM or COUNT .
This makes it useful for setting group-level conditions.
Join operations in SQL are responsible for combining rows from multiple tables, primarily based on related columns that are
established using a foreign key relationship.
Inner Join
Outer Join
Left Outer Join
Right Outer Join
Full Outer Join
Cross Join
Self Join
[Link] 6/19
4/10/25, 3:56 PM GitHub - Devinterview-io/sql-interview-questions: 🟣 SQL interview questions and answers to help you prepare for your next techni…
Inner Join
Inner Join only returns rows where there is a match in both tables for the specified column(s).
Visual Representation:
A B B C A B C
- - - - - - -
1 aa aa 20 1 aa 20
2 bb bb 30 2 bb 30
3 cc cc 40
SQL Query:
Outer Join
Outer Joins—whether left, right or full—include all records from one table (the "left" or the "right" table") and matched existing
records from the other table. Unmatched records are filled with NULL values for missing columns from the other table.
Left Outer Join (or simply Left Join) returns all records from the "left" table and the matched records from the "right" table.
Visual Representation:
A B B C A B C
- - - - - - -
1 aa aa 20 1 aa 20
2 bb bb 30 2 bb 30
3 cc NULL NULL 3 cc NULL
SQL Query:
Right Outer Join (or Right Join) returns all records from the "right" table and the matched records from the "left" table.
Visual Representation:
A B B C A B C
- - - - - - -
1 aa aa 20 1 aa 20
2 bb bb 30 2 bb 30
NULL NULL cc 40 NULL NULL 40
SQL Query:
[Link] 7/19
4/10/25, 3:56 PM GitHub - Devinterview-io/sql-interview-questions: 🟣 SQL interview questions and answers to help you prepare for your next techni…
Full Outer Join (or Full Join) returns all records when there is a match in either the left or the right table.
Visual Representation:
A B B C A B C
- - - - - - -
1 aa aa 20 1 aa 20
2 bb bb 30 2 bb 30
3 cc NULL NULL 3 cc NULL
NULL NULL cc 40 NULL NULL 40
SQL Query:
Cross Join
A Cross Join, also known as a Cartesian Join, produces a result set that is the cartesian product of the two input sets. It will generate
every possible combination of rows from both tables.
Visual Representation:
A B C D A B C D
- - - - - - - -
1 aa 20 X 1 aa 20 X
2 bb 30 Y 1 aa 30 Y
3 cc 40 Z 1 aa 40 Z
2 bb 20 X
2 bb 30 Y
2 bb 40 Z
3 cc 20 X
3 cc 30 Y
3 cc 40 Z
SQL Query:
Self Join
A Self Join is when a table is joined with itself. This is used when a table has a relationship with itself, typically when it has a parent-
child relationship.
Visual Representation:
[Link] 8/19
4/10/25, 3:56 PM GitHub - Devinterview-io/sql-interview-questions: 🟣 SQL interview questions and answers to help you prepare for your next techni…
SQL Query:
Key Characteristics
Uniqueness: Each value in the primary key column is unique, distinguishing every record.
Stability: It generally does not change throughout the record's lifetime, promoting consistency.
Association Control: Helps manage relationships across tables and ensures referential integrity in foreign keys.
Performance Advantages
Efficient Indexing: Primary keys are often auto-indexed, making data retrieval faster.
Optimized Joins: When the primary key links to a foreign key, query performance improves for related tables.
Avoid Data in Column Attributes: Using data can lead to bloat, adds complexity, and can be restrictive.
Avoid Data Sensitivity: Decrease potential risks associated with sensitive data by separating it from keys.
Evaluate Multi-Column Keys Carefully: Identify and justify the need for such complexity.
[Link] 9/19
4/10/25, 3:56 PM GitHub - Devinterview-io/sql-interview-questions: 🟣 SQL interview questions and answers to help you prepare for your next techni…
first_name VARCHAR(50),
last_name VARCHAR(50)
);
Relationship Mapping: Defines logical connections between tables that can be used to retrieve related data.
Action Propagation: Specify what action should be taken in the child table when a matching record in the parent table is created,
updated, or deleted.
Cascade Control: Allows operations like deletion or updates to propagate to related tables, maintaining data consistency.
Uniqueness: The referencing column or combination of columns in the child table is unique.
Consistency: Each foreign key in the child table either matches a corresponding primary key or unique key in the parent table or
contains a null value.
Relationship Representation: FKs depict relationships between tables, such as 'One-to-Many' (e.g., one department in a company
can have multiple employees) or 'Many-to-Many' (like in associative entities).
Querying Simplification: They aid in performing joined operations to retrieve related data, abstracting away complex data
relationships.
[Link] 10/19
4/10/25, 3:56 PM GitHub - Devinterview-io/sql-interview-questions: 🟣 SQL interview questions and answers to help you prepare for your next techni…
Parameterized Queries
Description: Also known as a prepared statement, it separates SQL code from user input, rendering direct command injection
impossible.
Code Example:
Java (JDBC):
String query = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement ps = [Link](query);
[Link](1, username);
[Link](2, password);
ResultSet rs = [Link]();
Python (MySQL):
[Link]("SELECT * FROM users WHERE username = %s AND password = %s", (username, password))
Benefits:
Improved security.
Reliability across different databases.
No need for manual escaping.
Stored Procedures
Description: Allows the database to pre-compile and store your SQL code, providing a layer of abstraction between user input and
database operations.
Code Example:
With MySQL:
Procedure definition:
Advantages:
Input Validation
Description: Examine user-supplied data to ensure it meets specific criteria before allowing it in a query.
[Link] 11/19
4/10/25, 3:56 PM GitHub - Devinterview-io/sql-interview-questions: 🟣 SQL interview questions and answers to help you prepare for your next techni…
Code Example: Using regex:
Drawbacks:
Code Filtering
Description: Sanitize incoming data based on its type, like strings or numbers. This approach works best in conjunction with other
methods.
Considerations:
Normalization is a database design method, refining table structures to reduce data redundancy and improve data integrity. It is a
multi-step process, divided into five normal forms (1NF, 2NF, 3NF, BCNF, 4NF), each with specific rules.
Normalization in Action
Let's consider a simplistic "Customer Invoices" scenario, starting from an unnormalized state:
ID Name Invoice No. Invoice Date Item No. Description Quantity Unit Price
In this initial state, all data is stored in a single table without structural cohesion. Each record is a mix of customer and invoice
information. This can lead to data redundancy and anomalies.
To reach 1NF, ensure all cells are atomic, meaning they hold single values. Make separate tables for related groups of data. In our
example, let's separate customer details from invoices and address multiple items on a single invoice.
ID Name
Invoices Table
Items Table
[Link] 12/19
4/10/25, 3:56 PM GitHub - Devinterview-io/sql-interview-questions: 🟣 SQL interview questions and answers to help you prepare for your next techni…
1NF is crucial for efficient database operations, especially for tasks like reporting and maintenance.
To achieve 2NF, consider the context of a complete data entry. Each non-key column should be dependent on the whole primary
key.
In our example, the Items table already satisfies 2NF, as all non-key columns, like Description and Unit Price , depend on the entire
primary key, formed by Invoice No. and Item No. together.
For 3NF compliance, there should be no transitive dependencies. Non-key columns should rely only on the primary key.
README
Here, Customer_ID is the sole attribute associated with the customer.
Practical Implications
Higher normal forms provide stronger data integrity but might be harder to maintain during regular data operations.
Consider your specific application needs when determining the target normal form.
Real-World Usage
Many databases aim for 3NF.
In scenarios requiring exhaustive data integrity, 4NF, and sometimes beyond, are appropriate.
[Link] 13/19
4/10/25, 3:56 PM GitHub - Devinterview-io/sql-interview-questions: 🟣 SQL interview questions and answers to help you prepare for your next techni…
FOREIGN KEY (InvoiceNo) REFERENCES Invoices(InvoiceNo)
);
This code demonstrates the specified 3NF structure with distinct tables for Customer, Invoices, and Items, ensuring data integrity
during operations.
11. Describe the concept of denormalization and when you would use it.
Denormalization involves optimizing database performance by reducing redundancy at the cost of some data integrity.
2. Aggregating Data:
Replicating data from one table in another to reduce the need for joins.
Example: The Customer and Sales tables can both have a Country column, even though the country is indirectly linked
through the Customer table.
Companies often need to run complex reports that span numerous tables.
Denormalization can flatten these tables, making the reporting process more efficient.
In systems where data consistency can be relaxed momentarily, denormalization can speed up operations.
It's commonly seen in e-commerce sites where a brief delay in updating the sales figures might be acceptable for faster
checkouts and improved user experience.
Read-Mostly Applications:
Systems that are heavy on data reads and relatively light on writes can benefit from denormalization.
For example, search engines often store data in a denormalized format to enhance retrieval speed.
Partitioning Data:
In distributed systems like Hadoop or NoSQL databases, data is often stored redundantly across multiple nodes for enhanced
performance.
Maintenance Challenges:
[Link] 14/19
4/10/25, 3:56 PM GitHub - Devinterview-io/sql-interview-questions: 🟣 SQL interview questions and answers to help you prepare for your next techni…
Redundant data must be managed consistently, which can pose challenges.
Operational Simplicity:
Sometimes, having a simple, denormalized structure can outweigh the benefits of granularity and normalization.
Query Flexibility:
A normalized structure can be more flexible for ad-hoc queries and schema changes. Denormalized structures might require
more effort to adapt to such changes.
12. What are indexes and how can they improve query performance?
Indexes are essential in SQL to accelerate queries by providing quick data lookups.
Sorted Data Access: With data logically ordered, lookups are more efficient.
Reduces Disk I/O: Queries may read fewer data pages when using an index.
Enhances Joins: Indexes help optimize join conditions, particularly in larger tables.
Aggregates and Uniques: They can swiftly resolve aggregate functions and enforce data uniqueness.
Index Types
B-Tree: Standard for most databases, arranges data in a balanced tree structure.
Hash: Direct lookup based on a hash of the indexed column.
Bitmap: Best used for columns with a low cardinality.
R-Tree: Optimized for spatial data, such as maps.
Consume Resources: Indexes require disk space and upkeep during data modifications.
Slow Down Writes: Each write operation might trigger updates to associated indexes.
Best Practices
1. Appropriate Index Count: Identify crucial columns and refrain from over-indexing.
2. Monitor and Refactor: Regularly assess index performance and refine or remove redundant ones.
3. Consistency: Ensure all queries access data in a consistent manner to take full advantage of indexes.
4. Data Type Consideration: Certain data types are better suited for indexing than others.
Types of Keys
Primary Key: Uniquely identifies each record in a table.
Foreign Key: Establishes a link between tables, enforcing referential integrity.
Compound Key: Combines two or more columns to form a unique identifier.
[Link] 15/19
4/10/25, 3:56 PM GitHub - Devinterview-io/sql-interview-questions: 🟣 SQL interview questions and answers to help you prepare for your next techni…
Key Functions
Data Aggregation: Collapses rows into summary data.
Filtering: Provides filtering criteria for groups.
Calculated Fields: Allows computation on group-level data.
Usage Examples
Consider a Sales table with the following columns: Product , Region , and Amount .
Data Aggregation
For data aggregation, we use aggregate functions such as SUM , AVG , COUNT , MIN , or MAX .
Filtering
The GROUP BY clause can include conditional statements. For example, to count only those sales that exceed $100 in amount:
Calculated Fields
You can compute derived values for groups. For instance, to find what proportion each product contributes to the overall sales in a
region, use this query:
SELECT Region, Product, SUM(Amount) / (SELECT SUM(Amount) FROM Sales WHERE Region = [Link]) AS RelativeContribution
FROM Sales s
GROUP BY Region, Product;
Performance Considerations
Efficient database design aims to balance query performance with storage requirements. Aggregating data during retrieval can
optimize performance, especially when dealing with huge datasets.
It's essential to verify these calculations for accuracy, as improper data handling can lead to skewed results.
Scalar Subquery
[Link] 16/19
4/10/25, 3:56 PM GitHub - Devinterview-io/sql-interview-questions: 🟣 SQL interview questions and answers to help you prepare for your next techni…
A Scalar Subquery returns a single value. They're frequently used for comparisons—like > , = , or IN .
Examples:
SELECT col1 FROM table1 WHERE col1 = (SELECT MAX(col1) FROM table1);
Checking existence:
SELECT col1, col2 FROM table1 WHERE col1 = (SELECT col1 FROM table2 WHERE condition);
Using aggregates:
SELECT col1 FROM table1 WHERE col1 = (SELECT SUM(col2) FROM table2);
Table Subquery
A Table Subquery is like a temporary table. It returns rows and columns and can be treated as a regular table for further processing.
Examples:
Filtering data:
SELECT * FROM table1 WHERE col1 IN (SELECT col1 FROM table2 WHERE condition);
Data deduplication:
SELECT DISTINCT col1 FROM table1 WHERE condition1 AND col1 IN (SELECT col1 FROM table2 WHERE condition2);
Structured Data: Subqueries can ensure that intermediate data is properly processed, making them ideal for multi-step tasks.
Reduced Code Duplication: By encapsulating certain logic within a subquery, you can avoid repetitive code.
Dynamic Filtering: The data returned by a subquery can dynamically influence the scope of the outer query.
Milestone Calculations: For long and complex queries, subqueries can provide clarity and help break down the logic into
manageable parts.
Versatility: While subqueries are powerful, they can be less flexible in some scenarios compared to other advanced features like
Common Table Expressions (CTEs) and Window Functions.
Understanding and Debugging: Nested logic might make a stored procedure or more advanced techniques like CTEs easier to
follow and troubleshoot.
[Link] 17/19
4/10/25, 3:56 PM GitHub - Devinterview-io/sql-interview-questions: 🟣 SQL interview questions and answers to help you prepare for your next techni…
-- Table Subquery Example
SELECT col1, col2
FROM table1
WHERE col1 = (SELECT col1 FROM table2 WHERE condition);
Key Features
Column-Specific Sorting: You can designate one or more columns as the basis for sorting. For multiple columns, the order of
precedence is from left to right.
ASC and DESC Directives: These allow for both ascending and descending sorting. If neither is specified, it defaults to ascending.
Use Cases
Top-N Queries: Selecting a specific number of top or bottom records can be accomplished using ORDER BY along with LIMIT or
OFFSET.
Trends Identification: With ORDER BY, you can identify trends or patterns in your data, such as ranking by sales volume or time-
based sequences.
Improved Data Presentation: By sorting records in a logical order, you can enhance the visual appeal and comprehension of your
data representations.
The expected result will show the top 3 products with the highest units sold on the given date. If two products have the same number
of units sold, they will be sorted in alphabetical order by their names.
SELECT product_name
FROM products
ORDER BY RAND()
LIMIT 1;
Releases
No releases published
Packages
No packages published
[Link] 19/19