Subqueries Vs Temp Tables
Subqueries Vs Temp Tables
VS
Subquery runs
Results of the subquery
replace the subquery
Outer query executes
AN EXAMPLE
Subquery in
parenthesis
PROs
Simplest option for filtering or
performing calculations on data
within a query
Often have good performance
CONs
Can make complex queries
harder to read and understand
Not reusable in the same query
WHAT IT IS
CREATE TEMPORARY
TABLE statement
Write query with results
you want stored
Use the temp table like
you would any table
AN EXAMPLE
PROs
Act like regular tables for storing
intermediate results
Can be accessed by multiple
queries within the same session
Useful for complex data
manipulation with multiple steps
CONs
Disappear after the session ends
Data is physically stored
WHAT IT IS
A named temporary
result set
Used in SELECT, INSERT,
UPDATE, or DELETE
Exists for the duration of
a single query
HOW IT WORKS
Create first
CTE using
WITH clause
Following CTEs are
separated by a comma
PROS & CONS
PROs
Improve readability by breaking
complex queries into named
result sets
Can be reused multiple times
within a single query
Support recursive queries
CONs
Limited to a single query (not
accessible by other queries in the
session)
WHAT IT ALL
MEANS