Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

SQL INTERVIEW QUESTIONS

The document provides an overview of SQL/PostgreSQL interview questions, covering key concepts such as the differences between IN and BETWEEN operators, various types of JOINs, normalization, and the distinctions between DROP, DELETE, and TRUNCATE commands. It also explains the use of LIMIT and OFFSET for pagination in SQL queries. Additionally, it includes common interview questions and their answers related to these topics.

Uploaded by

gayathri Jayalal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

SQL INTERVIEW QUESTIONS

The document provides an overview of SQL/PostgreSQL interview questions, covering key concepts such as the differences between IN and BETWEEN operators, various types of JOINs, normalization, and the distinctions between DROP, DELETE, and TRUNCATE commands. It also explains the use of LIMIT and OFFSET for pagination in SQL queries. Additionally, it includes common interview questions and their answers related to these topics.

Uploaded by

gayathri Jayalal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

SQL/PostgreSQL Interview Questions

1. Difference Between IN and BETWEEN Operators:


The IN and BETWEEN operators are commonly used in SQL for filtering query results.
 IN Operator
Used to check if a value matches any value in a list or a subquery result.

SELECT column_name
FROM table_name
WHERE column_name IN (value1, value2, value3, ...);

SELECT *
FROM Employees
WHERE department_id IN (1, 2, 3);

 Fetches rows where department_id is either 1, 2, or 3.

 BETWEEN Operator
Used to filter records within a specific range of values (inclusive of both boundaries).
Ideal when filtering data between two continuous values like dates, numbers, or
alphabets.

SELECT column_name
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

SELECT *
FROM Orders
WHERE order_date BETWEEN '2024-01-01' AND '2024-12-31';

 Fetches rows where order_date is within the range 2024-01-01 to 2024-12-31


(inclusive).
Feature IN Operator BETWEEN Operator

Checks if a value exists in a Checks if a value falls within


Purpose
specified list. a range.

A continuous range of two


Input A set of discrete values.
boundary values.

Can include strings, numbers, Works best with numbers,


Type of Values
or subquery results. dates, or time.

Evaluates exact matches with Includes both boundary


Inclusivity
the provided values. values in the range.

Can work with non-continuous Works only with ranges of


Flexibility
values. continuous values.

2. Explain Joins

In SQL, a JOIN is used to combine rows from two or more tables based on a related column between
them. Joins are essential when you need to retrieve data from multiple tables in a relational database
that are related to each other through keys (such as primary and foreign keys).

There are different types of JOINs, each serving a specific purpose:

1. INNER JOIN/SIMPLE JOIN

 An INNER JOIN returns only the rows where there is a match in both tables.

 It's the most commonly used join type when you need to select records that have matching
values in both tables.
Example:

SELECT orders.order_id, customers.customer_name

FROM orders

INNER JOIN customers ON orders.customer_id = customers.customer_id;

 This query will return the order ID and customer name only for customers who have placed
orders.

2. LEFT JOIN (or LEFT OUTER JOIN)

 A LEFT JOIN returns all records from the left table (the first table), and the matched records from
the right table (the second table). If there is no match, the result will contain NULL for columns
from the right table.

 Use this when you want to include all records from the left table, even if there is no match in the
right table.

Example:

SELECT customers.customer_name, orders.order_id

FROM customers

LEFT JOIN orders ON customers.customer_id = orders.customer_id;

 This query will return all customers, along with their order IDs if they have placed any. If a
customer has not placed an order, the order ID will be NULL.

3. RIGHT JOIN (or RIGHT OUTER JOIN)

 A RIGHT JOIN is similar to a LEFT JOIN, but it returns all records from the right table, and the
matched records from the left table. If there is no match, the result will contain NULL for
columns from the left table.

 Use this when you want to include all records from the right table, even if there is no match in
the left table.

Example:

SELECT orders.order_id, customers.customer_name

FROM orders

