Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views19 pages

70+ SQL Interview Questions

Uploaded by

727822tuad019
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views19 pages

70+ SQL Interview Questions

Uploaded by

727822tuad019
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

70+ SOL INTERVIEW

QUESTIONS:
FROM BEGINNER TO
Beginner-Level
Questions
SQL (Structured Query Language) is used to interact with databases. It helps in
retrieving, updating, and managing structured data efficiently.

SQL statements are categorized into:


+ DDL (Data Definition Language) - CREATE, ALTER, DROP
* DML (Data Manipulation Language) — INSERT, UPDATE, DELETE
« DCL (Data Control Language) - GRANT, REVOKE
« TCL (Transaction Control Language) - COMMIT, ROLLBACK, SAVEPOINT
DQL (Data Query Language) — SELECT

* SQL is a query language used to interact with databases.


* MySQL is a relational database management system (RDBMS) that uses
SQL as its query language.

* CHAR is a fixed-length data type (e.g., CHAR(10) always takes 10 bytes).


« VARCHAR is a variable-length data type (e.g., VARCHAR(10) takes up only
the required space).

waLTER
oATn swigLos
° Renvemy
« DELETE removes specific rows and can be rolled back.
+ TRUNCATE removes all rows but retains the table structure.
+ DROP deletes the table along with its structure.

Normalization is the process of organizing a database to reduce redundancy


and improve data integrity. It involves dividing large tables into smaller ones
and establishing relationships.

1INF: Eliminate duplicate columns and ensure atomicity.


2NF: Meet 1NF and remove partial dependencies.
3NF: Meet 2NF and remove transitive dependencies.
BCNF: A stricter version of 3NF, ensuring all functional dependencies are
handled.

Denormalization is the process of combining tables to improve read


performance, often used in reporting or analytical applications where fast
retrieval is more important than minimizing redundancy.

« Primary Key: A unique identifier for a record in a table.


« Foreign Key: A reference to a primary key in another table to establish
relationships between tables.

waLTER
oATn swigLos
° Renvemy
* One-to-One (1:1)

« One-to-Many (1:M)
* Many-to-Many (M:M)

The WHERE clause is used to filter records based on a specified condition.

The ORDER BY clause is used to sort the result set in ascending (ASC) or
descending (DESC) order.

GROUP BY is used to group rows with the same values in specified columns
and apply aggregate functions.

The WHERE clause filters rows before aggregation, while HAVING filters after
aggregation.

e COUNT(): Counts the number of rows.


* SUM(): Adds up numerical values.
* AVG(): Calculates the average of numerical values.

waLTER
oATA SwigLDS
0 Reavemy
DISTINCT eliminates duplicate values in a result set.

BETWEEN filters values within a specified range.

IN is used to filter rows matching a list of values

LIKE is used for pattern matching in string values.

The SELECT statement is used to retrieve data from a database table.

waLTER
oATA SwigLDS
0 Reavemy
Intermediate-
Level Questions
21. WHAT IS THE DIFFERENCE BETWEEN INNER JOIN, LEFT JOIN, RIGHT JOIN,
AND FULL JOIN?

INNER JOIN: Returns only matching records from both tables.


LEFT JOIN: Returns all records from the left table and matching records
from the right table. If no match is found, NULL values are returned for the
right table columns.
RIGHT JOIN: Returns all records from the right table and matching records
from the left table. If no match is found, NULL values are returned for the
left table columns.
FULL JOIN: Returns all records from both tables, with NULLs in columns
where there is no match.

22. HOW DOES A CROSS JOIN WORK?

A CROSS JOIN returns the Cartesian product of two tables, meaning it joins
every row from the first table with every row from the second table.

23. WHAT IS A SELF JOIN?

A SELF JOIN is a join where a table is joined with itself, often using an alias to
differentiate the instances of the table.

24. WHAT IS A NATURAL JOIN?

A NATURAL JOIN automatically


joins tables on columns with the same name
and compatible data types, eliminating duplicate columns in the result.

° Reabemy
25. WHEN WOULD YOU USE A LEFT JOIN INSTEAD OF AN INNER JOIN?

You would use a LEFT JOIN when you need to retrieve all records from the left
table regardless of whether there is a match in the right table. An INNER JOIN
only returns matching rows from both tables.

26. WHAT HAPPENS WHEN THERE IS NO MATCH IN A RIGHT JOIN?

If there is no match in a RIGHT JOIN, NULL values are returned for columns
from the left table.

27. WHAT ARE UNION AND UNION ALL, AND HOW DO THEY DIFFER?

* UNION combines the results of two queries and removes duplicate rows.
* UNION ALL combines results without removing duplicates.

28. WHAT IS THE DIFFERENCE BETWEEN EXISTS AND IN?

