Frequently asked interview questions in SQL
1. What do you mean by databases?
A)
A database is a structured collection of data that is stored and accessed electronically.
Databases are designed to organize, store, and retrieve large amounts of information
efficiently. They support various data operations, such as querying, updating, and
managing data. Databases can be managed by Database Management Systems
(DBMS), which provide the necessary tools and functionalities to interact with the data.
2. What is MySQL?
A)
MySQL is an open-source relational database management system (RDBMS). It is
widely used for managing and manipulating databases, offering features like data
storage, retrieval, and support for the SQL language.
3. What is RDBMS?
A)
RDBMS (Relational Database Management System) is a type of database management
system that stores data in a structured format, using rows and columns. This data is
organized into tables, which can be linked to each other through relationships. RDBMSs
use SQL (Structured Query L anguage) for querying and managing the data. They
ensure data integrity and support the principles of ACID (Atomicity, Consistency,
Isolation, Durability) properties to guarantee reliable transaction processing.
Example: Consider a university database that manages information about students,
courses, and enrollments. An RDBMS would organize this data into related tables:
● Students Table: Contains student ID, name, date of birth, and contact
information.
● Courses Table: Contains course ID, course name, description, and credits.
● Enrollments Table: Contains enrollment ID, student ID, course ID, and
enrollment date.
Relationships between these tables can be established using foreign keys. For
example, the student ID in the Enrollments table references the student ID in the
Students table, and the course ID in the Enrollments table references the course ID in
the Courses table.
4. What is the difference between SQL and MySQL?
A)
SQL (Structured Query Language) is a standard language for managing relational
databases. MySQL is a specific implementation of an RDBMS that uses SQL for
querying and managing the database. The main difference lies in the specific syntax
and features supported by MySQL.
5. Why do we have a lot of data types in MySQL?
A)
MySQL offers a variety of data types to ensure efficient storage, optimal performance,
and data integrity. Each data type is designed for a specific kind of data and helps
optimize the storage space and processing speed. Different data types also help
enforce data validation and integrity by restricting the kind of data that can be stored in
a column.
Examples of Data Types in MySQL:
1. Numeric Data Types:
○ INT: Used for integer values. Example: age INT.
○ FLOAT, DOUBLE: Used for floating-point numbers. Example: price
DOUBLE.
○ DECIMAL: Used for precise decimal numbers, often for financial data.
Example: salary DECIMAL(10, 2).
2. String Data Types:
○ CHAR: Fixed-length character strings. Example: gender CHAR(1).
○ VARCHAR: Variable-length character strings. Example: name
VARCHAR(255).
○ TEXT: Large text strings. Example: description TEXT.
3. Date and Time Data Types:
○ DATE: Stores dates. Example: birthdate DATE.
○ TIME: Stores time. Example: appointment_time TIME.
○ DATETIME: Stores date and time. Example: created_at DATETIME.
4. Binary Data Types:
○ BLOB: Used for binary large objects, such as images or files. Example:
profile_picture BLOB.
Example:
Consider a database table for storing employee records:
CREATE TABLE Employees (
employee_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
birthdate DATE,
salary DECIMAL(10, 2),
profile_picture BLOB
);
In this table:
● employee_id is an integer that uniquely identifies each employee.
● name is a variable-length string to store the employee’s name.
● birthdate stores the date of birth.
● salary stores the salary with precision, ensuring two decimal places.
● profile_picture stores binary data for the employee’s profile picture.
6. What is the difference between char and varchar?
A) CHAR is a fixed-length string datatype in MySQL, while VARCHAR is a
variable-length string datatype.
Example:
CREATE TABLE ExampleTable (
char_column CHAR(10),
varchar_column VARCHAR(10)
);
7. What are types of Commands in SQL?
A)
SQL commands are categorized into five main types, each serving a specific purpose in
database management:
1. Data Definition Language (DDL):
○ CREATE: Creates a new database, table, index, or view.
○ ALTER: Modifies an existing database object, such as a table.
○ DROP: Deletes a database object.
○ TRUNCATE: Removes all records from a table, but not the table itself.
2. Data Manipulation Language (DML):
○ SELECT: Retrieves data from a database.
○ INSERT: Adds new records to a table.
○ UPDATE: Modifies existing records in a table.
○ DELETE: Removes records from a table.
3. Data Query Language (DQL):
○ SELECT: It is used to query and retrieve data from a database.
4. Data Control Language (DCL):
○ GRANT: Gives a user access privileges to the database.
○ REVOKE: Removes access privileges from a user.
5. Transaction Control Language (TCL):
○ COMMIT: Saves all changes made during the current transaction.
○ ROLLBACK: Reverts changes made during the current transaction.
○ SAVEPOINT: Sets a point within a transaction to which you can later roll
back.
8. What is a Distinct keyword?
A)
The DISTINCT keyword is used in SQL to retrieve unique values from a specified
column in a table. It eliminates duplicate records in the result set.
Example:
SELECT DISTINCT column_name FROM table_name;
9. What is the difference between delete and truncate?
A)
DELETE: Removes specific rows from a table based on a condition.
DELETE FROM table_name WHERE condition;
TRUNCATE: Removes all rows from a table, providing a more efficient way to delete all
records.
TRUNCATE TABLE table_name;
10. What is the difference between WHERE and HAVING clauses?
A)
Both WHERE and HAVING clauses are used to filter data in SQL queries, but they are
applied at different stages of the query process and serve different purposes:
1. WHERE Clause:
○ The WHERE clause is used to filter rows before any groupings are made.
It is applied to individual rows in the table.
○ It cannot be used with aggregate functions (like SUM, COUNT, AVG, etc.)
directly.
2. HAVING Clause:
○ The HAVING clause is used to filter groups of rows after the GROUP BY
operation is performed. It is applied to the result set of a query with
aggregated data.
○ It can be used with aggregate functions to filter the results based on the
aggregated values.
Example:
Consider a table Sales with the following columns: sale_id, product_id, quantity, price,
and sale_date.
Using the WHERE Clause:
SELECT product_id, quantity, price
FROM Sales
WHERE price > 50;
1. This query filters individual sales records where the price is greater than 50
before any aggregation.
Using the HAVING Clause:
SELECT product_id, SUM(quantity) as total_quantity, AVG(price) as
average_price
FROM Sales
GROUP BY product_id
HAVING AVG(price) > 50;
2. This query first groups the sales records by product_id, calculates the total
quantity sold and the average price for each product, and then filters the grouped
results to include only those products where the average price is greater than 50.
11. What are the types of constraints in SQL?
A)
Constraints in SQL are rules applied to table columns to enforce data integrity and
consistency. They help ensure that the data stored in the database meets certain
criteria and relationships. The main types of constraints in SQL are:
1. Primary Key Constraint:
○ Ensures that each row in a table is uniquely identified by a column or a set
of columns. A table can have only one primary key.
○ The primary key column(s) must contain unique values and cannot be null.
2. Foreign Key Constraint:
○ Establishes a relationship between the columns of two tables. It ensures
that the values in a column (or a set of columns) match values in the
primary key column of another table.
○ This constraint enforces referential integrity between the related tables.
3. Unique Constraint:
○ Ensures that all values in a column or a set of columns are unique. It
allows null values unless explicitly restricted.
○ A table can have multiple unique constraints.
4. Not Null Constraint:
○ Ensures that a column cannot have a null value. This constraint is used to
enforce that a column must always contain a value.
5. Check Constraint:
○ Ensures that all values in a column satisfy a specific condition. It can be
used to enforce domain integrity by limiting the values that can be placed
in a column.
6. Default Constraint:
○ Provides a default value for a column when no value is specified during an
insert operation. It ensures that a column always has a value even if one
is not explicitly provided.
Example:
Consider a table Employees with constraints applied:
CREATE TABLE Employees (
employee_id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE,
birthdate DATE,
salary DECIMAL(10, 2) CHECK (salary > 0),
department_id INT,
FOREIGN KEY (department_id) REFERENCES Departments(department_id)
);
In this table:
● employee_id is the primary key, ensuring each employee has a unique identifier.
● name has a NOT NULL constraint, ensuring each employee must have a name.
● email has a UNIQUE constraint, ensuring no two employees can have the same
email address.
● salary has a CHECK constraint, ensuring the salary is greater than 0.
● department_id has a FOREIGN KEY constraint, ensuring the value must match
an existing department_id in the Departments table.
12. What is the difference between primary key and foreign key?
A)
Answer: The primary key and foreign key are fundamental concepts in relational
databases that are used to enforce data integrity and establish relationships between
tables.
1. Primary Key:
○ Purpose: The primary key uniquely identifies each record in a table.
○ Uniqueness: Values in the primary key column(s) must be unique across
the table.
○ Not Null: The primary key column(s) cannot contain NULL values.
○ Table Limitation: A table can have only one primary key, which can
consist of one or multiple columns (composite key).
○ Example: In an Employees table, employee_id might be the primary key
to uniquely identify each employee.
2. Foreign Key:
○ Purpose: The foreign key creates a link between two tables, ensuring
referential integrity by enforcing that values in the foreign key column(s)
match values in the primary key column(s) of the referenced table.
○ Non-Uniqueness: Values in the foreign key column(s) do not need to be
unique in the referencing table.
○ Null Values: Foreign key columns can contain NULL values unless
explicitly restricted.
○ Multiple Keys: A table can have multiple foreign keys.
○ Example: In an Orders table, customer_id might be a foreign key
referencing the customer_id in a Customers table to associate orders with
customers.
Example:
Consider the following two tables: Customers and Orders.
Customers Table:
CREATE TABLE Customers (
customer_id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE
);
Orders Table:
CREATE TABLE Orders (
order_id INT PRIMARY KEY,
order_date DATE NOT NULL,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES Customers(customer_id)
);
In this example:
● The customer_id in the Customers table is the primary key, uniquely identifying
each customer.
● The customer_id in the Orders table is a foreign key, establishing a relationship
with the Customers table by referencing the customer_id primary key. This
ensures that every customer_id in the Orders table matches an existing
customer_id in the Customers table, maintaining referential integrity.
13. If you have established a relationship between two tables, what if I want to
delete or update something in the parent table? How?
A)
If a relationship (foreign key constraint) is established between two tables, you can use
the ON DELETE and ON UPDATE clauses to define the actions to be taken when the
referenced data in the parent table is deleted or updated.
Example:
CREATE TABLE ParentTable (
parent_id INT PRIMARY KEY
);
CREATE TABLE ChildTable (
child_id INT PRIMARY KEY,
parent_id INT,
FOREIGN KEY (parent_id) REFERENCES ParentTable(parent_id) ON DELETE
CASCADE ON UPDATE CASCADE
);
In this example, if a record in ParentTable is deleted or updated, the corresponding
records in ChildTable will be deleted or updated due to the specified CASCADE actions.
14. What are joins, and what are the types of joins?
A)
Joins in SQL are used to combine rows from two or more tables based on a related
column between them. Joins allow you to retrieve data from multiple tables in a single
query, making it easier to analyze and manipulate related data.
There are several types of joins in SQL, each serving a different purpose:
INNER JOIN:
○ Returns only the rows that have matching values in both tables.
○ It is the most commonly used join.
Example:
SELECT Employees.employee_id, Employees.name,
Departments.department_name
FROM Employees
INNER JOIN Departments ON Employees.department_id =
Departments.department_id;
- This query retrieves employees and their corresponding department names
where there is a match between the department_id in both tables.
LEFT JOIN (or LEFT OUTER JOIN):
○ Returns all rows from the left table and the matched rows from the right
table. If there is no match, NULL values are returned for columns from the
right table.
Example:
SELECT Employees.employee_id, Employees.name,
Departments.department_name
FROM Employees
LEFT JOIN Departments ON Employees.department_id =
Departments.department_id;
- This query retrieves all employees, including those who do not belong to any
department. For employees without a department, the department_name will be
NULL.
RIGHT JOIN (or RIGHT OUTER JOIN):
○ Returns all rows from the right table and the matched rows from the left
table. If there is no match, NULL values are returned for columns from the
left table.
Example:
SELECT Employees.employee_id, Employees.name,
Departments.department_name
FROM Employees
RIGHT JOIN Departments ON Employees.department_id =
Departments.department_id;
- This query retrieves all departments, including those without employees. For
departments without employees, the employee details will be NULL.
FULL JOIN (or FULL OUTER JOIN):
○ Returns all rows when there is a match in either the left or right table.
Rows without a match in one of the tables will still appear in the result set,
with NULL values for columns from the table without a match.
Example:
SELECT Employees.employee_id, Employees.name,
Departments.department_name
FROM Employees
FULL OUTER JOIN Departments ON Employees.department_id =
Departments.department_id;
- This query retrieves all employees and departments, including employees
without departments and departments without employees.
CROSS JOIN:
○ Returns the Cartesian product of the two tables, meaning it returns all
possible combinations of rows from the two tables. It does not require a
condition to join.
Example:
SELECT Employees.name, Departments.department_name
FROM Employees
CROSS JOIN Departments;
- This query retrieves every possible combination of employees and departments.
SELF JOIN:
○ Joins a table with itself. It is useful for hierarchical or recursive
relationships within the same table.
Example:
SELECT e1.employee_id, e1.name, e2.name AS manager_name
FROM Employees e1
LEFT JOIN Employees e2 ON e1.manager_id = e2.employee_id;
- This query retrieves employees along with their manager's name by joining the
Employees table with itself.
15. What is the difference between left and inner join?
A)
- INNER JOIN returns only the rows where there is a match in both tables.
- LEFT JOIN returns all rows from the left table and matched rows from the right
table. If there is no match, NULL values are returned for columns from the right
table.
Example:
- INNER JOIN
SELECT * FROM Employees
INNER JOIN Departments ON Employees.DepartmentID =
Departments.DepartmentID;
- LEFT JOIN
SELECT * FROM Employees
LEFT JOIN Departments ON Employees.DepartmentID =
Departments.DepartmentID;
16. What is a subquery?
A)
A subquery is a query nested inside another query. It can be used to retrieve data that
will be used by the main query as a condition or to perform calculations.
Example:
Retrieve employees who have a salary greater than the average salary:
SELECT * FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);
17. What types of relationships are used in SQL?
A)
In SQL, relationships between tables are used to link data logically and ensure data
integrity. There are three main types of relationships:
1. One-to-One (1:1) Relationship:
○ Each row in the first table is linked to one and only one row in the second
table, and vice versa.
○ This type of relationship is less common but is used to split data into
different tables for better organization and security.
○ Example:
■ Tables: Employees and EmployeeDetails
■ Relationship: Each employee has one unique set of detailed
information.
One-to-Many (1:M) Relationship:
● A single row in the first table can be associated with multiple rows in the second
table, but each row in the second table is associated with only one row in the first
table.
● This is the most common type of relationship and is used to model hierarchical
data.
● Example:
○ Tables: Departments and Employees
○ Relationship: One department can have multiple employees, but each
employee belongs to only one department.
Many-to-Many (M:M) Relationship:
● Multiple rows in the first table can be associated with multiple rows in the second
table.
● This relationship is typically implemented using a junction table (or associative
table) that contains foreign keys referencing the primary keys of the two tables.
● Example:
○ Tables: Students, Courses, and Enrollments
○ Relationship: A student can enroll in multiple courses, and a course can
have multiple students.
18. What is the use of CTE?
A)
A Common Table Expression (CTE) is used to create a temporary result set that can be
referred to within a SELECT, INSERT, UPDATE, or DELETE statement. It helps simplify
complex queries and makes them more readable.
Example:
WITH HighSalaryCTE AS (
SELECT * FROM Employees WHERE Salary > (SELECT AVG(Salary) FROM
Employees)
)
SELECT * FROM HighSalaryCTE;
19. What is a view, and What are the uses of views?
A)
A view is a virtual table based on the result of a SELECT query. It does not store the
data itself but provides a way to represent complex queries. Uses of views include
simplifying queries, providing security by restricting access to certain columns, and
encapsulating complex logic.
20. What is an index in MySQL and types?
A)
An index is a data structure that improves the speed of data retrieval operations on a
database table. Types of indexes include Primary Key Index, Unique Index, Clustered
Index, and Non-Clustered Index.
Example:
Create an index on the "LastName" column:
CREATE INDEX idx_LastName ON Employees (LastName);
21. What are stored procedures? / What is a procedure?
A)
A stored procedure is a set of SQL statements with a name that is stored in the
database. It can be called and executed as a single unit. Procedures can accept
parameters and return values.
Example:
CREATE PROCEDURE GetEmployeeDetails (IN empID INT)
BEGIN
SELECT * FROM Employees WHERE EmployeeID = empID;
END;
22. What is a Function?
A)
A function is a set of SQL statements that performs a specific task. Functions return a
value to the caller and can accept parameters.
Example:
CREATE FUNCTION CalculateArea(radius INT)
RETURNS DOUBLE
BEGIN
RETURN 3.14 * radius * radius;
END;
23. What are Window Functions?
A)
Window Functions operate on a set of rows related to the current row. Types of window
functions are ROW_NUMBER(), RANK(), DENSE_RANK(), FIRST_VALUE(),
NTH_VALIUE(), LAG(), LEAD().
Examples include ROW_NUMBER(), DENSE_RANK(), and LAG()They are often used
for analytics and reporting.
Example:
Assign a rank to employees based on their salary:
SELECT EmployeeID, Salary, RANK() OVER (ORDER BY Salary DESC) AS
SalaryRank
FROM Employees;
24. What is the difference between stored procedures and functions?
A)
Stored Procedures can perform actions and may or may not return values. They can
have input and output parameters.
Functions return a single value and are generally used for calculations.
Example:
Stored Procedure:
CREATE PROCEDURE GetEmployeeCount ()
BEGIN
SELECT COUNT(*) FROM Employees;
END;
Function:
CREATE FUNCTION GetEmployeeCount ()
RETURNS INT
BEGIN
RETURN (SELECT COUNT(*) FROM Employees);
END;
25. Explain the ACID properties in the context of database transactions?
A)
ACID properties ensure the reliability of transactions:
Atomicity: Transactions are treated as a single, indivisible unit.
Consistency: Transactions bring the database from one consistent state to another.
Isolation: Transactions are executed in isolation from each other.
Durability: Once a transaction is committed, its changes are permanent.
Example:
- Consider a bank transaction where money is transferred from one account to
another. ACID ensures that either the entire transaction is completed (money is
deducted from one account and added to another), or nothing happens.
26. What is a trigger, and what are the types of triggers we can create?
A)
A trigger is a set of instructions that automatically initiates an action in response to a
specified event. Types of triggers include BEFORE Triggers, AFTER Triggers.
Example:
Create a trigger to update the "LastModified" column whenever a row is updated:
CREATE TRIGGER UpdateLastModified
BEFORE UPDATE ON Employees
FOR EACH ROW
SET NEW.LastModified = NOW();