MetricMinds.
in
SQL
Interview
Question
If you’re an aspiring data analytics fresher preparing for your upcoming SQL
interview, then you need this guide to prepare. Here are 50 SQL Interview Questions
from Beginner to Advance.
Happy Learning!
Copyright by MetricMinds.in
SQL Interview Question
Beginner Level
1. What is Database?
Answer:
A database is an organized collection of data, stored and retrieved digitally
from a remote or local computer system.
2. What is SQL and what does it stand for?
Answer:
SQL (Structured Query Language) is a standard programming language
specifically designed for managing and manipulating relational databases. It is
used for querying, updating, and managing data stored in relational databases.
3. Explain the difference between SQL and MySQL.
Answer:
SQL is a language for querying databases, while MySQL is a relational
database management system (RDBMS) that uses SQL to manage databases.
MySQL is an open-source RDBMS.
4. What is a primary key?
Answer:
A primary key is a field or combination of fields that uniquely identifies each
record in a table. It ensures that no two rows have the same primary key value
and that the value is never NULL.
Page : 01 Copyright by MetricMinds.in
5. What is a foreign key?
Answer:
A foreign key is a field or a set of fields in one table that uniquely identifies a
row in another table. It establishes a relationship between the two tables and
enforces referential integrity.
6. What is a unique key?
Answer:
A Unique key constraint uniquely identified each record in the database. This
provides uniqueness for the column or set of columns.
A Primary key constraint has automatic unique constraint defined on it. But
not, in the case of Unique Key.
There can be many unique constraint defined per table, but only one Primary
key constraint defined per table.
Primary Key Candidate Key
Foreign Key
Empld EmpName EmpLicence EmpPassport DId DId Designation
1 BPO
1001 Matt LC1201 MA100LC
1
2 Account
1002 Maxy LC2078 XY100LC2 2
3 IT
1003 Roy LK00928 LK100RO 3
TABLE-2
TABLE-1 Alternate Key
Primary Key Candidate Key Alternate Key
Unique Key
Super Key
Page : 02 Copyright by MetricMinds.in
7. What are the different types of SQL commands?
Answer:
Data Definition Language (DDL)
Defines & modifies the structure of database objects like tables & indexes.
Create Update Delete Drop Insert Alter Merge
Data Manipulation Language (DML)
Manages and manipulates data within tables, including inserting, updating,
and deleting records.
Update Delete Insert Merge
Data Control Language (DCL)
Control access to data in the database, ensuring security and proper
permissions.
GRANT REVOKE
Transaction Control Language (TCL)
Manage transactions within a database to ensure data integrity and
handle errors.
COMMIT ROLLBACK SAVEPOINT SET TRANSACTION
Data Query Language (DQL)
Primarily used for querying the database to retrieve data.
select
Page : 03 Copyright by MetricMinds.in
8. What are tables and Fields?
Answer:
A table is a set of data that are organized in a model with Columns and Rows.
Columns can be categorized as vertical, and Rows are horizontal.
A table has specified number of column called fields but can have any
number of rows which is called record.
Field Empld EmpName EmpLicence EmpPassport DId
1001 Matt LC1201 MA100LC
1
1002 Maxy LC2078 XY100LC2 2 Data
1003 Roy LK00928 LK100RO 3
Table : Employee
9. What is the difference between WHERE and HAVING
clauses?
Answer:
WHERE filters records before any groupings are made, while HAVING filters
groups after the GROUP BY clause.
Where Clause :
SELECT S_Name, Age FROM Student
WHERE Age >=18;
have Clause :
SELECT Age, COUNT(Roll_No) AS No_of_Students
FROM Student GROUP BY Age
HAVING COUNT(Roll_No) > 1;
Page : 04 Copyright by MetricMinds.in
10. How do you retrieve unique records from a table?
Answer:
Use the DISTINCT keyword to eliminate duplicate rows.
SELECT DISTINCT column_name
FROM table_name;
11. How do you sort the result set in SQL?
Answer:
Use the ORDER BY clause to sort the result set by one or more columns.
SELECT * FROM table_name
ORDER BY column_name ASC/DESC;
12. Explain the use of the SELECT statement.
Answer:
The SELECT statement is used to query and retrieve data from a database.
SELECT column1, column2
FROM tables_name;
13. What is a NULL value in SQL?
Answer:
A NULL value represents missing or undefined data. It is different from an
empty string or a zero value.
Page : 05 g e
Copyri ht by M tricMinds.in
13. How do you insert data into a table?
Answer:
Use the INSERT INTO statement to add new rows to a table.
INSERT INTO table_name (column1, column2)
VALUES (value1, value2);
14. How do you update data in a table?
Answer:
Use the UPDATE statement to modify existing rows in a table.
UPDATE table_name SET column1 = value1
WHERE condition;
15. How do you handle NULL values in SQL?
Answer:
Use functions like IS NULL, IS NOT NULL, COALESCE(), or IFNULL() to
handle NULL values.
SELECT column_name,
FROM table_name
WHERE column_name IS NULL;
16. What is a query?
Answer:
A DB query is a code written in order to get the information back from
the database. Simply, a question to the Database.
Page : 06 Copyright by MetricMinds.in
17. What is the difference between DELETE and TRUNCATE
commands?
Answer:
DELETE removes rows based on a condition and can be rolled back if used
within a transaction.
TRUNCATE removes all rows from a table without logging individual row
deletions and cannot be rolled back.
18. What is a View?
Answer:
A view is a virtual table which consists of a subset of data contained in a table.
Views are not virtually present, and it takes less space to store. View can have
data of one or more tables combined, and it is depending on the relationship.
19. What is an Index?
Answer:
An index is performance tuning method of allowing faster retrieval of records
from the table. An index creates an entry for each value and it will be faster to
retrieve data.
20. What is Join?
Answer:
This is a keyword used to query data from more tables based on the
relationship between the fields of the tables. Keys play a major role when
JOINs are used.
Page : 07 Copyright by MetricMinds.in
21. What are the types of join and explain each?
Answer:
There are various types of join which can be used to retrieve data and it depends
on the relationship between tables.
Inner join
Inner join return rows when there is at least one match of rows between the
tables.
1 1
VAL_Y
INNER JOIN
VAL X
KEY
X1 2 2 Y1
4 Y2 SELECT
X2 3 <SELECT LIST>
Y3 FROM
1
X1 Y1
X3 TABLE_A A
INNER JOIN TABLE_B B
2 X2 Y2
ON A.KEY = B.KEY
Right Join
Right join return rows which are common between the tables and all rows of
Right hand side table. Simply, it returns all the rows from the right hand side
table even though there are no matches in the left hand side table.
1 VAL_Y
VAL X
1
KEY
X1 2 RIGHT JOIN
2 Y1
X2 3
4 Y2 SELECT
1
X1 Y1
X3 <SELECT LIST>
LL Y3 FROM
2 X2 Y2
NU TABLE_A A
RIGHT JOIN TABLE_B B
ON A.KEY = B.KEY
4 NULL Y3
Page : 08 Copyright by MetricMinds.in
Left Join
Left join return rows which are common between the tables and all rows of
Left hand side table. Simply, it returns all the rows from Left hand side table
even though there are no matches in the Right hand side table.
VAL_Y
VAL X
1 2 Y1 LEFT JOIN
KEY
X1 2 4 Y2
SELECT
1
X1 Y1
X2 3 Y3 <SELECT LIST>
NU FROM
X2 Y2
X3 LL TABLE_A A
2
LEFT JOIN TABLE_B B
ON A.KEY = B.KEY 3 X3 NULL
Full Join
Full join return rows when there are matching rows in any one of the tables.
This means, it returns all the rows from the left hand side table and all the
rows from the right hand side table.
1
VAL_Y
1
VAL X
KEY
X1 2 2 Y1
4 Y2 FULL OUTER JOIN
X2 3 1
X1 Y1
Y3
X3 NU SELECT
2 X2 Y2
ULL LL <SELECT LIST>
N FROM
TABLE_A A
3 X3 NULL
FULL OUTER JOIN TABLE_B B
ON A.KEY = B.KEY 4 NULL Y3
Page : 09 Copyright by MetricMinds.in
SQL Interview Question
Intermediate Level
22. What are the different types of indexes?
Answer:
There are three types of indexes -.
Unique Index
This indexing does not allow the field to have duplicate values if the column is
unique indexed. Unique index can be applied automatically when primary key is
defined.
Clustered Index
This type of index reorders the physical order of the table and search based on
the key values. Each table can have only one clustered index.
Non-Clustered Index
NonClustered Index does not alter the physical order of the table and maintains
logical order of data. Each table can have 999 nonclustered indexes.
Page : 10 Copyright by MetricMinds.in
23. What is a self-join?
Answer:
A self-join is a regular join but the table is joined with itself.
SELECT a.column_name, b.column_name
FROM table_name a, able_name b
WHERE a.common_field = b.common_field;
24. Explain the difference between an INNER JOIN and an
OUTER JOIN.
Answer:
INNER JOIN returns only matching rows from both tables.
OUTER JOIN returns matching rows and unmatched rows from one or both
tables, depending on whether it is a LEFT, RIGHT, or FULL outer join.
25. Explain the difference between a stored procedure
and a function.
Answer:
A stored procedure performs a task but doesn't return a value. A function
performs a calculation and returns a value. Functions can be used in
SQL expressions; procedures cannot.
26. What are aggregate functions? List some examples.
Answer:
Aggregate functions perform a calculation on a set of values and return
a single value. Examples include SUM(), AVG(), COUNT(), MAX(), MIN().
Page : 11 Copyright by MetricMinds.in
27. What is a subquery? Provide an example.
Answer:
A subquery is a query within another query. It can be used in SELECT, INSERT,
UPDATE, or DELETE statements.
SELECT column_name
FROM table_name
WHERE column_name = (SELECT column_name
FROM table_name WHERE condition);
28. How do you find the second highest salary in a table?
Answer:
A Use the LIMIT clause with ORDER BY.
SELECT salary
FROM employees
ORDER BY salary DESC limit 1 OFFSET 1;
29. What is a UNION? How does it differ from UNION ALL?
Answer:
UNION combines results from two queries and removes duplicates.
UNION ALL includes duplicates.
SELECT column_name FROM column1
UNION
SELECT column_name FROM column2;
Page : 12 Copyright by MetricMinds.in
30. How do you use the CASE statement in SQL?
Answer:
CASE is used to provide conditional logic in a query.
SELECT column_name,
CASE
WHEN condition1 THEN ‘result1’
WHEN condition2 THEN ‘result2’
ELSE ‘result3’
END
FROM table_name;
31. Explain the difference between COUNT, SUM, AVG, MAX,
and MIN functions.
Answer:
COUNT counts the number of rows, SUM calculates the total, AVG
calculates the average, MAX finds the maximum value, MIN finds the
minimum value
SELECT COUNT(*), SUM (column_name), AVG(column_name),
MAX(column_name), MIN(column_name)
FROM(table_name);
32. What is data Integrity?
Answer:
Data Integrity defines the accuracy and consistency of data stored in a
database. It can also define integrity constraints to enforce business rules on
the data when it is entered into the application or database.
Page : 13 Copyright by MetricMinds.in
33. Explain the use of the GROUP BY clause.
Answer:
GROUP BY is used to arrange identical data into groups.
SELECT column_name, COUNT(*)
FROM table_name
GROUP BY column_name;
34. What are triggers? Provide an example.
Answer:
Triggers are automatic actions performed when specified events occur
in a database.
CREATE TRIGGER trigger_name
AFTER INSERT ON table_name
FOR EACH ROW
BEGIN
--Trigger logic
END;
35. What is normalization?
Answer:
Normalization is the process of minimizing redundancy and dependency by
organizing fields and table of a database. The main aim of Normalization is to
add, delete or modify field that can be made in a single table.
Page : 14 Copyright by MetricMinds.in
36. What is denormalization?
Answer:
DeNormalization is a technique used to access the data from higher to lower
normal forms of database. It is also process of introducing redundancy into a
table by incorporating data from the related tables
37. What are all the different normalizations?
Answer:
The normal forms can be divided into 5 forms, and they are explained below -.
First Normal Form (1NF)
This should remove all the duplicate columns from the table. Creation of tables
for the related data and identification of unique columns.
Second Normal Form (2NF)
Meeting all requirements of the first normal form. Placing the subsets of data
in separate tables and Creation of relationships between the tables using
primary keys.
Third Normal Form (3NF)
This should meet all requirements of 2NF. Removing the columns which are not
dependent on primar y key constraints.
Fourth Normal Form (3NF)
Meeting all the requirements of third normal form and it should not have multi-
valued dependencies.
Page : 15 Copyright by MetricMinds.in
SQL Interview Question
Advanced Level
38. What are window functions in SQL? Provide an example.
Answer:
Window functions perform calculations across a set of table rows
related to the current row, providing ranking, aggregating, and offset
functionalities.
SELECT column_name,
ROW_NUMBER ()
OVER (PARTITION BY partition_column ORDER BY order_column)
AS row_FROM table_name;
39. How do you optimize a SQL query for performance?
Answer:
Optimize by using indexes, avoiding unnecessary columns in SELECT,
avoiding wildcards in SELECT, using appropriate JOINs, and ensuring
proper use of WHERE clauses.
40. Explain the concept of partitioning in SQL.
Answer:
Partitioning divides a large table into smaller, more manageable pieces,
improving performance and manageability.
Page : 16 Copyright by MetricMinds.in
41. What is the difference between OLTP and OLAP systems?
Answer:
OLTP (Online Transaction Processing) systems are used for transactional
tasks with quick, short queries, typically involving inserts, updates, and deletes.
OLAP (Online Analytical Processing) systems are used for complex queries
and data analysis, often involving large datasets and aggregations.
42. What are the differences between SQL and NoSQL
databases?
Answer:
SQL databases are relational and use structured query language for
defining and manipulating data. They are table-based.
NoSQL databases are non-relational, can be document-based, key-value
pairs, graph databases, and are designed for distributed data stores.
43. Explain the difference between ROW_NUMBER(), RANK(),
and DENSE_RANK() functions.
Answer:
ROW_NUMBER() assigns unique numbers to rows. RANK() assigns ranks
with gaps for ties. DENSE_RANK() assigns ranks without gaps for ties.
SELECT column_name,
ROW_number () over (order by column_name),
RANK () over (order by column_name),
DENSE_RANK () over (order by column_name),
FROM table_name;
Page : 17 Copyright by MetricMinds.in
44. What is a materialized view?
Answer:
A materialized view stores the result of a query physically, unlike a regular view
that runs the query each time it's accessed. It can be refreshed to update the
data.
45. Explain the concept of sharding in databases.
Answer:
Sharding distributes data across multiple databases to improve performance
and scalability. Each shard is a separate database and can be managed
independently.
46. How do you manage and work with large datasets in
SQL?
Answer:
Use indexing, partitioning, and efficient query practices. Avoid unnecessary
j oins and complex queries that can slow down performance.
47. How do you ensure data integrity in SQL databases?
Answer:
Use constraints like primary keys, foreign keys, unique constraints, and check
constraints. Implement ACID properties and proper indexing.
48. What are the best practices for writing efficient SQL
queries?
Page : 18 Copyright by MetricMinds.in
Answer:
Use appropriate indexing, limit the number of columns in SELECT, use WHERE
clauses to filter data, avoid wildcard characters, and optimize JOIN operations.
49. What is data warehousing and how is it related to SQL?
Answer:
Data warehousing is the process of storing and managing large volumes of
data from different sources for analysis and reporting. SQL is used to query,
analyze, and manage this data.
50. How do you handle transactions in SQL?
Answer:
Use BEGIN TRANSACTION, COMMIT, and ROLLBACK to manage transactions.
BEGIN TRANSACTION;
-- SQL Statements
COMMIT;
51. Explain the use of the EXPLAIN command.
Answer:
EXPLAIN shows the execution plan of a SQL query, helping to understand
and optimize query performance.
EXPLAIN SELECT * FROM table_name
WHERE condition_name;
Page : 19 Copyright by MetricMinds.in
52. What is data warehousing and how is it related to SQL?
Answer:
Data warehousing is the process of storing and managing large volumes of
data from different sources for analysis and reporting. SQL is used to query,
analyze, and manage this data.
53. How do you handle transactions in SQL?
Answer:
Use BEGIN TRANSACTION, COMMIT, and ROLLBACK to manage transactions.
BEGIN TRANSACTION;
-- SQL Statements
COMMIT;
54. How do you perform error handling in SQL?
Answer:
Use TRY...CATCH blocks for error handling.
BEGIN TRY;
-- SQL Statements
END TRY
BEGIN CATCH
-- Error handling
END CATCH
55. Explain the use of the MERGE statement.
Page : 20 Copyright by MetricMinds.in
Answer:
MERGE allows you to perform INSERT, UPDATE, or DELETE operations in a
single statement.
MERGE INTO target_table USING source_table
ON target_table.id = source_table.id
WHEN MATCHED THEN
UPDATE SET target_table.column_name = source_table.column_name
WHEN NOT MATCHED THEN
INSERT (column_name) VALUES (source_table.column_name);
56. How do you implement recursive queries in SQL?
Answer:
Use recursive CTEs.
WITH RECURSIVE CTE_name AS (
SELECT column_name
FROM table_name
WHERE condition
UNION ALL
SELECT column_name
FROM table_name
JOIN CTE_name ON condition
SELECT * FROM CTE_name;
57. Explain the concept of a CTE (Common Table
Expression) with an example.
Page : 21 Copyright by MetricMinds.in
Answer:
A CTE is a temporary result set that can be referenced within a SELECT,
INSERT, UPDATE, or DELETE statement.
WITH CTE_name AS (
SELECT column_name
FROM table_name
WHERE condition
SELECT * FROM CTE_name;
58. What is ACID property in the context of databases?
Answer:
ACID stands for Atomicity, Consistency, Isolation, Durability. These
properties ensure reliable transactions
Atomicity: Ensures that all operations within a transaction are
completed successfully
Consistency: Ensures that the database remains in a consistent
state before and after the transaction
Isolation: Ensures that transactions are isolated from each other
Durability: Ensures that once a transaction is committed, it remains
committed.
Page : 22 Copyright by MetricMinds.in
Who We Are!
At MetricMinds.in, we are passionate about data and its transformative potential
for businesses of all sizes. Our journey began with a vision to democratize
analytics, making powerful insights accessible to everyone.
With a commitment to excellence and innovation, we've established ourselves as
a trusted partner for organizations seeking to harness the full power of their
data.
We provide consulting, implementations, and training services to optimize your
data potential. Our team of industry veterans ensures that your work is done
right, the first time.
Our Mission is Two-Fold :
To empower students, freshers, and early professionals to become
employable in data analytics roles faster.
To empower businesses with actionable insights that drive growth,
innovation & success.
get started with
MetricMinds.in
Dr. Jayen Thakker
Founder at MetricMinds.in
x.com/JayenThakker
[email protected] linkedin.com/in/jayen/
www.MetricMinds.in instagram.com/dr.jayenthakker/
Wanna
Become
Top 1%
of Data
Analysts?
DM “1%” for 1:1 Consultation