Post thumbnail
INTERVIEW

Top 30 SQL Interview Questions with Answers

By Roopa Dharshini

Welcome to the last-minute guide to ace your SQL interview! Whether you are preparing for your first SQL interview or aiming to level up in your current database-related role, mastering SQL is essential for success. 

This blog lists top 30 SQL interview questions with answers, covering a wide range of SQL concepts from beginner to advanced level. From theoretical concepts to query writing, each question is explained in detail to ensure you’re fully prepared. Let’s jump into it. 

Table of contents


  1. Beginner's SQL Interview Questions
  2. Intermediate SQL Interview Questions
  3. Advanced SQL Interview Questions
  4. FAQs
    • Q1. What is normalization, and why is it important in database design?
    • Q2. What is the importance of learning SQL for a database professional?
    • Q3. How do I improve my SQL skills?

Beginner’s SQL Interview Questions

Let’s start with the basic level SQL interview questions for beginners. If you’re a beginner in SQL or applying to an entry-level job, then you can expect more theoretical SQL interview questions. This includes questions on databases and their types, SQL applications, statements, commands, and types of queries. Let’s dive deeper into the detailed answers for these SQL interview questions.

  1. What is SQL?

SQL stands for Standard Query Language. It is a programming language used to interact with Relational Databases. This is a popular query language that helps in fetching, updating, deleting and inserting data from and to the databases.

  1. What is a database?

A database is a structured collection of data that is stored electronically. It can store data in the form of numbers, texts, images, videos, and other types of data. Databases serve as a backbone to most of the modern applications, from e-commerce to social networking platforms and also in enterprise applications.

  1. What is a DBMS with some examples?

DBMS stands for database management system. It is a software system that is used to manage the databases and handle the data stored inside the databases. Examples of DBMS include MySQL, Oracle, PostgreSQL for relational databases, and MongoDB for non-relational databases.

  1. What is the difference between SQL and NoSQL?

SQL: SQL is are relational databases that use a predefined schema for storing data in structured tables. It uses horizontal scaling and SQL query language for CRUD operations. Examples for SQL databases include MySQL, Oracle, and PostgreSQL.

NoSQL: NoSQL is are non-relational databases that use a flexible schema for storing data in non-structured formats such as JSON and graphs. It uses vertical scaling and APIs for CRUD operations. Examples for NoSQL databases include MongoDB, Cassandra, and Redis.

  1. What are the types of SQL statements?
SQL Interview questions

SQL statements are also known as commands that are used to modify, create, and delete data from the databases. There are five types of commands in SQL.

  • Data Definition Language (DDL): These commands are used to define and modify the structure of the database and tables.
  • Data Manipulation Language (DML): These commands are used to manipulate and modify data present in the tables.
  • Data Control Language (DCL): These commands are used to control the user access to the database/table by providing or revoking access.
  • Transaction Control Language (TCL): These commands are used to control the transactions that happen in the databases.
  • Data Query Language (DQL): This command is used to perform queries on the data present in the table.
  1. Give some examples of common SQL commands
  • DDL: This includes commands such as CREATE, ALTER, DROP, TRUNCATE, and RENAME.
  • DML: This includes commands such as SELECT, INSERT, UPDATE, and DELETE.
  • DCL: This includes commands such as GRANT and REVOKE.
  • TCL: It includes commands such as COMMIT, ROLLBACK, SAVEPOINT, and SET TRANSACTION.
  • DQL: It includes the command SELECT.
  1. What is the difference between a primary key and a foreign key?

Primary Key: A primary key is a field in a table that uniquely identifies each row in the table. The main constraint of the primary key is that it must contain unique values, and it cannot have NULL values. Each table has only one primary key. Example: Student’s ROLL NUMBER.

Foreign Key: A foreign key is a field in one table that uniquely identifies a row in another table. It creates a relationship between two tables by linking to the primary key of the other table. It may or may not have NULL values. Example: Student’s COURSE_ID.

  1. What is a join?

A Join in SQL is used to combine data from two or more tables based on common or related columns between them. This can retrieve records from multiple tables using a single query. 

  1. What are tables and fields in SQL?

Tables: A table is a collection of rows and columns. It is a fundamental unit of storage in relational databases. Each table represents an entity, for example: Students, Employees, etc.

Fields: A field is also known as a column in SQL. It is a single piece of data stored in a table. It defines a type to the data stored in the column, such as integer, string or date. Example: StudentID, EmployeeID, etc.

  1. What is RDBMS?

