📒
Notes
Cloud ComputingData Science/AIGame Development
  • Home
  • Big O
  • Data Structures & Algorithms
    • Data Structures
      • Array
      • Stack
      • Queue
      • Linked List
      • Binary Tree
    • Algorithms
      • Searching
      • Sorting
      • Graphs
        • Searching
        • Minimum Spanning Tree
        • Shortest Path Algorithms
      • String Algorithms
  • Object Oriented Programming
  • Languages
    • HTML/CSS
      • CSS
    • C++
    • C#
      • Types
      • Keywords
        • Modifiers
          • Access Modifiers
        • Method Parameters
      • Operators and Expressions
      • Collections
      • Constructors
      • Delegates
      • Indexers
      • Concepts
      • Features
        • LINQ
          • Operators
          • Working with Data
          • Methods
          • Resources
        • Asynchronous Programming
        • Reflection
    • Dart
    • GraphQL
    • JavaScript
      • Variable and Parameter
      • Built-in objects
        • Array
        • Built-in Functions
      • Functions
      • Classes
      • Prototype
      • Libraries
        • jQuery
        • React
          • Components
          • State and Lifecycle
          • Hooks
            • useState
            • useEffect
          • Resources
      • Testing Framework
      • Web APIs
    • Kotlin
      • Basics
    • Python
      • Basics
      • Data Structures
      • Functions
      • Resources
        • Flask
    • SQL
      • Basics
      • Operators
      • JOINs
      • Aggregations
      • Subqueries
      • Views
      • Functions
        • Window Functions
      • Stored Procedures
      • Performance Tuning
      • Extras
    • Resources
  • 🌐Web Frameworks
    • Angular
      • Templates
      • Directives
        • Attribute Directives
        • Structural Directives
    • ASP.NET
      • Fundamentals
        • Dependency Injection
        • Middleware
        • Session & State Management
      • Web apps
        • MVC
          • Controllers
            • Filters
          • Models
            • Model Binding
            • Model Validation
          • Views
            • Tag Helpers
            • View Components
          • Features
        • Client-side development
      • Web APIs
        • Controller-based APIs
        • Minimal APIs
        • OpenAPI
        • Content Negotiation
      • SignalR
      • Host and Deploy
        • IIS
      • Security
    • Django
      • The Request/Response Cycle
    • Terminologies
      • Web Server
        • Internet Information Services
    • Resources
  • 📱App Frameworks
    • Introduction
      • Resources
    • Xamarin
      • Lifecycle
      • Custom Renderers & Effects
      • Behaviors
      • Triggers
      • Gestures
      • Commands
      • Dependency Service in XF
      • Libraries
      • Showcase
    • .NET MAUI
      • Controls
      • Navigation
      • Storage Options
  • Multi-Platform Frameworks
    • .NET
      • .NET Framework
        • ADO.NET
        • WCF
      • Fundamentals
        • Logging
        • Testing
      • Advanced
        • Asynchronous Programming
        • Parallel Programming
        • Threading
        • Memory Management
          • Garbage Collection
    • Flutter
  • Object-Relational Mappers
    • Entity Framework
      • Application Models
      • Configuration
      • Setting Up
      • Advanced
  • Databases
    • Introduction
      • DBMS Architecture
      • Normalization
      • Database Transaction Models
    • Relational Databases
      • Microsoft SQL Server
        • Basics
        • Functions
        • Stored Procedures
        • Error Handling
        • Log Shipping
        • Querying and Manipulating JSON data
        • Statements
        • Topics
        • Extras
    • Non-Relational Databases
      • MongoDB
      • Redis
        • Data Structures
        • Introduction
        • Managing Database
  • Tools
    • Version Control
      • Git
        • Setup and Config
        • Basics
          • Sharing and Updating Projects
        • Resources
      • Perforce Helix
    • GitHub
    • Powershell
  • Software Development
    • Software Development Life Cycle
    • Software Design Patterns
      • GoF Design Patterns
      • Architectural Patterns
        • MVC
        • MVVM
        • N-tier Architecture
        • Onion Architecture
        • Data Transfer Objects
      • CQRS
    • Software Design Principles
      • S.O.L.I.D. Priniciple
  • System Design
    • Topics
      • Load Balancing
  • Topics
    • JWT
    • Caching
      • Static vs Dynamic Caching
    • OSI model
      • HTTP
    • Glossary
    • API
      • SOAP
      • REST
    • Microservices
    • WebHooks
    • Practice
    • Operating Systems
      • Windows
    • Architecture
  • 🔖Bookmarks
  • 🔗Resources
