1. How do nested queries and subqueries work in SQL? Give an example.
Nested queries, or subqueries, are SQL queries embedded within another SQL query. They
allow you to perform complex data retrieval by breaking it into manageable parts. A
subquery can provide data to the outer query as a condition, value, or derived table.
Example: Non-Correlated Subquery
Let’s say you have a table students with columns like student_id, name, and score. If you
want to find students whose scores are above the class average, you can use a subquery like
this:
SELECT student_id, name, score
FROM students
WHERE score > (SELECT AVG(score) FROM students);
Here, the inner query (SELECT AVG(score) FROM students) calculates the average score of all
students. The outer query then uses this result to filter the rows, returning only those
students whose scores are greater than the average.
Example: Correlated Subquery
Now, imagine you have another column class_id to indicate which class a student belongs to.
If you want to find the highest-scoring student in each class, a correlated subquery can help:
SELECT s.student_id, s.name, s.score, s.class_id
FROM students s
WHERE s.score = (
SELECT MAX(score)
FROM students
WHERE class_id = s.class_id
);
In this case, the inner query depends on the outer query since it uses s.class_id. For every
row in the students table, the subquery finds the maximum score within the same class_id.
The outer query then returns the rows where the student’s score matches this maximum.
Subqueries in Other Clauses
You can also use subqueries in other parts of an SQL query, such as the FROM clause:
SELECT class_id, avg_score
FROM (
SELECT class_id, AVG(score) AS avg_score
FROM students
GROUP BY class_id
) AS class_avg
WHERE avg_score > 50;
In this example, the subquery creates a derived table containing the average scores for each
class. The outer query then filters out classes with an average score below 50.
Subqueries offer flexibility and can be very powerful for complex tasks, such as filtering,
aggregation, or even constructing temporary tables. Would you like to explore any specific
use case or learn about alternatives like Common Table Expressions (CTEs)?
2. What are set operations in SQL? Explain UNION, INTERSECT, and EXCEPT with
examples.
Set operations in SQL are used to combine results from two or more queries. They allow you
to manipulate data by treating query outputs as sets, just like in mathematics. The main set
operations are UNION, INTERSECT, and EXCEPT, and all of them require that the queries
have the same number of columns with compatible data types.
Here’s a breakdown of each operation:
1. UNION
The UNION operator combines the results of two queries into a single result set, removing
duplicates by default (similar to a mathematical union). If you want to include duplicates,
you can use UNION ALL.
Example
Suppose you have two tables: students_math and students_science, which list student
names enrolled in math and science classes.
SELECT name
FROM students_math
UNION
SELECT name
FROM students_science;
This query returns all unique student names from both students_math and
students_science. If duplicates are acceptable, use:
SELECT name
FROM students_math
UNION ALL
SELECT name
FROM students_science;
2. INTERSECT
The INTERSECT operator returns the rows that are common to both queries—i.e., the
intersection of two result sets.
Example
Using the same tables:
SELECT name
FROM students_math
INTERSECT
SELECT name
FROM students_science;
This query finds the students who are enrolled in both math and science classes.
3. EXCEPT
The EXCEPT operator returns rows from the first query that are not in the second query—
i.e., it performs subtraction in set theory.
Example
If you want to find students enrolled in math but not science:
SELECT name
FROM students_math
EXCEPT
SELECT name
FROM students_science;
This query gives you names of students who are in students_math but not in
students_science.
3. What is an updatable view and a non-updatable view in SQL? Explain with examples.
Views in SQL are virtual tables that consist of columns and rows derived from one or more
tables. They are commonly used to simplify complex queries or restrict access to specific
columns or rows. Views can be classified as updatable or non-updatable, depending on
whether modifications (such as INSERT, UPDATE, or DELETE) can be performed through the
view.
Updatable View
An updatable view allows changes to the underlying base table(s) via the view. For a view to
be updatable:
1. It must directly reference a single table.
2. It cannot contain aggregate functions, GROUP BY, DISTINCT, HAVING, or UNION.
3. Columns in the view must map one-to-one to columns in the base table.
4. There must not be complex expressions or computations in the view's definition.
Example
Consider a table employees:
employee_id name department salary
1 Alice HR 50000
2 Bob IT 70000
Create an updatable view for employees in the HR department:
CREATE VIEW hr_employees AS
SELECT employee_id, name, salary
FROM employees
WHERE department = 'HR';
Now you can update the salary for HR employees directly through the view:
UPDATE hr_employees
SET salary = 55000
WHERE name = 'Alice';
The change in the view updates the corresponding data in the employees table.
Non-Updatable View
A non-updatable view cannot modify the base table(s). This is usually because the view’s
definition involves features that do not directly map to the base table's structure, such as
aggregations, multiple tables, or computed columns.
Example
Consider a view that calculates the average salary for each department:
CREATE VIEW avg_salary AS
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department;
This view is non-updatable because:
• It uses the AVG() aggregate function.
• It groups data by department.
Attempting an update like this:
UPDATE avg_salary
SET avg_salary = 60000
WHERE department = 'HR';
Would result in an error, as changes cannot be propagated to the base table.