RDBMS stands for Relational Database Management System. It is a subset of the database management system (DBMS), it only stores structured data such as tables. RDBMS defines relationships between tables through the concept of foreign keys. It is based on the relational model of data, where tables represent data and relationships among them. Examples of popular RDBMS include MySQL, PostgreSQL, Oracle and SQL server.

If you’re curious about learning SQL, then why are you wasting your time? Start your SQL journey from Guvi’s course on MySQL. This course provides a detailed knowledge of SQL from basic to advanced levels by leveraging the MySQL database. You will also gain industry-recognized certifications and hands-on experience in creating databases and building real-world projects.

MDN

Intermediate SQL Interview Questions

This section will cover intermediate SQL interview questions with answers that cover concepts such as functions, CRUD operations, joins, and constraints with sample SQL queries. So, stay tuned!

  1. What are the types of joins? Explain with examples.
Types of SQL Joins

There are five types of joins in SQL. They are:

  • INNER JOIN: This join returns only the rows that have matching values (common values) in both tables.

Example query

SELECT Employees.Name, Orders.OrderDate
FROM Employees
INNER JOIN Orders ON Employees.EmployeeID = Orders.EmployeeID;

This returns only the employees who placed the orders.

  • LEFT JOIN: It is also known as LEFT OUTER JOIN. It returns all the rows from the left table and only returns the matching rows from the right table. If there are no matching rows, then NULL values are returned from the right table.

Example query

SELECT Employees.Name, Orders.OrderDate
FROM Employees
LEFT JOIN Orders ON Employees.EmployeeID = Orders.EmployeeID;

This will return all employees who placed orders, and for those without orders, the OrderDate will be null.

  • RIGHT JOIN: It is also known as RIGHT OUTER JOIN. This join returns all the rows from the right table and only returns the matching rows from the left table. If there are no matching rows, it will return NULL values from the left table.

Example query

SELECT Employees.Name, Orders.OrderDate
FROM Employees
RIGHT JOIN Orders ON Employees.EmployeeID = Orders.EmployeeID;

This will return all the orders, employees without orders, the employee name will be NULL values.

  • FULL JOIN: It is also known as FULL OUTER JOIN. This join returns all rows from both the left and right tables if there is a match between either of the left or right tables. No matching rows will return NULL values.

Example query

SELECT Employees.Name, Orders.OrderDate
FROM Employees
FULL JOIN Orders ON Employees.EmployeeID = Orders.EmployeeID;

This will return all the values from both the employees and the orders table, even if there is no match.

  • SELF JOIN: This will join a table with itself. It is used to compare the rows within the same table.
  1. What is an index and its types?
Types of SQL Indexes

The index is an object that is used to improve the speed of data retrieval operations on a table. It is created on a table’s one or two columns to quickly find the rows based on those columns.

There are 6 types of indexes. They are

  • Unique Index: It ensures that all the values in the index are unique. It is automatically created when a unique constraint is applied.
    • Example: CREATE UNIQUE INDEX id ON Student(StId);
  • Non-Unique Index: It doesn’t enforce uniqueness, and it can store duplicate values.
    • Example: CREATE INDEX id ON Student(StId);
  • Composite Index: It is a type of index that is created on multiple columns in a table.
    • Example: CREATE INDEX id ON Student(StId, StName);
  • Clustered Index: It reorganizes the data of the table based on the indexed column and it stores the data in the index’s order.
  • Non-Clustered Index: It stores a separate copy of the indexed columns and pointers to the table’s data without altering the data structure of the table.
  • Full Text Index: It is an index used for indexing large text fields for faster search results.
  1. How to create a table?

A table in SQL can be created using the CREATE keyword. The syntax for creating a table is given below:

CREATE TABLE table_name(
column1 datatype constraint,
column2 datatype constraint,

);

Example query:

CREATE TABLE Students(
StudentID INT PRIMARY KEY,
Name VARCHAR(100),
Age INT,
Address VARCHAR(100)
);
  1. What are CRUD Operations? Explain with examples.

CRUD stands for Create, Read, Update, and Delete, which are the four basic operations for managing data in a database.

  • Create: It is used to create a table and insert new records into the table.
  • Read: It is used to retrieve records from the table (SELECT * FROM Students;).
  • Update: It is used to modify the existing records in the table (UPDATE Students SET Age = 21 WHERE StudentID = 3;).
  • Delete: It removes the records from a table (DELETE FROM Students WHERE StudentID = 1;).
  1. What are aggregate functions? Give some examples of functions.