Powered by GitBook
On this page
  • Subquery Basics
  • Subquery: Placement
  • Subquery: Dependencies

Was this helpful?

  1. Languages
  2. SQL

Subqueries

a query within a query.

PreviousAggregationsNextViews

Last updated 2 years ago

Was this helpful?

When do you need to use a subquery?

You need to use a subquery when you have the need to manipulate an existing table to "pseudo-create" a table that is then used as a part of a larger query.

Components
Subqueries
Joins

Combine data from multiple tables into a single result

Create a flexible view of tables stitched together using a “key”

Build an output to use in a later part of the query

Subquery Plan: What happens under the hood

Subquery Basics

When a subquery, typically in the form of a nested or inline subquery, is correlated to its outer query, it cannot run independently. This is most certainly an edge case since correlated subqueries are rarely implemented compared to standalone, simple subqueries.

Subquery: Placement

  • WITH: This subquery is used when you’d like to “pseudo-create” a table from an existing table and visually scope the temporary table at the top of the larger query.

A Common Table Expression (CTE) in SQL allows you to define a temporary result, such as a table, to then be referenced in a later part of the query.

  • Nested: This subquery is used when you’d like the temporary table to act as a filter within the larger query, which implies that it often sits within the WHERE clause.

  • Inline: This subquery is used in the same fashion as the WITH use case above. However, instead of the temporary table sitting on top of the larger query, it’s embedded within the FROM clause.

  • Scalar: This subquery is used when you’d like to generate a scalar value to be used as a benchmark of some sort.

Nested & Scalar subqueries often do not require aliases the way WITH & Inline subqueries do.

  • When a user wants to create a version of an existing table to be used in a larger query

WITH average_price AS
( SELECT brand_id, AVG(product_price) AS brand_avg_price
  FROM product_records
),
SELECT a.brand_id, a.total_brand_sales, b.brand_avg_price
FROM brand_table a
JOIN average_price b
ON b.brand_id = a.brand_id
ORDER BY a.total_brand_sales DESC;
  • When a user wants to filter an output using a condition met from another table.

SELECT *
FROM students
WHERE student_id
IN (SELECT DISTINCT student_id
    FROM gpa_table
    WHERE gpa > 3.5);
  • Inline subqueries create a “pseudo table” that aggregates or manipulates an existing table to be used in a larger query.

SELECT dept_name, max_gpa
FROM department_db x
     (SELECT dept_id, MAX(gpa) AS max_gpa
      FROM students
      GROUP BY dept_id
      ) y
WHERE x.dept_id = y.dept_id
ORDER BY dept_name;
  • It selects only one column or expression and returns one row, used in the select clause of the main query

SELECT 
   (SELECT MAX(salary) 
    FROM employees_db) AS top_salary,
   employee_name
FROM employees_db;
  • If a scalar subquery does not find a match, it returns a NULL.

  • If a scalar subquery finds multiple matches, it returns an ERROR.

For example, when you’d like to calculate the average salary across an entire organization to compare to individual employee salaries. Because it’s often a single value that is generated and used as a benchmark, the scalar subquery often sits within the SELECT clause.

Advantages:

  • Readability: WITH and Nested subqueries are most advantageous for readability.

  • Performance: Scalar subqueries are advantageous for performance and are often used on smaller datasets.

Subquery: Dependencies

  • Simple Subquery: The inner subquery is completely independent of the larger query.

  • Correlated Subquery: The inner subquery is dependent on the larger query.

When to use Correlated Query ?

When the value of the inner query is dependent on a value outputted from the main query (e.g., the filter statement constantly changes).

SELECT first_name, last_name, GPA, university
FROM student_db outer_db
WHERE GPA >
    (SELECT AVG(GPA) 
    FROM student_db 
    WHERE university = outer_db.university);

In the example above, you’ll notice that the value of the inner query -- average GPA -- keeps adjusting depending on the university the student goes to. THAT is a great use case for the correlated subquery.

CoRelated Subquery
Non-CoRelated Subquery

The inner query or subquery references the outer query.

The inner query doesn't depend on the outer query and can run as a stand-alone query.

The outer query executes before the inner query.

The inner query executes before the outer query.

Correlated subqueries are slower than Non-Correlated subqueries and should be avoided as much as possible.

Subquery Basics
Subquery Strategy