« EXISTS: Checks if a subquery returns any rows. It stops executing once it


finds a match, making it more efficient in some cases.
« IN: Compares a value with a list of values and retrieves matching rows. It
processes the entire list before returning results.

29. WHAT IS A COMPOSITE KEY?

A composite key is a primary key that consists of two or more columns that
together uniquely identify a record in a table.

30. WHAT IS THE DIFFERENCE BETWEEN A PRIMARY KEY AND A UNIQUE KEY?

« Primary Key: Uniquely identifies each record and does not allow NULL values.
« Unique Key: Ensures uniqueness but allows one NULL value per column.

waLTER
oATA SwigLDS
° Reavemy
Aggregate functions perform calculations on multiple rows and return a
single value. Examples include:
e SUM() - Returns the sum of values.
« AVG() - Returns the average of values.
« COUNT() - Counts the number of rows.
MAX() - Returns the maximum value.
MIN() - Returns the minimum value.

Scalar functions return a single value based on the input. Examples include:
* UPPER() - Converts text to uppercase.
« LOWER() - Converts text to lowercase.
* LEN() - Returns the length of a string.

COALESCE() returns the first non-null value in a list.

NULLIF() returns NULL if two values are equal; otherwise, it returns the

first value.

LEN() - Returns the length of a string.


SUBSTRING() - Extracts a substring from a string.
REPLACE() — Replaces part of a string.
TRIM() - Removes leading/trailing spaces.

waLTER
oATA SwigLDS
° Reavemy
36. HOW CAN YOU USE THE CASE STATEMENT IN SQL?

The CASE statement is used to implement conditional logic.

37. WHAT IS THE CAST() FUNCTION USED FOR?

CAST() converts one data type to another.

38. HOW DOES THE CONVERT() FUNCTION DIFFER FROM CAST()?

CONVERT() is SQL Server-specific and allows formatting options, while CAST()


is more standard and works across databases.

39. WHAT IS THE DIFFERENCE BETWEEN LEAD() AND LAG() FUNCTIONS?

« LEAD() retrieves the next row’s value.


* LAG() retrieves the previous row’s value.

40. WHAT IS THE DIFFERENCE BETWEEN RANK(), DENSE_RANK(), AND


ROW_NUMBER()?

* RANK() assigns a rank but skips numbers for duplicate values.


+ DENSE_RANK() assigns ranks sequentially without gaps.
+« ROW_NUMBER() assigns a unique row number to each record.

41. WHAT IS A SUBQUERY IN SQL?

A subquery is a query inside another query, used to retrieve data for the main
query.

42. WHAT IS A CORRELATED SUBQUERY?

A correlated subquery depends on the outer query and runs once per row
processed by the outer query.

° Achoemy
To find the second-highest salary, you can use the LIMIT and OFFSET or a
subquery:

SELECT DISTINCT salary


FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1;

Or using a subquery:

SELECT MAX(salary)
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);

You can find the nth highest salary using a subquery with LIMIT and OFFSET:

SELECT DISTINCT salary


FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET (n-1);

Or using the DENSE_RANK() function:

SELECT salary
FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) as rnk

FROM employees
) ranked
WHERE rnk = n;

waLTER
oATA SwigLDS
° Reavemy
A CTE is a temporary result set that can be referenced multiple times in a
query.

A recursive CTE calls itself until a termination condition is met.

A pivot converts row values into columns. In SQL Server, you can use the
PIVOT operator:

SELECT *

FROM (
SELECT department, employee, salary
FROM employees

) SourceTable
PIVOT(
SUM(salary)

FOR department IN (Sales, IT, HR)


) AS PivotTable;

In databases like PostgreSQL or MySQL, you can use CASE WHEN:

SELECT
employee,
SUM(CASE WHEN department = 'Sales' THEN salary ELSE 0 END) AS Sales,
SUM(CASE WHEN department = 'IT* THEN salary ELSE 0 END) AS IT,
SUM(CASE WHEN department = 'HR' THEN salary ELSE 0 END) AS HR
FROM employees
GROUP BY employee;

waLTER
oATA SwigLDS
° Reavemy
An unpivot operation converts columns into rows.
Example in SQL Server using UNPIVOT:

SELECT department, category, salary


FROM (

SELECT department, Sales, IT, HR


FROM employees
) SourceTable
UNPIVOT
(

salary FOR category IN (Sales, IT, HR)


) AS UnpivotTable;

In other SQL versions, you can achieve the same result using UNION ALL:

SELECT department, 'Sales' AS category, Sales AS salary FROM employees


UNION ALL

SELECT department, ‘IT', IT FROM employees


UNION ALL
SELECT department, 'HR', HR FROM employees;

To check for duplicates, use the GROUP BY clause with HAVING COUNT(*) > 1:

SELECT name, COUNT(*)


FROM employees
GROUP BY name
HAVING COUNT(*) > 1;

WALTER SHIELDS.
oA TA
ACADEMY
(2
To delete duplicates while keeping one record, you can use ROW_NUMBER():

WITH DuplicateCTE AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY name, salary ORDER BY id) AS
row_num
FROM employees
)
DELETE FROM employees
WHERE id IN (

SELECT id FROM DuplicateCTE WHERE row_num > 1

)i