Various aggregate functions

Aggregate functions are used to perform calculations against a column and return a single value as a result. Some of the examples for aggregate functions include:

  • COUNT(): Returns the number of rows.
  • SUM(): Return the sum of the values in a column.
  • AVG(): Returns the average of a column.
  • MIN(): Returns the minimum value in a column.
  • MAX(): Returns the maximum value in a column.
  1. What is the difference between SQL and PL/SQL?

SQL: Standard Query Language (SQL) is a declarative language used to query and manipulate relational databases. It interacts with the database to perform operations like retrieving, updating and deleting data.

PL/SQL: Procedural Language/SQL (PL/SQL) is an extension of SQL provided by Oracle. It allows us to write procedural code which includes looping statements, conditions, variables, and exception handling. 

  1. What is a composite key?

A composite key is a primary key that consists of more than one column. It is used when a single column is not sufficient to uniquely identify a row in a table.

Example query

CREATE TABLE Orders(
OrderID INT,
ProductID INT,
Quantity INT,
PRIMARY KEY (OrderID, ProductID);
);
  1. What is the difference between DELETE and TRUNCATE?
DELETETRUNCATE
It is used to delete one record at a time and can be rolled back when needed.It removes all the rows from a table and cannot be rolled back.
It is slower for larger datasets.It is faster for larger datasets.
DELETE FROM Students WHERE StudentID = 1;TRUNCATE TABLE Students;
  1. What is the difference between DROP and TRUNCATE?
DROPTRUNCATE
It completely removes a table with its structure and data from the database.It removes all the rows from the table but the structure of the table retains the same.
It cannot be rolled back.It cannot drop a table.
DROP TABLE Students;TRUNCATE TABLE Students;
  1. What are constraints, and give some examples of constraints?

Constraints are the rules applied to columns in a table to ensure data integrity, uniqueness, and correctness. There are various types of constraints, some of which are:

  • PRIMARY KEY: It uniquely identifies each record in the table.
  • FOREIGN KEY: It ensures values from one table match of another table. It handles the relationship between tables.
  • NOT NULL: It ensures that a column cannot have a NULL value.
  • DEFAULT: It sets a default value for a column if no value is provided.

Advanced SQL Interview Questions

This section will cover the advanced SQL interview questions. This includes advanced concepts such as stored procedures, cursors, transaction protocols, normalization techniques, and writing queries based on requirements. Let’s dive into the SQL interview questions.

  1. What is a stored procedure?

A stored procedure is a set of SQL statements that can be stored in a database and executed as a single unit of code. This is used to access the set of instructions repeatedly without writing the code multiple times. It can accept input parameters and return values.

Example query

CREATE PROCEDURE GetEmployeeDetails (IN empId INT)
BEGIN
SELECT * FROM Employees WHERE EmployeeID = empId;
END;
CALL GetEmployeeDetails (101);
  1. What are the differences between OLTP and OLAP?

OLTP: Online Transaction Processing (OLTP) deals with day-to-day transaction data. It focuses on faster processing of insertion, updation, and deletion operations. Example: Banking systems and order processing.

OLAP: Online Analytical Processing (OLAP) is used for complex queries and analysis that often involves large amounts of historical data. It focuses on read-heavy operations and aggregation of data. Example: Business intelligence and reporting systems.

  1. What is a subquery? What are its types?

A subquery is also known as a nested query that is present inside another query. It can be used to return results that will be used by the outer query. There are four types of subqueries.

  • Single-row subquery: It returns only a single value (using aggregation functions).
  • Multi-row subquery: It returns multiple rows/fields (using WHERE condition against a column).
  • Correlated subquery: It refers to the outer query, and this executes once for each row processed by the outer query.
  • Scalar subquery: This subquery returns a single value (one row and one column).
  1. What is a cursor in SQL?

A cursor is an SQL object that is used to retrieve, update, and navigate through a result set. It is mainly used for operations that perform row-by-row basis rather than set-based.

Example query

DECLARE my_cursor CURSOR FOR
    SELECT EmployeeID, Name FROM Employees;

OPEN my_cursor;

FETCH NEXT FROM my_cursor INTO @emp_id, @emp_name;

—- Main operation goes here

CLOSE my_cursor;
DEALLOCATE my_cursor;
  1. List the different types of relationships in SQL