RIGHT JOIN customers ON orders.customer_id = customers.customer_id;

 This query will return all orders along with customer names. If there is no corresponding
customer for an order, the customer name will be NULL.
4. FULL JOIN (or FULL OUTER JOIN)

 A FULL JOIN returns all records when there is a match in either left (first) or right (second) table.
If there is no match, the result will contain NULL values for columns from the table that does not
have the matching row.

 Use this when you want to retrieve all records from both tables, regardless of whether there is a
match.

Example:

SELECT customers.customer_name, orders.order_id

FROM customers

FULL JOIN orders ON customers.customer_id = orders.customer_id;

 This query will return all customers and all orders, with NULL values where there is no match.

5. CROSS JOIN

 A CROSS JOIN returns the Cartesian product of the two tables, meaning it returns all possible
combinations of rows from both tables.

 This is used rarely, often for generating combinations or for cases where you need all possible
pairings between two sets of data.

Example:

SELECT customers.customer_name, orders.order_id

FROM customers

CROSS JOIN orders;

 This query will return every combination of customer and order, regardless of whether they are
related.

Select ID, ProductName, CustomerName, CustomerAddress, Amount FROM Product_Details, Customer


_Details;

6. SELF JOIN

 SELF JOIN is a join where a table is joined with itself. This can be useful for hierarchical or
recursive data.

 Self joins are often used when you need to compare rows within the same table.

Example:
SELECT e1.employee_name AS Employee, e2.employee_name AS Manager

FROM employees e1

JOIN employees e2 ON e1.manager_id = e2.employee_id;

 This query shows the employees along with their managers by joining the employees table with
itself.

Select TB.ID, TB.ProductName FROM Product_Details TB, Product_Details TB2 WHERE TB.AMOUNT <
TB2.AMOUNT;

Visual Summary of Joins:

Join Type Records Returned

INNER JOIN Only rows with matching values in both tables.

LEFT JOIN All rows from the left table, and matching rows from the right table (NULL if no match).

RIGHT JOIN All rows from the right table, and matching rows from the left table (NULL if no match).

FULL JOIN All rows from both tables, with NULL where there is no match.

CROSS JOIN Cartesian product of both tables, returning every combination of rows.

SELF JOIN Joining the table with itself, often for hierarchical or recursive data relationships.

1. What is the difference between an INNER JOIN and a LEFT JOIN?

"An INNER JOIN only returns rows where there is a match in both tables. A LEFT JOIN returns all rows
from the left table, and the matched rows from the right table; if there is no match, NULL is returned for
the right table's columns."

2. When would you use a RIGHT JOIN instead of a LEFT JOIN?

"A RIGHT JOIN is used when you want to make sure that all records from the right table are included in
the result, regardless of whether they have a match in the left table."

3. What is a Cartesian Product in CROSS JOIN?

"A Cartesian product occurs when every row in the first table is combined with every row in the second
table. For example, if the first table has 3 rows and the second table has 4 rows, the result will have 12
rows (3 x 4)."

4. Can you use multiple JOINs in a single query?

"Yes, you can use multiple JOINs in a single query to combine more than two tables. The order of the
JOINs matters, and the logic of how they combine rows should be considered carefully."

3. Explain Normalization?
Normalization is the process of organizing data in a database to reduce redundancy and improve data
integrity. It involves dividing a database into smaller tables and defining relationships between them.
The main goal of normalization is to ensure that data is stored efficiently and consistently.

Why is Normalization Important?

1. Minimizes Redundancy: Eliminates duplicate data, saving storage space.

2. Ensures Data Integrity: Maintains consistency in the data by ensuring dependencies are properly
enforced.

3. Improves Query Performance: Simplifies database structure, making queries more efficient.

4. Simplifies Maintenance: Easier to update and maintain the database due to reduced complexity.

Types (Forms) of Normalization

Normalization is achieved through a series of steps called normal forms (NF). Each normal form builds
upon the previous one. The most commonly used are:

1. First Normal Form (1NF):

Objective: Eliminate duplicate columns and ensure each column contains atomic (indivisible) values.

Rules:

 Each table cell must contain a single value.

 Each record must be unique.

Example (Before Normalization):

OrderID CustomerName Product1 Product2

1 Alice Laptop Phone

2 Bob TV NULL

After Normalization:

OrderID CustomerName Product

1 Alice Laptop

1 Alice Phone

2 Bob TV
2. Second Normal Form (2NF):

Objective: Ensure that all non-key attributes are fully functionally dependent on the primary key. Partial
dependencies are removed.

Rules:

 Must meet all requirements of 1NF.

 Non-key attributes should depend on the whole primary key, not just a part of it.

Example (Before Normalization):

OrderID ProductID ProductName CustomerName

1 101 Laptop Alice

2 102 TV Bob

Problem: ProductName depends only on ProductID, not on OrderID + ProductID.

After Normalization:

 Split the table into two:

1. Product Table:

ProductID ProductName

101 Laptop

102 TV

2. Order Table:

OrderID ProductID CustomerName

1 101 Alice

2 102 Bob

3. Third Normal Form (3NF):

Objective: Remove transitive dependencies, where non-key attributes depend on other non-key
attributes.

Rules:

 Must meet all requirements of 2NF.

 No transitive dependency (a non-key attribute should not depend on another non-key attribute).

Example (Before Normalization):


EmployeeID EmployeeName DepartmentID DepartmentName

1 John D01 HR

2 Sarah D02 Finance

Problem: DepartmentName depends on DepartmentID, not directly on EmployeeID.

After Normalization:

 Split the table into two:

1. Employee Table:

EmployeeID EmployeeName DepartmentID

1 John D01

2 Sarah D02

2. Department Table:

DepartmentID DepartmentName

D01 HR

D02 Finance

4. Boyce-Codd Normal Form (BCNF):

Objective: A stricter version of 3NF, ensuring that every determinant is a candidate key.

Rule:

 For every functional dependency (X → Y), X must be a superkey.

Higher Normal Forms:

 4NF: Removes multi-valued dependencies.

 5NF: Deals with join dependencies and ensures no loss of data after decomposition.

 6NF: Ensures no non-trivial dependencies exist, used rarely in practice.

Advantages of Normalization

1. Data Consistency: Reduces chances of anomalies (insert, update, delete).

2. Efficient Storage: Eliminates unnecessary duplication.


3. Scalability: Simplifies database maintenance and extension.

4. Improved Query Performance: Smaller tables mean faster queries.

Disadvantages of Normalization

1. Complex Queries: Data spread across multiple tables can require complex joins.

2. Performance Overhead: Too many joins can slow down performance.

3. Storage Considerations: May require more metadata for keys and relationships.

4. Difference between DROP, DELETE and TRUNCATE?

The SQL commands DROP, DELETE, and TRUNCATE are used to remove data or database objects.

1. DROP

 Definition: Removes the entire database object (e.g., table, database, or index) from the
database.

 Operation: Deletes the structure of the table along with all its data.

 Rollback: Not reversible (no rollback possible).

 DDL- Data Definition Language.

 Syntax: DROP TABLE table_name;

 Use Case: Use when you want to completely remove a table or database and no longer need it.

Example: DROP TABLE employees;

 This will delete the employees table, including all its data and structure.

2. DELETE

 Definition: Deletes specific rows from a table based on a condition.

 Operation: Removes data only; the table structure remains intact.

 DML- Data Manipulation Language.

 Rollback: Reversible if wrapped in a transaction (if COMMIT is not executed).

 Syntax: DELETE FROM table_name WHERE condition;

(Without a WHERE clause, it deletes all rows but keeps the table structure.)
 Use Case: Use when you want to delete specific records or all records from a table while
retaining the table structure.

Example: DELETE FROM employees WHERE department = 'HR';

 Deletes all employees from the employees table where the department is HR.

3. TRUNCATE

 Definition: Removes all rows from a table, but keeps the table structure intact.

 Operation: Resets the table, clearing all data faster than DELETE.

 DDL- Data Definition Language

 Rollback: Not reversible in most databases (behaves like DROP in terms of recovery).

 Syntax: TRUNCATE TABLE table_name;

 Use Case: Use when you want to quickly remove all rows from a table without logging individual
row deletions.

Example: TRUNCATE TABLE employees;

 Deletes all rows in the employees table, but the table structure remains.

Key Differences

Feature DROP DELETE TRUNCATE

Removes table structure Deletes all rows but retains


Scope Deletes specific rows or all rows.
and data. structure.

Not reversible in most


Rollback Not reversible. Reversible if within a transaction.
databases.

Fast (removes
Speed Slower (logs each row deletion). Faster (minimal logging).
everything).

Can delete specific rows using Deletes all rows (no


Condition Not applicable.
WHERE. WHERE).

Frees space allocated to Does not free space; only marks


Space Freed Frees all allocated space.
the table. rows as deleted.

Table
Deleted along with data. Retained. Retained.
Structure
When to Use Each

1. DROP: Use when you no longer need the table or database.

o Example: Dropping an outdated or backup table.

2. DELETE: Use when you need to remove specific rows or records based on a condition.

o Example: Deleting inactive user accounts from a user table.

3. TRUNCATE: Use when you need to quickly remove all data from a table and reset it for reuse.

o Example: Clearing log tables after archiving their contents.

Common Interview Questions

1. Can you use WHERE with TRUNCATE?

Answer: No, TRUNCATE removes all rows in the table and does not support a WHERE clause. Use DELETE
if you need to delete specific rows.

2. Which is faster, TRUNCATE or DELETE? Why?

Answer: TRUNCATE is faster because it does not log individual row deletions, only the deallocation of
pages. DELETE logs each deleted row, making it slower.

3. Can you rollback TRUNCATE?

Answer: In most databases, TRUNCATE cannot be rolled back as it does not log individual row deletions.
However, in some databases that support transactional DDL (e.g., SQL Server with an active transaction),
it may be possible.

4. What happens to table constraints with DROP?

Answer: Dropping a table also removes all constraints, indexes, and relationships associated with it.

What is LIMIT & OFFSET in SQL?


LIMIT and OFFSET are used to control the number of rows returned in a query, particularly useful for
pagination and fetching specific rows.

1.LIMIT – Restrict the Number of Rows

 LIMIT is used to restrict the number of records returned by a query.

 It is commonly used in MySQL, PostgreSQL, and SQLite.


Example: Fetch only the first 5 records from the Employee table.

SELECT *

FROM Employee

LIMIT 5;

✅ Output: Returns only 5 rows.

2️.OFFSET – Skip Rows Before Fetching Data

 OFFSET is used to skip a specific number of rows before returning results.

 Usually used with LIMIT to implement pagination.

Example: Fetch records 6 to 10 (skip first 5 records).

SELECT *

FROM Employee

LIMIT 5 OFFSET 5;

✅ Explanation:

 OFFSET 5 → Skips the first 5 rows.

 LIMIT 5 → Fetches the next 5 rows.

Write a query to fetch the nth record from a table.


SELECT *

FROM employees

ORDER BY employee_id

LIMIT 1 OFFSET 5;

Write a query to find departments with the highest average salary.

SELECT DepartmentID
FROM Employee
GROUP BY DepartmentID
ORDER BY AVG(Salary) DESC
LIMIT 1;

Write a query to find employees whose salaries are higher than their managers.
SELECT e.EmployeeID, e.Salary
FROM Employee e
JOIN Employee m ON e.ManagerID = m.EmployeeID
WHERE e.Salary > m.Salary;

You might also like