In MySQL:

DELETE e1 FROM employees e1


INNER JOIN employees e2
ON e1.name = e2.name AND e1.salary = e2.salary
WHERE e.id > e2.id;

waLTER
oATA SwigLDS
° Reavemy
SN
Advanced-Level
Questions

An index is a database object that improves the speed of data retrieval


operations by allowing the database engine to find rows more quickly.

» Clustered Index — Sorts and stores data physically in the table.


+ Non-Clustered Index — Stores pointers to the data instead of sorting it
physically.
Unique Index - Ensures that all values in a column are unique.
Composite Index - Created on multiple columns to optimize specific
queries.
Filtered Index - Created with a WHERE clause to index a subset of data.

+ A clustered index determines the physical order of data and there can be
only one per table.
« A non-clustered index stores pointers to data and allows multiple indexes
per table.

A unique index prevents duplicate values in a column, enforcing uniqueness.

waLTER
oATA SwigLDS
° Reavemy
Indexing speeds up queries by reducing the number of rows that need to be
scanned, leading to faster retrieval times.

+ Indexes require additional storage space.


* They slow down INSERT, UPDATE, and DELETE operations because indexes
must be updated when the data changes.

A covering index contains all columns needed for a query, reducing the need
to access the actual table.

» Index Scan - Scans the entire index (less efficient).


« Index Seek - Directly searches for relevant data (more efficient).

A filtered index is created on a subset of data based on a specific condition.

A composite index is an index on multiple columns, improving performance for


queries filtering by those columns.

waLTER
oATA SwigLDS
° Reavemy
(o)
A transaction is a sequence of operations performed as a single unit of work.

Atomicity — All operations in a transaction are completed, or none are.


Consistency — Ensures database integrity before and after transactions.
Isolation — Prevents interference from other transactions.
Durability — Ensures committed transactions remain saved.

Read Uncommitted — Allows dirty reads.


Read Committed - Prevents dirty reads.
Repeatable Read - Prevents dirty and non-repeatable reads.
Serializable - Ensures full isolation.

A deadlock occurs when two transactions wait for each other to release locks,
causing them to halt indefinitely.

Use proper indexing, short transactions, and consistent locking orders.

« Optimistic Locking - Assumes conflicts are rare and checks before


committing changes.
» Pessimistic Locking — Locks data to prevent conflicts.

waLTER
oATA SwigLDS
° Reavemy
67. WHAT IS A SAVEPOINT IN SQL TRANSACTIONS?

A savepoint allows rolling back part of a transaction.

68. WHAT HAPPENS WHEN A TRANSACTION IS ROLLED BACK?

All changes made in the transaction are undone, restoring the database to its
previous state.

69. WHAT IS AN IMPLICIT TRANSACTION?

Automatically starts a transaction before a SQL statement is executed.

70. WHAT IS AN EXPLICIT TRANSACTION?

A transaction manually defined using BEGIN TRANSACTION and


COMMIT/ROLLBACK.

71. HOW DO YOU OPTIMIZE SQL QUERIES FOR PERFORMANCE?

Use indexes, optimize joins, limit SELECT columns, analyze execution plans,
and avoid unnecessary calculations.

72. WHAT IS A QUERY EXECUTION PLAN, AND HOW DO YOU ANALYZE IT?

A query execution plan shows how SQL Server executes a query. Use EXPLAIN
PLAN or EXPLAIN ANALYZE to analyze it.

73. WHAT ARE SQL STORED PROCEDURES?

Stored procedures are precompiled SQL queries stored in the database,


improving performance and security.

waLTER
oATA SwigLDS
° Reavemy
Triggers automatically execute SQL code in response to events (INSERT,
UPDATE, DELETE).

A view is a virtual table based on a query. It simplifies complex queries and


improves security.

« Materialized views store query results.


+ Non-materialized views execute queries dynamically.

Functions created by users to encapsulate reusable SQL logic.

waLTER
oATA SwigLDS
0 Reavemy
« Deterministic functions return the same output for the same input.
« Non-deterministic functions return varying results (e.g., GETDATE()).

SQL injection, unauthorized access, improper privilege handling.

» SQL injections exploit input vulnerabilities to manipulate queries.


* Use prepared statements, parameterized queries, and input validation to
prevent them.

waLTER
oATA SwigLDS
0 Reavemy

You might also like