Types of Relationships

There are three types of relationships in SQL. It includes:

  • One-to-One (1:1): Each record in table A is related to only one record in table B.
  • One-to-Many (1:N): A record in table A can relate to multiple records in table B.
  • Many-to-Many (N:N): Every record in table A can be related to multiple records in table B and vice versa.
  1. What are the various forms of Normalization?
Types of Normalization in SQL

In general, normalization is the process of organizing data in a database to reduce redundancy and dependency. Various forms of normalization include:

  • First Normal Form (1NF): This form ensures that there are no duplicates present in the record, i.e., each column contains atomic values and each record is uniquely identified.
  • Second Normal Form (2NF): This form should meet 1NF requirements and remove partial dependencies, i.e., non-key attributes depend on the whole primary key.
  • Third Normal Form (3NF): This form should meet the 2NF requirements and remove transitive dependency, i.e.,non-key attributes depend only on the primary key.
  • Boyce-Codd Normal Form (BCNF): It is a stricter version of 3NF, where every determinant is a candidate key.
  • Fourth Normal Form (4NF): It should meet 3NF and eliminate multi-valued dependencies.
  • Fifth Normal Form (5NF): It should meet 4NF and ensure that the database is free of redundancy caused by joins.
  1. How do you select all even or odd records in a table?

You can check whether the record in the numeric column is even or odd using the modulo (%) operator.

Query

—- Select all even records from EmployeeId column
SELECT * FROM Employees WHERE EmployeeID % 2 = 0;

—- Select all odd records from EmployeeId column
SELECT * FROM Employees WHERE EmployeeID % 2 != 0;
  1. Write a SQL query to find values in a text column of a table that starts with a letter ‘R’.

With the help of the LIKE operator, you can easily find the values in a text column that start with the letter ‘R’.

Query

SELECT * FROM Employees WHERE Name LIKE ‘R%’;
  1. Write a query to find the top 5 customers with the highest total order amounts.

Using the SUM() function combined with GROUP BY and ORDER BY, we can find the top 5 customers from the orders table.

SELECT CustomerID, SUM(OrderAmount) AS TotalOrderAmount
FROM Orders
GROUP BY CustomerID
ORDER BY TotalOrderAmount DESC
LIMIT 5;
  1. Write a query to find employees who earn more than the average salary in their department.

By leveraging the subquery concept to calculate the average salary by department and compare it with the employee’s salary in the outer query.

SELECT EmployeeID, Name, Salary, DepartmentID
FROM Employees e
WHERE Salary > (
    SELECT AVG(Salary)
    FROM Employees
    WHERE DepartmentID = e.DepartmentID
);

FAQs

Normalization is the process of organizing a database to minimize redundancy and avoid undesirable characteristics like insertion, update, and deletion anomalies. The goal of normalization is to break down complex data structures into smaller, manageable parts that are easier to maintain and update. It improves the efficiency of the database by reducing storage costs and maintaining data integrity. Normal forms, like 1NF, 2NF, 3NF, and BCNF, define the levels of normalization to achieve better database design.

Learning SQL is crucial for any database professional as it is the standard language used to interact with relational databases. SQL helps in performing tasks like querying data, updating records, managing database structures, and ensuring data integrity. Mastering SQL enables professionals to manage large datasets efficiently, optimize performance, and handle complex queries, making it an essential skill for roles like Database Administrator, Data Analyst, and Data Engineer.

Improving your SQL skills involves a combination of learning the theory and practicing hands-on. Start by reviewing basic SQL syntax and commands, then gradually work your way up to more complex topics like subqueries, joins, and indexing. Participate in SQL exercises on websites like Guvi, LeetCode, SQLZoo, and HackerRank, which offer challenges to test your knowledge.

Career transition

Did you enjoy this article?

Schedule 1:1 free counselling

Similar Articles

Loading...
Share logo Copy link
Power Packed Webinars
Free Webinar Icon
Power Packed Webinars
Subscribe now for FREE! 🔔
close
Webinar ad
Table of contents Table of contents
Table of contents Articles
Close button

  1. Beginner's SQL Interview Questions
  2. Intermediate SQL Interview Questions
  3. Advanced SQL Interview Questions
  4. FAQs
    • Q1. What is normalization, and why is it important in database design?
    • Q2. What is the importance of learning SQL for a database professional?
    • Q3. How do I improve my SQL skills?