Are you preparing for a SQL interview? SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM in the 1970's, SQL allows us to create, read, update, and delete data with simple yet effective commands. For both newcomers and seasoned professionals, mastering SQL is a must-have skill in today’s data-driven job market
Here, we cover 100 SQL Interview Questions with answers asked in SQL developer interviews at MAANG and other high-paying companies. Whether we’re preparing for our first data-related role or seeking to advance our career, this guide will walk us through the most commonly asked SQL interview questions to help us stand out in competitive job interviews.
SQL Basic Interview Questions"SQL Basic Interview Questions" covers fundamental concepts that are essential for anyone preparing for a SQL interview. Explore these essential questions to build a strong understanding and boost our confidence in SQL basics.
1. What is SQL?SQL (Structured Query Language) is a standard programming language used to communicate with relational databases. It allows users to create, read, update, and delete data, and provides commands to define database schema and manage database security.
2. What is a database?A database is an organized collection of data stored electronically, typically structured in tables with rows and columns. It is managed by a database management system (DBMS), which allows for efficient storage, retrieval, and manipulation of data.
3. What are the main types of SQL commands?SQL commands are broadly classified into:
A primary key is a unique identifier for each record in a table. It ensures that no two rows have the same value in the primary key column(s), and it does not allow NULL values.
6. What is a foreign key?A foreign key is a column (or set of columns) in one table that refers to the primary key in another table. It establishes and enforces a relationship between the two tables, ensuring data integrity.
7. What is the purpose of the DEFAULT constraint?The DEFAULT constraint assigns a default value to a column when no value is provided during an INSERT operation. This helps maintain consistent data and simplifies data entry.
8. What is normalization in databases?Normalization is the process of organizing data in a database to reduce redundancy and improve data integrity. This involves dividing large tables into smaller, related tables and defining relationships between them to ensure consistency and avoid anomalies.
9. What is denormalization, and when is it used?Denormalization is the process of combining normalized tables into larger tables for performance reasons. It is used when complex queries and joins slow down data retrieval, and the performance benefits outweigh the drawbacks of redundancy.
10. What is a query in SQL?A query is a SQL statement used to retrieve, update, or manipulate data in a database. The most common type of query is a SELECT statement, which fetches data from one or more tables based on specified conditions.
11. What are the different operators available in SQL?A view is a virtual table created by a SELECT query. It does not store data itself, but presents data from one or more tables in a structured way. Views simplify complex queries, improve readability, and enhance security by restricting access to specific rows or columns.
13. What is the purpose of the UNIQUE constraint?The UNIQUE constraint ensures that all values in a column (or combination of columns) are distinct. This prevents duplicate values and helps maintain data integrity.
14. What are the different types of joins in SQL?The GROUP BY clause is used to arrange identical data into groups. It is typically used with aggregate functions (such as COUNT, SUM, AVG) to perform calculations on each group rather than on the entire dataset.
17. What are aggregate functions in SQL?Aggregate functions perform calculations on a set of values and return a single value. Common aggregate functions include:
A subquery is a query nested within another query. It is often used in the WHERE clause to filter data based on the results of another query, making it easier to handle complex conditions.
19. What is the difference between the WHERE and HAVING clauses?Indexes are database objects that improve query performance by allowing faster retrieval of rows. They function like a book’s index, making it quicker to find specific data without scanning the entire table. However, indexes require additional storage and can slightly slow down data modification operations.
21. What is the difference between DELETE and TRUNCATE commands?The ORDER BY clause sorts the result set of a query in either ascending (default) or descending order, based on one or more columns. This helps present the data in a more meaningful or readable sequence.
23. What are the differences between SQL and NoSQL databases?A table is a structured collection of related data organized into rows and columns. Columns define the type of data stored, while rows contain individual records.
25. What are the types of constraints in SQL?Common constraints include:
A cursor is a database object used to retrieve, manipulate, and traverse through rows in a result set one row at a time. Cursors are helpful when performing operations that must be processed sequentially rather than in a set-based manner.
27. What is a trigger in SQL?A trigger is a set of SQL statements that automatically execute in response to certain events on a table, such as INSERT, UPDATE, or DELETE. Triggers help maintain data consistency, enforce business rules, and implement complex integrity constraints.
28. What is the purpose of the SQL SELECT statement?The SELECT statement retrieves data from one or more tables. It is the most commonly used command in SQL, allowing users to filter, sort, and display data based on specific criteria.
29. What are NULL values in SQL?NULL represents a missing or unknown value. It is different from zero or an empty string. NULL values indicate that the data is not available or applicable.
30. What is a stored procedure?A stored procedure is a precompiled set of SQL statements stored in the database. It can take input parameters, perform logic and queries, and return output values or result sets. Stored procedures improve performance and maintainability by centralizing business logic.
This section covers moderately complex SQL topics like advanced queries, multi-table joins, subqueries, and basic optimization techniques. These questions help enhance skills for both database developers and administrators, preparing us for more technical SQL challenges in the field.
31. What is the difference between DDL and DML commands?1. DDL (Data Definition Language):
These commands are used to define and modify the structure of database objects such as tables, indexes, and views. For example, the CREATE
command creates a new table, the ALTER
command modifies an existing table, and the DROP
command removes a table entirely. DDL commands primarily focus on the schema or structure of the database.
Example:
CREATE TABLE Employees (
ID INT PRIMARY KEY,
Name VARCHAR(50)
);
2. DML (Data Manipulation Language):
These commands deal with the actual data stored within database objects. For instance, the INSERT
command adds rows of data to a table, the UPDATE
command modifies existing data, and the DELETE
command removes rows from a table. In short, DML commands allow you to query and manipulate the data itself rather than the structure.
Example:
INSERT INTO Employees (ID, Name) VALUES (1, 'Alice');32. What is the purpose of the ALTER command in SQL?
The ALTER
command is used to modify the structure of an existing database object. This command is essential for adapting our database schema as requirements evolve.
A composite primary key is a primary key made up of two or more columns. Together, these columns must form a unique combination for each row in the table. It’s used when a single column isn’t sufficient to uniquely identify a record.
Example:
Consider an Orders table where OrderID
and ProductID
together uniquely identify each record because multiple orders might include the same product, but not within the same order.
CREATE TABLE OrderDetails (34. How is data integrity maintained in SQL databases?
OrderID INT,
ProductID INT,
Quantity INT,
PRIMARY KEY (OrderID, ProductID)
);
Data integrity refers to the accuracy, consistency, and reliability of the data stored in the database. SQL databases maintain data integrity through several mechanisms:
NOT NULL
ensures a column cannot have missing values, FOREIGN KEY
ensures a valid relationship between tables, and UNIQUE
ensures no duplicate values.The UNION
operator combines the result sets of two or more SELECT
queries into a single result set, removing duplicate rows. The result sets must have the same number of columns and compatible data types for corresponding columns.
Example:
SELECT Name FROM Customers37. What is the difference between UNION and UNION ALL?
UNION
SELECT Name FROM Employees;
UNION ALL
is faster than UNION because it doesn’t perform the additional operation of eliminating duplicates.Example:
SELECT Name FROM Customers38. How does the CASE statement work in SQL?
UNION ALL
SELECT Name FROM Employees;
The CASE
statement is SQL’s way of implementing conditional logic in queries. It evaluates conditions and returns a value based on the first condition that evaluates to true. If no condition is met, it can return a default value using the ELSE
clause.
Example:
SELECT ID,39. What are scalar functions in SQL?
CASE
WHEN Salary > 100000 THEN 'High'
WHEN Salary BETWEEN 50000 AND 100000 THEN 'Medium'
ELSE 'Low'
END AS SalaryLevel
FROM Employees;
Scalar functions operate on individual values and return a single value as a result. They are often used for formatting or converting data. Common examples include:
Example:
SELECT LEN('Example') AS StringLength;40. What is the purpose of the COALESCE function?
The COALESCE
function returns the first non-NULL value from a list of expressions. It’s commonly used to provide default values or handle missing data gracefully.
Example:
SELECT COALESCE(NULL, NULL, 'Default Value') AS Result;41. What are the differences between SQL’s COUNT() and SUM() functions?
1. COUNT(): Counts the number of rows or non-NULL values in a column.
Example:
SELECT COUNT(*) FROM Orders;
2. SUM(): Adds up all numeric values in a column.
Example:
SELECT SUM(TotalAmount) FROM Orders;42. What is the difference between the NVL and NVL2 functions?
NVL(Salary, 0)
will replace NULL
with 0
.Example:
SELECT NVL(Salary, 0) AS AdjustedSalary FROM Employees; -- Replaces NULL with 043. How does the RANK() function differ from DENSE_RANK()?SELECT NVL2(Salary, Salary, 0) AS AdjustedSalary FROM Employees; -- If Salary is NULL, returns 0; otherwise, returns Salary.
Example:
SELECT Name, Salary, RANK() OVER (ORDER BY Salary DESC) AS Rank
FROM Employees;
If two employees have the same salary, they get the same rank, but RANK()
will skip a number for the next rank, while DENSE_RANK()
will not.
Example:
SELECT Name, ROW_NUMBER() OVER (ORDER BY Salary DESC) AS RowNum45. What are common table expressions (CTEs) in SQL?
FROM Employees;
A CTE is a temporary result set defined within a query. It improves query readability and can be referenced multiple times.
Example:
WITH TopSalaries AS (46. What are window functions, and how are they used?
SELECT Name, Salary
FROM Employees
WHERE Salary > 50000
)
SELECT * FROM TopSalaries WHERE Name LIKE 'A%';
Window functions allow you to perform calculations across a set of table rows that are related to the current row within a result set, without collapsing the result set into a single row. These functions can be used to compute running totals, moving averages, rank rows, etc.
Example: Calculating a running totalSELECT Name, Salary,47. What is the difference between an index and a key in SQL?
SUM(Salary) OVER (ORDER BY Salary) AS RunningTotal
FROM Employees;
1. Index
LastName
allows quick lookups of rows where the last name matches a specific value.2. Key
Indexing allows the database to locate and access the rows corresponding to a query condition much faster than scanning the entire table. Instead of reading each row sequentially, the database uses the index to jump directly to the relevant data pages. This reduces the number of disk I/O operations and speeds up query execution, especially for large tables.
Example:
CREATE INDEX idx_lastname ON Employees(LastName);
SELECT * FROM Employees WHERE LastName = 'Smith';
The index on LastName
lets the database quickly find all rows matching ‘Smith’ without scanning every record.
Advantages
Disadvantages:
1. Clustered Index:
EmployeeID
is the clustered index, the rows in the table are stored physically sorted by EmployeeID
.2. Non-Clustered Index:
LastName
allows fast lookups by last name even if the table is sorted by another column.Temporary tables are tables that exist only for the duration of a session or a transaction. They are useful for storing intermediate results, simplifying complex queries, or performing operations on subsets of data without modifying the main tables.
1. Local Temporary Tables:
#
(e.g., #TempTable
).2. Global Temporary Tables:
##
(e.g., ##GlobalTempTable
).Example:
CREATE TABLE #TempResults (ID INT, Value VARCHAR(50));52. What is a materialized view, and how does it differ from a standard view?
INSERT INTO #TempResults VALUES (1, 'Test');
SELECT * FROM #TempResults;
A sequence is a database object that generates a series of unique numeric values. It’s often used to produce unique identifiers for primary keys or other columns requiring sequential values.
Example:
CREATE SEQUENCE seq_emp_id START WITH 1 INCREMENT BY 1;54. What are the advantages of using sequences over identity columns?
SELECT NEXT VALUE FOR seq_emp_id; -- Returns 1
SELECT NEXT VALUE FOR seq_emp_id; -- Returns 2
1. Greater Flexibility:
2. Dynamic Adjustment: Can alter the sequence without modifying the table structure.
3. Cross-Table Consistency: Use a single sequence for multiple related tables to ensure unique identifiers across them.
In short, sequences offer more control and reusability than identity columns.
Constraints enforce rules that the data must follow, preventing invalid or inconsistent data from being entered:
CHECK (Salary > 0)
).#
(e.g., #TempTable
).##
(e.g., ##GlobalTempTable
).Example:
CREATE TABLE #LocalTemp (ID INT);57. What is the purpose of the SQL MERGE statement?
CREATE TABLE ##GlobalTemp (ID INT);
The MERGE
statement combines multiple operations INSERT, UPDATE, and DELETE into one. It is used to synchronize two tables by:
Example:
MERGE INTO TargetTable T58. How can you handle duplicates in a query without using DISTINCT?
USING SourceTable S
ON T.ID = S.ID
WHEN MATCHED THEN
UPDATE SET T.Value = S.Value
WHEN NOT MATCHED THEN
INSERT (ID, Value) VALUES (S.ID, S.Value);
1. GROUP BY: Aggregate rows to eliminate duplicates
SELECT Column1, MAX(Column2)
FROM TableName
GROUP BY Column1;
2. ROW_NUMBER(): Assign a unique number to each row and filter by that
WITH CTE AS (
SELECT Column1, Column2, ROW_NUMBER() OVER (PARTITION BY Column1 ORDER BY Column2) AS RowNum
FROM TableName
)
SELECT * FROM CTE WHERE RowNum = 1;
A correlated subquery is a subquery that references columns from the outer query. It is re-executed for each row processed by the outer query. This makes it more dynamic, but potentially less efficient.
Example:
SELECT Name,60. What are partitioned tables, and when should we use them?
(SELECT COUNT(*)
FROM Orders
WHERE Orders.CustomerID = Customers.CustomerID) AS OrderCount
FROM Customers;
Partitioned tables divide data into smaller, more manageable segments based on a column’s value (e.g., date or region). Each partition is stored separately, making queries that target a specific partition more efficient. It is used when
This section covers complex SQL topics, including performance tuning, complex indexing strategies, transaction isolation levels, and advanced query optimization techniques. By tackling these challenging questions, we’ll gain a deeper understanding of SQL, preparing us for senior-level roles and technical interviews.
61. What are the ACID properties of a transaction?ACID is an acronym that stands for Atomicity, Consistency, Isolation, and Durability—four key properties that ensure database transactions are processed reliably.
1. Atomicity:
2. Consistency:
3. Isolation:
4. Durability:
Isolation levels define the extent to which the operations in one transaction are isolated from those in other transactions. They are critical for managing concurrency and ensuring data integrity. Common isolation levels include:
1. Read Uncommitted:
2. Read Committed:
3. Repeatable Read:
4. Serializable:
Example:
SELECT *
FROM Orders WITH (NOLOCK);
This query fetches data from the Orders
table without waiting for other transactions to release their locks.
Deadlocks occur when two or more transactions hold resources that the other transactions need, resulting in a cycle of dependency that prevents progress. Strategies to handle deadlocks include:
1. Deadlock detection and retry:
2. Reducing lock contention:
3. Using proper isolation levels:
4. Consistent ordering of resource access:
A database snapshot is a read-only, static view of a database at a specific point in time.
Example:
CREATE DATABASE MySnapshot ON66. What are the differences between OLTP and OLAP systems?
(
NAME = MyDatabase_Data,
FILENAME = 'C:\Snapshots\MyDatabase_Snapshot.ss'
)
AS SNAPSHOT OF MyDatabase;
1. OLTP (Online Transaction Processing)
2. OLAP (Online Analytical Processing)
1. Live Lock
2. Deadlock
The EXCEPT
operator is used to return rows from one query’s result set that are not present in another query’s result set. It effectively performs a set difference, showing only the data that is unique to the first query.
Example:
SELECT ProductID FROM ProductsSold
EXCEPT
SELECT ProductID FROM ProductsReturned;
Use Case:
Performance Considerations:
EXCEPT
works best when the datasets involved have appropriate indexing and when the result sets are relatively small.Dynamic SQL is SQL code that is constructed and executed at runtime rather than being fully defined and static. In SQL Server: Use sp_executesql
or EXEC.
In other databases: Concatenate query strings and execute them using the respective command for the database platform.
Syntax:
DECLARE @sql NVARCHAR(MAX)
SET @sql = 'SELECT * FROM ' + @TableName
EXEC sp_executesql @sql;
Advantages:
Risks:
Partitioning is a database technique used to divide data into smaller, more manageable pieces.
1. Indexing Strategy:
2. Index Types:
3. Partitioned Indexes:
4. Maintenance Overhead:
5. Monitoring and Tuning:
6. Indexing large tables requires a careful approach to ensure that performance gains from faster queries outweigh the costs of increased storage and maintenance effort.
72. What is the difference between database sharding and partitioning?1. Sharding
2. Partitioning
1. Write Simple, Clear Queries:
2. Filter Data Early:
3. **Avoid SELECT *:
4. Use Indexes Wisely:
5. Leverage Query Execution Plans:
6. Use Appropriate Join Types:
7. Break Down Complex Queries:
8. Optimize Aggregations:
9. Monitor Performance Regularly:
1. Use Execution Plans:
Review the execution plan of queries to understand how the database is retrieving data, which indexes are being used, and where potential bottlenecks exist.
2. Analyze Wait Statistics:
Identify where queries are waiting, such as on locks, I/O, or CPU, to pinpoint the cause of slowdowns.
3. Leverage Built-in Monitoring Tools:
EXPLAIN
, SHOW PROFILE
, and the Performance Schema.EXPLAIN (ANALYZE)
, pg_stat_statements
, and log-based monitoring.4. Set Up Alerts and Baselines:
5. Continuous Query Tuning:
1. Indexing
2. Denormalization
SQL handles recursive queries using Common Table Expressions (CTEs). A recursive CTE repeatedly references itself to process hierarchical or tree-structured data.
Key Components:
Example:
WITH RecursiveCTE (ID, ParentID, Depth) AS (77. What are the differences between transactional and analytical queries?
SELECT ID, ParentID, 1 AS Depth
FROM Categories
WHERE ParentID IS NULL
UNION ALL
SELECT c.ID, c.ParentID, r.Depth + 1
FROM Categories c
INNER JOIN RecursiveCTE r
ON c.ParentID = r.ID
)
SELECT * FROM RecursiveCTE;
1. Transactional Queries:
2. Analytical Queries:
3. Key Differences:
1. Use Distributed Transactions: Implement two-phase commit (2PC) to ensure all participating databases commit changes simultaneously or roll back if any part fails.
2. Implement Eventual Consistency: If strong consistency isn’t required, allow data to become consistent over time. This approach is common in distributed systems where high availability is a priority.
3. Conflict Resolution Mechanisms: Use versioning, timestamps, or conflict detection rules to resolve inconsistencies.
4. Data Replication and Synchronization: Use reliable replication strategies to ensure that changes made in one database are propagated to others.
5. Regular Audits and Validation: Periodically verify that data remains consistent across databases and fix discrepancies as needed.
79. What is the purpose of the SQL PIVOT operator?The PIVOT operator transforms rows into columns, making it easier to summarize or rearrange data for reporting.
Example:
Converting a dataset that lists monthly sales into a format that displays each month as a separate column.
SELECT ProductID, [2021], [2022]80. What is a bitmap index, and how does it differ from a B-tree index?
FROM (
SELECT ProductID, YEAR(SaleDate) AS SaleYear, Amount
FROM Sales
) AS Source
PIVOT (
SUM(Amount)
FOR SaleYear IN ([2021], [2022])
) AS PivotTable;
1. Bitmap Index:
2. B-tree Index:
3. Key Difference:
This section is dedicated to questions that focus on writing and understanding SQL queries. By practicing these examples, we’ll learn how to retrieve, manipulate, and analyze data effectively, building the problem-solving skills needed for real-world scenarios.
81. Write a query to find the second-highest salary of an employee in a table.SELECT MAX(Salary) AS SecondHighestSalary
FROM Employee
WHERE Salary < (SELECT MAX(Salary) FROM Employee);
Explanation:
This query identifies the second-highest salary by selecting the maximum salary that is less than the overall highest salary. The subquery determines the top salary, while the outer query finds the next highest value.
82. Write a query to retrieve employees who earn more than the average salary.SELECT *
FROM Employee
WHERE Salary > (SELECT AVG(Salary) FROM Employee);
Explanation:
This query fetches details of employees whose salary exceeds the average salary. The subquery calculates the average salary, and the main query filters rows based on that result.
83. Write a query to fetch the duplicate values from a column in a table.SELECT ColumnName, COUNT(*)
FROM TableName
GROUP BY ColumnName
HAVING COUNT(*) > 1;
Explanation:
The query uses GROUP BY
to group identical values and HAVING COUNT(*) > 1
to identify values that appear more than once in the specified column.
SELECT *
FROM Employee
WHERE JoiningDate > DATE_SUB(CURDATE(), INTERVAL 30 DAY);
Explanation:
By comparing the JoiningDate
to the current date minus 30 days, this query retrieves all employees who joined within the last month.
SELECT *
FROM Employee
ORDER BY Salary DESC
LIMIT 3;
Explanation:
The query sorts employees by salary in descending order and uses LIMIT 3
to return only the top three earners.
DELETE FROM Employee
WHERE EmployeeID NOT IN (
SELECT MIN(EmployeeID)
FROM Employee
GROUP BY Column1, Column2
);
Explanation:
This query retains only one row for each set of duplicates by keeping the row with the smallest EmployeeID
. It identifies duplicates using GROUP BY
and removes rows not matching the minimum ID.
SELECT *
FROM TableA
INNER JOIN TableB ON TableA.ID = TableB.ID;
Explanation:
An INNER JOIN
is used to find rows present in both tables by matching a common column (in this case, ID
).
SELECT *
FROM Employee
WHERE Name LIKE 'A%' AND Name LIKE '%A';
Explanation:
The query uses LIKE
with wildcard characters to filter rows where the Name
column starts and ends with the letter 'A'.
SELECT DepartmentID, COUNT(*) AS EmployeeCount
FROM Employee
GROUP BY DepartmentID;
Explanation:
By grouping employees by their DepartmentID
and counting rows in each group, the query produces a list of departments along with the employee count.
SELECT *
FROM Employee
WHERE ManagerID IS NULL;
Explanation:
This query selects employees whose ManagerID
column is NULL
, indicating they don’t report to a manager.
WITH SalaryRank AS (
SELECT Salary, RANK() OVER (ORDER BY Salary DESC) AS Rank
FROM Employee
)
SELECT Salary
FROM SalaryRank
WHERE Rank IN (3, 4);
Explanation:
This query uses the RANK() window function to rank the salaries in descending order. The outer query then selects the 3rd and 4th highest salaries by filtering for those ranks.
92. Write a query to transpose rows into columns.SELECT
MAX(CASE WHEN ColumnName = 'Condition1' THEN Value END) AS Column1,
MAX(CASE WHEN ColumnName = 'Condition2' THEN Value END) AS Column2
FROM TableName;
Explanation:
This query converts specific row values into columns using conditional aggregation with CASE
. Each column’s value is determined based on a condition applied to rows.
SELECT *
FROM TableName
WHERE UpdatedAt >= NOW() - INTERVAL 1 HOUR;
Explanation:
By comparing the UpdatedAt
timestamp to the current time minus one hour, the query retrieves rows updated in the last 60 minutes.
SELECT *
FROM Employee
WHERE DepartmentID IN (
SELECT DepartmentID
FROM Employee
GROUP BY DepartmentID
HAVING COUNT(*) < 5
);
Explanation:
The subquery counts employees in each department, and the main query uses those results to find employees working in departments with fewer than 5 members.
95. Write a query to check if a table contains any records.SELECT CASE
WHEN EXISTS (SELECT * FROM TableName) THEN 'Has Records'
ELSE 'No Records'
END AS Status;
Explanation:
The query uses EXISTS
to determine if any rows exist in the table, returning a status of 'Has Records' or 'No Records' based on the result.
SELECT e.EmployeeID, e.Salary
FROM Employee e
JOIN Employee m ON e.ManagerID = m.EmployeeID
WHERE e.Salary > m.Salary;
Explanation:
This query joins the Employee
table with itself to compare employee salaries to their respective managers’ salaries, selecting those who earn more.
WITH RowNumbered AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
FROM Employee
)
SELECT *
FROM RowNumbered
WHERE RowNum % 2 = 0;
Explanation:
This query assigns a sequential number to each row using ROW_NUMBER()
, then selects rows where the row number is even, effectively fetching alternating rows. The ORDER BY (SELECT NULL)
is used to avoid any specific ordering and just apply a sequential numbering.
SELECT DepartmentID
FROM Employee
GROUP BY DepartmentID
ORDER BY AVG(Salary) DESC
LIMIT 1;
Explanation:
Grouping by DepartmentID
and ordering by the average salary in descending order, the query returns the department with the highest average.
WITH OrderedEmployees AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
FROM Employee
)
SELECT *
FROM OrderedEmployees
WHERE RowNum = n;
Explanation:
This query uses ROW_NUMBER() to generate a sequential number for each row. The outer query then retrieves the row where the number matches the desired nth
position. The approach is portable across most databases.
SELECT *
FROM Employee
WHERE MONTH(JoiningDate) = MONTH(CURDATE());
Explanation:
By comparing the month of JoiningDate
to the current month, the query selects all employees who were hired in that month regardless of the year.
A solid understanding of SQL is essential for anyone aspiring to work in data analysis, database administration, or software development. By reviewing and practicing these 100 SQL interview questions, we will gain the confidence and knowledge needed to answer even the toughest queries during our next interview. Remember, preparation is the key because each question we master brings us closer to securing that dream job in the tech industry.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4