SQL Sub-Queries


Intro

You can create a SELECT statement within a SELECT statement to make a more complex query

Sample Data

These are the tables we will use as an example:

SELECT * 
FROM ar_invoices
invoice# customer# salesperson# invoice_date invoice_amount amount_paid current_month_interest_charges total_interest_charges
1112019-06-17 10:43:53.727100.001.000.000.00
2222019-05-28 10:43:53.72750.000.005.0010.00
3322019-06-17 10:43:53.72770.000.0010.0020.00
4212019-07-07 10:43:53.72780.000.000.000.00
SELECT * 
FROM ar_salespeople
salesperson# salesperson_name
1bob
2mary
3tim
SELECT * 
FROM ar_customers
customer# customer_name customer_address customer_province customer_rating
1bill 123 main st. ab1
2ed 456 main st. bc2
3john 789 main st. ab3

Nested Column

This nested SELECT acts like a column and only returns one value

SELECT salesperson#,
	   invoice_amount,
	   (SELECT AVG(invoice_amount) AS Average FROM ar_invoices) AS Average
FROM ar_invoices
salesperson# invoice_amount Average
1100.0075.000000
250.0075.000000
270.0075.000000
180.0075.000000

Nested Table

This nested SELECT acts like a table and can return multiple rows

SELECT salesperson#,
	   invoice_amount,
	   (SELECT AVG(invoice_amount) AS Average FROM ar_invoices) AS Average
FROM ar_invoices
salesperson# invoice_amount Average
1100.0075.000000
250.0075.000000
270.0075.000000
180.0075.000000

Special Operators

FILL THIS IN
  • EXISTS
  • ANY
  • ALL