Join two SELECT statement results
Use a Common Table Expression (CTE) JOIN:
This code utilizes CTEs cradled within a WITH clause, and then performs a JOIN operation on the common id
field between them.
Advanced joining methods
With a bit more craft, you can turn the JOIN operation into a power tool:
Implementing left join
In this example, LEFT JOIN includes even those persons who have been model citizens with no late tasks. COALESCE conveniently deals with any NULL values resulting from the LEFT JOIN.
Aggregate functions and conditional statements
This code aggregates total and late tasks per person. COUNT(*) is the SQL version of a crowd control officer, tallying up all tasks for each person. SUM(CASE WHEN...) is the strict parent, only counting those tasks submitted after due_date.
Tackling complex join scenarios
When the going gets tough, use UNION ALL and nifty SQL conditionals:
UNION ALL for inclusive results
When the shared key between your selects is playing hide and seek, use UNION ALL:
This gives you everything on the menu, duplicates included. Remember to keep your column numbers and order consistent, and use aliases to achieve unified column naming.
Conditional logic within JOIN
Including conditional statements directly in the ON clause can work magic to shape the JOIN's outcome.
Real-world scenarios
In daily SQL operations, keep these pointers in your programming backpack:
Need for RIGHT or FULL OUTER JOIN
You may need a RIGHT JOIN if you must include all records from the RIGHT table, or a FULL OUTER JOIN for a full, unabridged version of your data:
Handling rogue duplicates and elusive order
Use SELECT DISTINCT to strike off duplicates, or ORDER BY to usher your results into a pleasing arrangement:
Merging data from disparate data sources
Have data from different table that need to play nicely together? No problem:
Was this article helpful?