Hello! Welcome to the fifth module of our course, "SQL for Data Interrogation."
In the previous module, we focused on modeling business processes and system logic using tools like BPMN, context diagrams, and decision tables. We learned how to define what a system should do. Now, we're shifting gears to learn how to ask questions of the data that these systems generate. This is a critical skill for any Business Analyst, as it allows you to perform independent analysis, validate your findings with hard data, and provide data-driven recommendations to your stakeholders.
Today's lesson is your first step into the world of SQL (Structured Query Language). Our goal is to learn how to write SELECT statements with WHERE clauses to query and filter data from single tables. By the end of this lesson, you will be able to retrieve specific pieces of information from a dataset and filter it down to find exactly what you need.
What is SQL? Basic Concepts
Before we write our first query, let's establish some fundamental concepts. In the simplest terms, SQL is the language we use to communicate with databases. As a Business Analyst, you won't be building databases, but you will frequently need to pull data from them.
Beginner SQL Concepts for Digital Marketers
This article from Seer Interactive provides clear, non-technical definitions of the core components we'll be working with. It's a great starting point before we dive into the syntax.
Please read the section 'Basic SQL Concepts', which includes the definitions for 'What is a Database?', 'What is a Table?', and 'What is a Query?'. The analogy of an Excel workbook and its sheets is quite helpful here.
To recap, a database is a structured collection of data. Inside a database, data is organized into tables, which consist of columns (attributes) and rows (records). We use a query to ask the database for specific data.
Writing Your First Query: SELECT and FROM
The most fundamental SQL query consists of two main parts:
SELECT: Specifies the columns you want to retrieve.FROM: Specifies the table you want to retrieve the columns from.
The basic syntax is:SELECT column1, column2 FROM table_name;
If you want to see all columns in a table, you can use an asterisk (*) as a shortcut:SELECT * FROM table_name;
Let's imagine you're working with a table called ad_campaigns in your company's database. To see the name and budget of every campaign, you would write:
SELECT campaign_name, budget
FROM ad_campaigns;
To see all information available for every campaign, you would write:
SELECT *
FROM ad_campaigns;
A quick tip: Real-world tables can contain millions of rows. It's good practice to add a LIMIT clause at the end of your query to only retrieve a small sample, preventing you from accidentally trying to load a massive dataset.
SELECT *
FROM ad_campaigns
LIMIT 10; -- This will show only the first 10 rows.
Filtering Data with the WHERE Clause
Retrieving all the data from a table is a good start, but the real power of SQL lies in filtering. As a BA, you'll constantly need to find records that meet specific business criteria. This is where the WHERE clause comes in.
The WHERE clause is added after the FROM clause and allows you to specify conditions that rows must meet to be included in the result.
The structure is:SELECT column(s) FROM table_name WHERE condition;
Let's watch a video that breaks down the most common ways to build these conditions.
Where Clause in MySQL | Beginner MySQL Series
This video from 'Alex The Analyst' is an excellent, beginner-friendly introduction to the WHERE clause. It covers the essential operators you'll use every day.
Watch from the beginning to 04:23. The video will walk you through: Basic filtering with the equals operator (=). Comparison operators (>, <, >=, <=) for numbers. The 'not equal' operator (!= or <>). Filtering on date columns.
Key Comparison Operators
As you just saw, you can use various operators in your WHERE clause:
| Operator | Description | Example |
|---|---|---|
= |
Equal to | WHERE status = 'Active' |
!= or <> |
Not equal to | WHERE country != 'USA' |
> |
Greater than | WHERE budget > 5000 |
< |
Less than | WHERE clicks < 100 |
>= |
Greater than or equal to | WHERE budget >= 5000 |
<= |
Less than or equal to | WHERE start_date <= '2023-01-01' |
Important Note: Text values (also called strings) must be enclosed in single quotes (e.g., 'Active'). Numbers do not need quotes.
Combining Conditions with AND, OR, and NOT
Often, a single condition isn't enough. You might need to find campaigns that are active and have a budget over $5000. Or perhaps you need to see campaigns targeting the 'USA' or 'Canada'. For this, we use logical operators.
AND: All conditions must be true.OR: At least one of the conditions must be true.NOT: Reverses the result of a condition.
Let's continue with the video to see how these are used in practice and learn about the crucial role of parentheses ().
Where Clause in MySQL | Beginner MySQL Series
We'll continue with the same video to see how to build more complex filters.
Watch from 04:23 to 07:46. Pay close attention to how parentheses are used to group conditions. This is fundamental for ensuring your query logic is correct, just like in mathematics (PEMDAS).
For example, to find all active campaigns with a budget over $5000, you would write:
SELECT *
FROM ad_campaigns
WHERE status = 'Active' AND budget > 5000;
To find campaigns in either the 'USA' or 'Canada' that are paused, you need to use parentheses to group the OR condition correctly:
SELECT *
FROM ad_campaigns
WHERE status = 'Paused' AND (country = 'USA' OR country = 'Canada');
Without the parentheses, the query would be interpreted incorrectly.
Advanced Filtering: LIKE, IN, BETWEEN, and IS NULL
Let's cover a few more powerful tools for your WHERE clause.
Pattern Matching with LIKE
The LIKE operator is used to search for a specified pattern in a column. This is incredibly useful when you don't know the exact text value. It uses two wildcards:
%: Represents zero, one, or multiple characters._: Represents a single character.
Let's see how LIKE works.
Where Clause in MySQL | Beginner MySQL Series
The final segment of the 'Alex The Analyst' video explains the LIKE operator for pattern matching, which is very useful for searching text fields.
Watch from 07:46 to the end (12:06). This section covers how to use the '%' and '_' wildcards to find partial matches in your data.
For instance, to find all campaigns whose names contain the word 'Summer', you'd write:WHERE campaign_name LIKE '%Summer%';
IN, BETWEEN, and IS NULL
These operators provide convenient shortcuts for common filtering tasks.
How to Filter with the WHERE clause in SQL
This video from 'Becoming a Data Scientist' demonstrates a few more essential operators that make your queries cleaner and more powerful.
Watch from 07:44 to 10:55. This will cover: BETWEEN: For filtering within a range (inclusive). IN: For filtering against a list of values. IS NULL: For finding rows with missing data (a very common BA task!).
Here's a summary:
BETWEEN: Selects values within a given range. The values can be numbers, text, or dates.WHERE budget BETWEEN 5000 AND 10000;(equivalent tobudget >= 5000 AND budget <= 10000)
IN: Specifies a list of possible values for a column.WHERE country IN ('USA', 'Canada', 'UK');(a much cleaner way to writecountry = 'USA' OR country = 'Canada' OR country = 'UK')
IS NULL: Checks for empty or missing values. You cannot use= NULL.WHERE completion_date IS NULL;(finds campaigns that have not yet been completed)WHERE completion_date IS NOT NULL;(finds campaigns that have a completion date)
Time to Practice!
Let's apply what you've learned. The following exercises use a simple database for a store. The key table for now is product, which contains columns like product_name, unit_price, and category_id.
SQL for Data Analysis: 15 Practical Exercises with Solutions
This article from LearnSQL provides a set of practical exercises. We will focus on the first few that deal with single-table queries.
Read the section 'Single Table Queries' and review Exercises 2 and 3. Try to write the solution yourself before looking at the provided answer.
Test your understanding!
Now, let's use a scenario from your AdTech background. Imagine you have a table named campaign_performance with the following columns:
campaign_name(text)status(text: 'Active', 'Paused', 'Ended')ctr(number, Click-Through Rate, e.g., 0.05)start_date(date)
Your Task: Write an SQL query to find all campaigns that meet the following criteria:
- Are either 'Active' or 'Paused'.
- Have a Click-Through Rate (
ctr) below 0.02. - Are NOT named 'Test Campaign'.
Show answer
Here is one possible solution. There can be multiple correct ways to write a query.
SELECT *
FROM campaign_performance
WHERE
status IN ('Active', 'Paused')
AND ctr < 0.02
AND campaign_name != 'Test Campaign';
Alternative for the first condition:WHERE (status = 'Active' OR status = 'Paused')
Alternative for the third condition:WHERE campaign_name <> 'Test Campaign' or WHERE NOT campaign_name = 'Test Campaign'
Conclusion
Congratulations on completing your first lesson in SQL! You've taken a significant step toward becoming a more data-savvy Business Analyst.
Key Takeaways:
- The basic structure of a query is
SELECT(columns)FROM(table). - The
WHEREclause is your primary tool for filtering data to find specific records. - You can filter on numbers, text, and dates using comparison operators like
=,>, and!=. - You can combine conditions using
ANDandOR, using parentheses()to ensure the logic is correct. - Operators like
LIKE,IN,BETWEEN, andIS NULLprovide powerful and convenient ways to handle more complex filtering needs.
Preview of the Next Lesson:
Now that you can select and filter your data, the next step is to make the results clear and readable. In our next lesson, we will learn how to sort and limit query results using ORDER BY and LIMIT. This will allow you to organize your output, find top/bottom performers, and present your findings in a more structured way.