Subqueries in sql
Subqueries/ Inner queries/ Nested Queries:
A SQL subquery is a query nested within another SQL statement. Whenever we want to retrieve data based on the result of another query, we use nested queries
When to Use SQL Subqueries?
Subqueries can be especially useful in the following scenarios:
- When a query needs to perform a calculation or retrieve a value from another table without using a join.
- When a query's condition depends on aggregated data.
- When combining results from multiple tables in complex ways.
- When working with conditional logic, such as retrieving data that meets certain criteria based on other data.
Advantages of SQL Subqueries
- Simplicity: Subqueries can make complex queries easier to read and understand by breaking them down into smaller parts.
- Modularity: Subqueries can be reused and modified without affecting the outer query.
- Flexibility: Subqueries provide a way to retrieve data without the need for joins.
Disadvantages of SQL Subqueries
- Performance: Subqueries can be less efficient than joins, especially in large datasets, as they may execute multiple times.
- Complexity: Correlated subqueries can become complex and difficult to optimize.
1. Write a query to find the persons who have a salary greater than the minimum salary
select name, salary from employees
where salary > (select Min(salary) from employees)
2. Find the employees with the minimum age
select name, age from employees
where age > (select MIN(age) from employees)
3. Find the employees with the average age and the ages of the employees
select name, age, (select avg(age) as avg_age from employees) from employees
Comments
Post a Comment