Subqueries in FROM and SELECT Clauses
Subqueries in FROM and SELECT Clauses
1. Aim
To understand and implement subqueries (nested queries) in the FROM clause and SELECT clause of SQL statements.
2. Theory
A subquery is a query within another SQL query. Depending on its placement, it can serve different purposes.
2.1 Subquery in the FROM Clause
-
When a subquery appears in the FROM clause, it is treated as a temporary table (also called a derived table).
-
Useful for performing complex calculations first, then querying the result.
2.2 Subquery in the SELECT Clause
-
Returns a single scalar value for each row of the outer query.
-
Useful for adding computed fields like counts, averages, or maximum values.
3. Table Schema Setup
Insert Sample Data
4. Subqueries in the FROM Clause
Example 1: Authors whose average book price is above 15
Output:
| AuthorID | AvgPrice |
|---|---|
| 1 | 15.00 |
| 3 | 25.00 |
Example 2: Maximum book price per author
Output:
| AuthorID | Name | MaxPrice |
|---|---|---|
| 1 | Author One | 20.00 |
| 2 | Author Two | 15.00 |
| 3 | Author Three | 25.00 |
Example 3: Count of books priced above the average price
5. Subqueries in the SELECT Clause
Example 1: Show each author with the number of books they have written
Output:
| Name | TotalBooks |
|---|---|
| Author One | 2 |
| Author Two | 1 |
| Author Three | 1 |
Example 2: Display each book with the average price of all books
Example 3: Show each book with the highest book price
6. Combined Example (FROM + SELECT)
7. Results
-
Successfully executed subqueries in FROM and SELECT clauses.
-
Understood how derived tables and scalar subqueries enhance SQL query capability.
-
Demonstrated complex data processing using nested queries.
8. Conclusion
Subqueries in the FROM and SELECT clauses are powerful SQL tools that allow advanced computations, filtering, and data analysis. They enable breaking down complex logic into smaller, manageable parts within a single SQL statement.
Comments
Post a Comment