💻
notes
  • Initial page
  • sql
    • date-and-time
    • Ordering Columns
    • Replacing Portions of Text
    • count-rows
    • Changing the Case of Strings
    • Create Excerpts with Substring
    • Transactions
    • removing-data
    • Finding Length of Strings
    • add-row-to-a-table
    • limit-and-paginate-results
    • Concatenating Strings
    • SQL JOINs
    • basic-math
    • updating-rows-in-a-table
    • Subqueries
    • Set Operations
    • SQL Basics Cheatsheet
  • ruby
    • gems
      • Auto use Ruby version with gemset
      • Must Have Gems
      • Create Devise user without any validation
    • rails
      • What are the differences between #where and #find?
  • postgresql
    • Export database dump from Heroku and import to local database
  • glossary
  • vim
    • Edit Recorded Macros
    • Sort Multiple Lines
    • Search and Replace
    • Folding
  • iTerm
  • git
    • Git
  • Command Line Utilities
  • How To Use Notes
  • Terminal Cheatsheet for Mac
Powered by GitBook
On this page

Was this helpful?

  1. sql

Subqueries

Subqueries are queries within queries. A subquery can also be called an inner query with the "parent" query being called the outer query.

There are two main ways to use a subquery:

  1. In an IN condition

  2. As a derived or temporary table

A subquery in an IN condition must only have one column.

SELECT <columns> FROM <table 1>
  WHERE <table 1>.<column> IN (<subquery>);

SELECT <columns> FROM <table 1>
  WHERE <table 1>.<column> IN (
    SELECT <a single column>
    FROM <table 2>
      WHERE <condition>);

Examples:

Get a list of user's names and emails for users who have spent over 100 dollars in a single transaction.

SELECT name, email FROM users
  WHERE id IN (SELECT DISTINCT(user_id)
                FROM sales
                WHERE saleAmount > 100);

// OR

SELECT name, email FROM users
  INNER JOIN (SELECT DISTINCT(user_id)
    FROM sales
    WHERE saleAmount > 100)
  AS best_customers
  ON users.id = best_customers.user_id;

Get a list of user's names and emails for users who have spent over 1000 dollars in total.

SELECT name, email FROM users
  WHERE id IN (
    SELECT user_id FROM sales
    WHERE SUM(saleAmount) > 1000 GROUP BY user_id);

// OR

SELECT name, email, total FROM users
  INNER JOIN (SELECT user_id, SUM(saleAmount) AS total FROM sales
    WHERE total > 1000 GROUP BY user_id) AS ultimate_customers
    ON users.id = ultimate_customers.user_id;
Previousupdating-rows-in-a-tableNextSet Operations

Last updated 5 years ago

Was this helpful?