Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Derived Tables with Nested Subqueries in FROM | Nested Subqueries in the FROM section
Generate Nested Subqueries in SQL

Derived Tables with Nested Subqueries in FROM

Pyyhkäise näyttääksesi valikon

Derived tables, also known as subqueries in the FROM clause, allow you to create a temporary result set that can be referenced as a table within your main query. This approach is especially useful when you need to break down complex logic into manageable steps or reuse aggregated data. By nesting a subquery in the FROM section, you can simplify intricate queries and make your SQL more modular.

123456789101112131415161718
-- Calculate total sales per product, then filter for products with sales above $100 SELECT dt.product_id, p.product_name, dt.total_sales FROM ( SELECT product_id, SUM(total_amount) AS total_sales FROM sales GROUP BY product_id ) AS dt JOIN products p ON dt.product_id = p.product_id WHERE dt.total_sales > 100;

Using derived tables in this way helps you organize your queries into logical building blocks. Instead of repeating calculations or making your main query overly complex, you can write a subquery that handles aggregation or filtering, then build on top of it. This leads to more readable, maintainable, and reusable SQL code, especially when working with multi-step data analysis.

1234567891011121314151617181920
-- Join a derived table of total sales per product with product categories for enriched analysis SELECT pc.category_name, p.product_name, dt.total_sales FROM ( SELECT product_id, SUM(total_amount) AS total_sales FROM sales GROUP BY product_id ) AS dt JOIN products p ON dt.product_id = p.product_id JOIN product_categories pc ON p.category_id = pc.category_id ORDER BY pc.category_name, dt.total_sales DESC;

1. What is the main purpose of using a subquery in the FROM clause?

2. How can derived tables be used in SQL joins?

3. Fill in the blanks to select product names and their total sales using a subquery in the FROM clause:

question mark

What is the main purpose of using a subquery in the FROM clause?

Valitse oikea vastaus

question mark

How can derived tables be used in SQL joins?

Valitse oikea vastaus

question-icon

Fill in the blanks to select product names and their total sales using a subquery in the FROM clause:

= p.
Returns a list of product names with their total sales, such as:

| product_name | total_sales |
|----------------------|-------------|
| Smartphone | 1199.98 |
| Laptop | 1999.98 |
| Bluetooth Headphones | 149.99 |
| ... | ... |

Klikkaa tai vedä ja pudota esineitä ja täytä tyhjät kohdat

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 2. Luku 1

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Osio 2. Luku 1
some-alt