SQL Fundamentals for Analysts: SELECT, WHERE, GROUP BY, JOIN, and HAVING
What You'll Learn
- 1Compose SELECT queries with filters, sorts, and calculated columns
- 2Aggregate correctly with GROUP BY and HAVING
- 3Join tables with clear cardinality and null awareness
- 4Write readable, consistent analytical SQL habits
SQL is the lingua franca of analytics because business data lives in relational tables and warehouses. Mastering select, filter, group, and join lets you answer most operational questions directly at the source. Consistent style and grain awareness separate trustworthy metrics from accidental double counts.
SELECT, WHERE, and Expressions
The select list defines output columns, aliases, and computed expressions such as revenue times quantity. Where filters rows before grouping and supports comparison, ranges, null checks, and boolean logic with and, or, and not. Order by sorts the final result, while limit or top caps rows for previews.
Filter on sargable predicates so the database can use indexes, and remember null uses three valued logic, so equality tests against null never match. Cast types deliberately when comparing dates, numbers, or text codes across sources.
GROUP BY, Aggregates, and HAVING
Group by partitions rows into buckets for aggregates such as count, sum, avg, min, and max. Every non aggregated column in the select list must appear in group by in standard SQL engines. Having filters groups after aggregation, whereas where filters rows before aggregation.
State the grain of your result in a comment or naming convention, for example daily revenue by channel. Use distinct counts carefully: sessions, users, and orders are different entities and often need different deduplication logic.
JOINs and Practical Patterns
Inner join keeps matching keys, left join keeps all left rows with nulls where unmatched, and cross join multiplies every pair. Know the cardinality of each relationship, one to many or many to many, before joining, because many to many joins inflate measures. Always null pad unmatched dimensions when required for reporting completeness.
Date tables, customer snapshots, and late arriving facts deserve extra care with filters placed on the correct side of outer joins. Debug by checking row counts after each join step rather than only inspecting the final numbers.
JOIN Types at a Glance
| Join | Keeps | Common Analytic Use |
|---|---|---|
| Inner join | Rows matching in both sides | Filtering to valid related records only |
| Left join | All left rows plus matches | Facts with optional dimensions |
| Right join | All right rows plus matches | Rarely needed; prefer flipping sides |
| Full outer join | All rows from both sides | Reconciliation between two systems |
| Cross join | Every combination | Scenario grids and date scaffolds |
| Self join | Same table twice | Parent child and prior period comparisons |
Real-World Examples
- Revenue by month â Group orders by calendar month and sum net amount to build a trend that ties to finance close numbers.
- Funnel conversion â Count distinct users at each stage, then divide adjacent stages to get step conversion rates.
- Left join customers â Left join orders to customers so new orders without profile rows still appear with a null segment instead of vanishing.
- HAVING threshold â Filter grouped products to those with more than one hundred units sold using having on the aggregated count.
â¨Comment the Grain
Common Mistakes
Filtering dimensions on the wrong join side
Fix: A where clause on a right table after left join turns it into an inner join; push dimension filters into the join condition or use an exists subquery when intent differs.
Double counting via bad joins
Fix: Fanout from one to many joins multiplies facts; aggregate at the right level first or use distinct measures with clear semantics.
Using where after aggregation mentally
Fix: Where cannot reference aggregates; use having or a subquery so filter intent matches SQL evaluation order.
Key Takeaways
- Select defines outputs, where filters rows, having filters groups.
- Join cardinality decides whether measures inflate or stay correct.
- Comment grain and use consistent aliases for reusable metric queries.
- Nulls and date logic are common sources of silent result errors.
Frequently Asked Questions
Why does my total double after a join?
You likely joined a one to many path that duplicated fact rows. Check join keys and aggregate before joining, or restructure the model.
Difference between where and having?
Where filters individual rows before aggregation; having filters aggregated groups after group by is applied.
How do I handle nulls in joins?
Decide whether nulls mean missing or not applicable. Coalesce display values, and understand how inner versus outer joins treat unmatched rows.
Interview Questions
Q1: Write a query for monthly revenue by region for the last twelve months.
Select region and month, sum net amount as revenue, join orders to a date table and region dimension, filter the date window in where, group by region and month, order by month desc, and document the grain as region by month.
Q2: How do you debug a slow analytical query?
Inspect the execution plan, check filter sargability and join order, verify indexes or partition pruning, reduce selected columns, and confirm statistics are current before rewriting logic.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type â Always start by categorizing the problem
- Incorrect formula application â Verify the formula applies to your specific case
- Unit errors â Always check units are consistent throughout
- Sign errors â Pay careful attention to positive and negative values
- Rounding too early â Keep full precision until the final answer
- Forgetting constraints â Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic â Build on the foundation laid here
- Next Topic â See how this concept extends to more advanced material
- Practice Problems â Additional exercises with solutions
- Video Explanation â Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions