0% found this document useful (0 votes)
5 views

SQL Interview Ques-Ans

The document provides a comprehensive overview of SQL concepts, including basic queries, filtering, sorting, joins, aggregation, subqueries, indexes, data modification, constraints, normalization, and window functions. It includes examples of SQL queries for each topic, explaining their usage and importance in database management. The content serves as a guide for understanding SQL operations and best practices.

Uploaded by

Suhani Rana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

SQL Interview Ques-Ans

The document provides a comprehensive overview of SQL concepts, including basic queries, filtering, sorting, joins, aggregation, subqueries, indexes, data modification, constraints, normalization, and window functions. It includes examples of SQL queries for each topic, explaining their usage and importance in database management. The content serves as a guide for understanding SQL operations and best practices.

Uploaded by

Suhani Rana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

https://www.linkedin.

com/in/vivek-kumar-singh-6a32a3190/
For More: Vivek Kumar Singh

1. Basic SQL Queries:

- Write a query to retrieve all columns from a table named "Customers."


SELECT * FROM Customers;

- How do you fetch distinct values from a column in SQL?


To retrieve distinct values from a column, you can use the DISTINCT keyword.
SELECT DISTINCT column_name FROM table_name;

- Write a query to calculate the total number of records in a table.


To count the total number of records in a table, you can use the COUNT()
function.
SELECT COUNT(*) FROM table_name;

2. Filtering and Sorting:

- How can you retrieve records from a table where a specific condition is met?
You can use the WHERE clause to filter records based on specific conditions.
SELECT * FROM table_name WHERE condition;

- Explain the difference between the WHERE and HAVING clauses in SQL.
The WHERE clause filters rows before grouping, while the HAVING clause filters
rows after grouping.
The WHERE clause is used in a SQL query to filter rows from a table based on a
specific condition. It operates on individual rows before the data is grouped or
aggregated. It's commonly used to restrict the result set to rows that meet
certain criteria.
The HAVING clause is used in a SQL query to filter the result set after it has been
grouped by using GROUP BY. It operates on aggregated data, allowing you to
filter groups based on conditions. It's often used to restrict the result set to
aggregated values that meet specific criteria.
https://www.linkedin.com/in/vivek-kumar-singh-6a32a3190/
For More: Vivek Kumar Singh

- Write a query to retrieve the top 5 highest values from a column.


To retrieve the top N highest values from a column, you can use the ORDER BY
clause with the LIMIT or FETCH FIRST clause.
SELECT column_name FROM table_name ORDER BY column_name DESC LIMIT
5;

3. Joins and Relationships:

- What are different types of joins in SQL? Explain with examples.


In SQL, joins are used to combine rows from different tables based on related
columns between them. There are several types of joins:

1. INNER JOIN:
An INNER JOIN returns only the rows that have matching values in both tables.
Example:
Suppose you have two tables, "Customers" and "Orders," and you want to
retrieve customers who have placed orders.

SELECT Customers.CustomerName, Orders.OrderDate


FROM Customers
INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

2. LEFT JOIN (or LEFT OUTER JOIN):


A LEFT JOIN returns all rows from the left table and matching rows from the
right table. If there's no match, NULL values are returned for columns from the
right table.
Example:
Retrieve all customers and their orders, including customers without orders.

SELECT Customers.CustomerName, Orders.OrderDate


FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

3. RIGHT JOIN (or RIGHT OUTER JOIN):


A RIGHT JOIN is similar to a LEFT JOIN, but it returns all rows from the right table
and matching rows from the left table. Non-matching rows from the left table
have NULL values.
https://www.linkedin.com/in/vivek-kumar-singh-6a32a3190/
For More: Vivek Kumar Singh

Example:
Retrieve all orders and their corresponding customers, including orders without
customers.

SELECT Orders.OrderID, Customers.CustomerName


FROM Orders
RIGHT JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

4. FULL JOIN (or FULL OUTER JOIN):


A FULL JOIN returns all rows from both tables. If there's a match, the values are
returned; if not, NULL values are returned.
Example:
Retrieve all customers and their orders, including unmatched customers and
orders.

SELECT Customers.CustomerName, Orders.OrderDate


FROM Customers
FULL JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

5. CROSS JOIN (or CARTESIAN JOIN):


A CROSS JOIN returns the Cartesian product of two tables, meaning every row
from the first table is combined with every row from the second table.
Example:
If you have a "Colors" table and a "Sizes" table, a CROSS JOIN would create
combinations of every color with every size.

SELECT Colors.ColorName, Sizes.SizeName


FROM Colors
CROSS JOIN Sizes;
https://www.linkedin.com/in/vivek-kumar-singh-6a32a3190/
For More: Vivek Kumar Singh

- How do you find records that exist in one table but not in another using SQL?
You can use the LEFT JOIN and IS NULL condition to find records that exist in one
table but not in another.

SELECT Customers.CustomerName
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
WHERE Orders.CustomerID IS NULL;

- Explain the concept of a self-join and when it might be used.


A self-join is when a table is joined with itself. It's useful when you want to
compare records within the same table, such as finding pairs of customers with
the same city.

SELECT a.CustomerName, b.CustomerName


FROM Customers a, Customers b
WHERE a.City = b.City AND a.CustomerID < b.CustomerID;

4. Aggregation:

- Write a query to calculate the average, sum, and count of a specific column.
You can use the AVG(), SUM(), and COUNT() functions for aggregation.
SELECT AVG(column_name), SUM(column_name), COUNT(column_name) FROM
table_name;

- How do you group records in SQL? Provide an example.


The GROUP BY clause is used to group rows with the same values in specified
columns.
SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name;

- What is the purpose of the GROUP BY clause in SQL?


The GROUP BY clause is used to group rows that share the same values in
specified columns, allowing aggregate functions to be applied to each group
separately.
https://www.linkedin.com/in/vivek-kumar-singh-6a32a3190/
For More: Vivek Kumar Singh

5. Subqueries and Nested Queries:

- Explain the concept of a subquery in SQL.


A subquery is a query nested inside another query. It's used to retrieve data
that will be used by the main query.
SELECT column_name
FROM table_name
WHERE column_name IN (SELECT column_name FROM another_table);

- Write a query to retrieve records from one table based on conditions from
another table.
You can use a subquery to achieve this.
SELECT column_name
FROM table_name
WHERE column_name = (SELECT column_name FROM another_table WHERE
condition);

- What are correlated subqueries and how are they different from regular
subqueries?
Correlated subqueries are subqueries that reference columns from the outer
query. Unlike regular subqueries, they depend on the outer query's results.

6. Indexes and Performance Optimization:

- What is an index in a database? Why is it important?


An index is a database structure that improves data retrieval speed by providing
a quick way to look up rows based on the values in certain columns. Indexes are
crucial for optimizing query performance.

- How do you improve the performance of a slow-running SQL query?


You can optimize slow queries by creating appropriate indexes, rewriting
inefficient queries, and using EXPLAIN to analyze query execution plans.
https://www.linkedin.com/in/vivek-kumar-singh-6a32a3190/
For More: Vivek Kumar Singh

- Explain the advantages and disadvantages of using indexes.


Advantages: Faster data retrieval, improved query performance.
Disadvantages: Increased storage and maintenance overhead, potentially
slower data modification.

7. Data Modification:

- Write a SQL query to update records in a table.


UPDATE table_name
SET column_name = new_value
WHERE condition;

- How do you delete records from a table using SQL?


DELETE FROM table_name WHERE condition;

- What is the purpose of the COMMIT statement in SQL transactions?


The COMMIT statement is used to save changes made within a transaction to
the database. It makes changes permanent.

8. Data Integrity and Constraints:

- What are constraints in SQL? Provide examples.


Constraints are rules applied to columns in a table to ensure data integrity.
Examples include PRIMARY KEY, UNIQUE, NOT NULL, and FOREIGN KEY
constraints.

- How do you enforce data integrity using constraints?


By applying constraints like NOT NULL, UNIQUE, and FOREIGN KEY, you ensure
that data follows predefined rules, maintaining data integrity.

- Explain the differences between PRIMARY KEY and UNIQUE constraints.


PRIMARY KEY enforces uniqueness and not null, and it's a table's main
identifier. UNIQUE enforces uniqueness but allows null values.
https://www.linkedin.com/in/vivek-kumar-singh-6a32a3190/
For More: Vivek Kumar Singh

9. Normalization and Database Design:

- What is database normalization? Why is it important?


Normalization is the process of organizing data to minimize redundancy and
dependency issues. It ensures data integrity and efficient storage.

- Explain the first three normal forms (1NF, 2NF, 3NF) with examples.
1. First Normal Form (1NF):
First Normal Form (1NF) ensures that the data in a table is organized without any
duplicate columns and that each column holds atomic values (values that cannot
be divided further).

For a table to be in 1NF, each cell must contain a single, indivisible value. There
should be no repeating groups or arrays within a single cell.

