SQL Interview Questions
SQL Interview Questions
SQL Interview Questions
„Give me more relational database management and data modeling interview questions and
replies.”
1. What is SQL?
Response: SQL, or Structured Query Language, is a standardized programming
language used to manage and manipulate relational databases. It allows users to
perform various operations such as querying data, inserting or updating records,
creating or modifying database structures, and managing permissions.
2. What are the different types of SQL commands?
Response: SQL commands can be categorized into four main types:
• Data Definition Language (DDL): Used to define, modify, and delete
database objects such as tables and indexes. Examples include CREATE,
ALTER, and DROP.
• Data Manipulation Language (DML): Used to manipulate data within
database objects. Examples include SELECT, INSERT, UPDATE, and DELETE.
• Data Control Language (DCL): Used to control access to database objects.
Examples include GRANT and REVOKE.
• Transaction Control Language (TCL): Used to manage transactions within a
database. Examples include COMMIT, ROLLBACK, and SAVEPOINT.
3. What is a primary key?
Response: A primary key is a column or combination of columns that uniquely
identifies each row in a table. It ensures that each row in the table is unique and
serves as the basis for establishing relationships between tables in a relational
database.
4. What is the difference between INNER JOIN and LEFT JOIN?
Response:
• INNER JOIN: Retrieves records that have matching values in both tables
based on the specified join condition. Rows from both tables that do not
meet the join condition are excluded from the result set.
• LEFT JOIN: Retrieves all records from the left table (the first table specified
in the query) and the matched records from the right table based on the
join condition. If there are no matching records in the right table, NULL
values are returned for the columns from the right table.
5. Explain the difference between WHERE and HAVING clauses in SQL.
Response:
• WHERE clause: Filters rows based on a specified condition before the
data is grouped or aggregated. It is used with SELECT, UPDATE, or DELETE
statements to specify the criteria for selecting or modifying rows.
• HAVING clause: Filters rows based on a specified condition after the data
is grouped or aggregated using GROUP BY. It is used with SELECT
statements to filter the results of aggregate functions such as SUM, AVG,
COUNT, etc.
6. What is a subquery?
Response: A subquery, also known as an inner query or nested query, is a SELECT
statement embedded within another SQL statement. It allows you to retrieve data
from one or more tables based on the results of another query. Subqueries can
be used in SELECT, INSERT, UPDATE, and DELETE statements.
7. Explain the difference between UNION and UNION ALL.
Response:
• UNION: Combines the results of two or more SELECT statements and
removes duplicate rows from the result set.
• UNION ALL: Combines the results of two or more SELECT statements,
including duplicate rows in the result set.
8. What is the difference between DELETE and TRUNCATE in SQL?
Response:
• DELETE: The DELETE statement is used to remove rows from a table based
on specified conditions. It operates on individual rows and generates a
transaction log for each deleted row, allowing for rollback operations.
DELETE can be rolled back, and triggers can be fired for each deleted row.
• TRUNCATE: The TRUNCATE statement is used to remove all rows from a
table, effectively resetting the table to its initial state. It removes the data
without logging individual row deletions, making it faster than DELETE for
large tables. TRUNCATE cannot be rolled back, and triggers are not fired.
9. What are SQL Joins? Explain different types of SQL Joins.
Response: SQL Joins are used to combine rows from two or more tables based
on related columns between them. The different types of SQL Joins are:
• INNER JOIN: Returns rows that have matching values in both tables
based on the specified join condition.
• LEFT JOIN (or LEFT OUTER JOIN): Returns all rows from the left table
and the matched rows from the right table. If there are no matches, NULL
values are returned for columns from the right table.
• RIGHT JOIN (or RIGHT OUTER JOIN): Returns all rows from the right
table and the matched rows from the left table. If there are no matches,
NULL values are returned for columns from the left table.
• FULL JOIN (or FULL OUTER JOIN): Returns all rows when there is a
match in either the left or right table. If there is no match, NULL values are
returned for the columns from the other table.
10. What is the difference between WHERE and HAVING clauses in SQL?
Response:
• WHERE clause: The WHERE clause is used to filter rows based on a
specified condition before the data is grouped or aggregated. It is applied
to individual rows before any grouping or aggregation occurs.
• HAVING clause: The HAVING clause is used to filter group rows based on
a specified condition after the data is grouped or aggregated using the
GROUP BY clause. It is applied to group results after the grouping or
aggregation process.
11. What is a subquery in SQL? Provide an example.
Response: A subquery is a query nested within another SQL query, also known as
an inner query or nested query. It can be used in SELECT, INSERT, UPDATE, or
DELETE statements to return data that is used as a condition or value in the outer
query. Here's an example:
SELECT *
FROM employees
WHERE department_id IN (SELECT department_id FROM
departments WHERE location = 'New York');
12. Explain the difference between UNION and UNION ALL in SQL.
Response:
• UNION: The UNION operator is used to combine the result sets of two or
more SELECT statements into a single result set, removing duplicate rows.
It performs a distinct operation on the result set.
• UNION ALL: The UNION ALL operator is similar to UNION but includes all
rows from the result sets of the SELECT statements, including duplicates. It
does not perform a distinct operation.
13. What is a SQL injection, and how can it be prevented?
Response: SQL injection is a security vulnerability that occurs when an attacker
inserts malicious SQL code into input fields or parameters of SQL queries,
allowing them to execute unauthorized SQL commands or manipulate the
database. It can lead to data theft, data corruption, or unauthorized access to
sensitive information. To prevent SQL injection, developers should use
parameterized queries or prepared statements, input validation and sanitization,
least privilege principle, and secure coding practices such as avoiding dynamic
SQL generation.
13. What is a primary key and a foreign key in SQL?
Response:
• Primary Key: A primary key is a column or set of columns that uniquely
identifies each row in a table. It ensures that each row in a table is unique
and cannot contain null values. Primary keys are used to enforce entity
integrity and are often indexed for faster data retrieval.
• Foreign Key: A foreign key is a column or set of columns in a table that
establishes a relationship with a primary key or unique key in another
table. It ensures referential integrity by enforcing a link between the data
in two related tables. Foreign keys typically represent relationships
between tables, such as parent-child relationships.
14. What is the difference between the CHAR and VARCHAR data types in SQL?
Response:
• CHAR: The CHAR data type is fixed-length and stores characters up to a
specified length. It pads the values with spaces to fill the remaining space
if the input value is shorter than the specified length. CHAR is suitable for
storing fixed-length strings, such as postal codes or state abbreviations.
• VARCHAR: The VARCHAR data type is variable-length and stores
characters up to a specified maximum length. It only uses the necessary
amount of storage space to store the actual data without padding with
spaces. VARCHAR is suitable for storing variable-length strings, such as
names or descriptions.
15. What are the different types of SQL constraints?
Response: SQL constraints are rules that enforce data integrity and ensure the
accuracy and consistency of data in a database. The different types of SQL
constraints include:
• PRIMARY KEY: Ensures uniqueness and identifies each row in a table.
• FOREIGN KEY: Establishes relationships between tables and enforces
referential integrity.
• UNIQUE: Ensures that all values in a column are unique.
• NOT NULL: Ensures that a column cannot contain null values.
• CHECK: Validates data based on a specified condition.
• DEFAULT: Specifies a default value for a column when no value is
provided during insertion.
16. What is a SQL stored procedure? Provide an example.
Response: A SQL stored procedure is a precompiled SQL code block stored in
the database and executed on demand. It can accept input parameters, perform
database operations, and return results. Stored procedures improve performance,
code reusability, and security. Here's an example:
CREATE PROCEDURE GetEmployeeById
@EmployeeId INT
AS
BEGIN
SELECT * FROM Employees WHERE EmployeeId = @EmployeeId;
END
17. Explain the difference between the GROUP BY and ORDER BY clauses in
SQL.
Response:
• GROUP BY: The GROUP BY clause is used to group rows that have the
same values into summary rows, typically to perform aggregate functions
like COUNT, SUM, AVG, etc. It operates on the entire result set and returns
a single row for each group.
• ORDER BY: The ORDER BY clause is used to sort the result set based on
one or more columns in ascending or descending order. It does not affect
the grouping of rows but arranges the rows in a specified order.
18. What is a SQL index, and how does it improve performance?
Response:
• A SQL index is a data structure that improves the speed of data retrieval
operations on a database table by providing quick access to the rows
based on the indexed columns.
• Indexes are created on columns that are frequently used in search, join,
and sort operations.
• They reduce the number of rows that need to be scanned to locate specific
data, resulting in faster query execution times.
• However, indexes also require additional storage space and may impact
the performance of data modification operations like INSERT, UPDATE,
and DELETE.