Example:
Consider a table with a denormalized structure:
| StudentID | Courses |
|-----------|--------------------------|
|1 | Math, Physics, Chemistry |
|2 | English, Biology |

This table violates 1NF because the "Courses" column contains multiple values
separated by commas. To convert it to 1NF, you'd split the courses into separate
rows:

| StudentID | Course |
|-----------|--------------|
|1 | Math |
|1 | Physics |
|1 | Chemistry |
|2 | English |
|2 | Biology |
https://www.linkedin.com/in/vivek-kumar-singh-6a32a3190/
For More: Vivek Kumar Singh

2. Second Normal Form (2NF):


Second Normal Form (2NF) deals with partial dependencies. A table is in 2NF if it's
in 1NF and every non-key attribute is fully functionally dependent on the entire
primary key, rather than just a part of it.

Example:
Consider a table with student grades:

| StudentID | Course | Instructor | Grade |


|-----------|--------------|------------|-------|
|1 | Math | Mr. A | A |
|1 | Physics | Mr. B | B |
|2 | Math | Mr. A | C |
|2 | Physics | Mr. B | A |

Here, the primary key is (StudentID, Course), and "Instructor" is functionally


dependent only on "Course," not the entire primary key. To achieve 2NF, you'd
split this into separate tables:

Table 1: Students

| StudentID |
|-----------|
|1 |
|2 |

Table 2: Courses

| Course | Instructor |
|-----------|------------|
| Math | Mr. A |
| Physics | Mr. B |
https://www.linkedin.com/in/vivek-kumar-singh-6a32a3190/
For More: Vivek Kumar Singh

Table 3: Grades

| StudentID | Course | Grade |


|-----------|--------|-------|
|1 | Math | A |
|1 | Physics| B |
|2 | Math | C |
|2 | Physics| A |

3. Third Normal Form (3NF):


Third Normal Form (3NF) deals with transitive dependencies. A table is in 3NF if
it's in 2NF and every non-key attribute is non-transitively dependent only on the
primary key.

Example:
Consider a table with employee information:

| EmployeeID | Department | DepartmentManager | ManagerPhone |


|------------|-------------|-------------------|--------------|
| 101 | Sales | John | 123-456-7890|
| 102 | Marketing | Mary | 987-654-3210|

Here, "ManagerPhone" is transitively dependent on "Department" through


"DepartmentManager." To achieve 3NF, you'd separate this into multiple tables:

Table 1: Employees

| EmployeeID | Department | DepartmentManager |


|------------|-------------|-------------------|
| 101 | Sales | John |
| 102 | Marketing | Mary |
https://www.linkedin.com/in/vivek-kumar-singh-6a32a3190/
For More: Vivek Kumar Singh

Table 2: Managers

| DepartmentManager | ManagerPhone |
|-------------------|--------------|
| John | 123-456-7890|
| Mary | 987-654-3210|

By doing this, you eliminate transitive dependencies and ensure 3NF.

1NF: Eliminate duplicate columns.


2NF: Eliminate partial dependencies.
3NF: Eliminate transitive dependencies.

10. Window Functions and Analytic Queries:

- What are window functions in SQL? Provide examples.


Window functions perform calculations across a set of table rows related to the
current row. Example: Calculating a running total.

- Write a query to calculate the running total using a window function.


SELECT OrderDate, OrderAmount, SUM(OrderAmount) OVER (ORDER BY
OrderDate) AS RunningTotal
FROM Orders;

- Explain the difference between ROW_NUMBER, RANK, and DENSE_RANK


functions.

The ROW_NUMBER function assigns a unique number to each row in the result
set based on the specified ordering. It starts with 1 and increments by 1 for each
subsequent row. If multiple rows have the same values in the ordering columns,
they receive distinct row numbers.

The RANK function assigns a unique rank to each row based on the specified
ordering. If multiple rows have the same values in the ordering columns, they
receive the same rank, and the next rank is skipped.
https://www.linkedin.com/in/vivek-kumar-singh-6a32a3190/
For More: Vivek Kumar Singh

The DENSE_RANK function is similar to RANK, but it doesn't skip ranks when
multiple rows have the same values in the ordering columns. Instead, it assigns
the same rank to those rows and then continues with the next rank.

So, ROW_NUMBER assigns a unique number to each row. RANK gives the same
rank to equal values but leaves gaps. DENSE_RANK gives the same rank to equal
values without gaps.

Good Luck!
Vivek Kumar Singh

You might also like