Learning Objectives
By the end of this lesson, learners should be able to:
- Explain the purpose and structure of SQL.
- Retrieve data using SELECT statements.
- Filter records using WHERE.
- Sort results using ORDER BY.
- Remove duplicate results using DISTINCT.
- Use comparison and logical operators.
- Apply SQL expressions and aliases.
- Work with NULL values.
- Use basic string, numeric and date functions.
- Interpret SQL query results in a business context.
1. Introduction to SQL
SQL (Structured Query Language) is a language used to interact with relational databases.
Business analysts can use SQL to:
- Retrieve information.
- Filter records.
- Combine data.
- Summarize results.
- Investigate business questions.
- Prepare analytical datasets.
SQL is therefore one of the most important technical skills for data-driven business analysis.
2. Basic SQL Structure
A simple query may look like:
SELECT Customer_Name, Region
FROM Customers;
The query asks the database to return selected columns from the Customers table.
The main clauses are:
- SELECT
- FROM
- WHERE
- ORDER BY
- GROUP BY
- HAVING
The first lessons focus primarily on data retrieval and filtering.
3. SELECT
SELECT specifies the columns to retrieve.
Example:
SELECT Customer_Name, Region
FROM Customers;
This returns only the requested columns.
4. Selecting All Columns
The * symbol can be used to select all columns.
SELECT *
FROM Customers;
Although convenient for exploration, selecting only required columns is often preferable for production analysis because it:
- Reduces unnecessary data transfer.
- Improves readability.
- Makes the query’s purpose clearer.
5. FROM
The FROM clause identifies the table or data source from which records are retrieved.
Example:
SELECT Product_Name
FROM Products;
The query retrieves Product_Name from Products.
6. DISTINCT
DISTINCT removes duplicate combinations from the returned result.
Example:
SELECT DISTINCT Region
FROM Customers;
This can help answer:
Which regions currently appear in the customer dataset?
However, DISTINCT should not be used automatically to hide duplicate rows caused by an incorrect join.
7. WHERE
WHERE filters records according to specified conditions.
Example:
SELECT *
FROM Customers
WHERE Region = ‘Nairobi’;
This returns customers whose region is Nairobi.
8. Comparison Operators
Common SQL comparison operators include:
- =
- <>
- >
- <
- >=
- <=
Example:
SELECT *
FROM Products
WHERE Price > 5000;
This retrieves products priced above 5,000.
9. Logical Operators
Multiple conditions can be combined using:
- AND
- OR
- NOT
Example:
SELECT *
FROM Customers
WHERE Region = ‘Nairobi’
AND Customer_Type = ‘Corporate’;
Both conditions must be satisfied.
10. Operator Precedence
Logical conditions require careful interpretation.
For example:
WHERE Region = ‘Nairobi’
OR Region = ‘Mombasa’
AND Customer_Type = ‘Corporate’
The database may evaluate AND before OR.
To make business logic explicit, parentheses should be used:
WHERE (Region = ‘Nairobi’ OR Region = ‘Mombasa’)
AND Customer_Type = ‘Corporate’;
This distinction can materially change analytical results.
11. ORDER BY
ORDER BY sorts query results.
Example:
SELECT Product_Name, Price
FROM Products
ORDER BY Price DESC;
DESC sorts from highest to lowest.
ASC sorts from lowest to highest.
12. Multiple Sorting Fields
Results can be sorted using multiple columns.
SELECT Customer_Name, Region
FROM Customers
ORDER BY Region ASC, Customer_Name ASC;
The database first sorts by Region and then by Customer_Name within each region.
13. Aliases
An alias provides a temporary name for a column or table in a query.
Example:
SELECT Price AS Unit_Price
FROM Products;
Aliases improve readability in analytical outputs.
14. Calculated Columns
SQL can perform calculations.
Example:
SELECT Quantity, Unit_Price,
Quantity * Unit_Price AS Sales_Value
FROM Order_Details;
This creates a calculated value without necessarily storing it permanently in the database.
15. Arithmetic Operators
Common arithmetic operators include:
- +
- –
- *
- /
For example:
SELECT Revenue – Cost AS Gross_Profit
FROM Financial_Data;
Business analysts frequently use calculated fields to derive metrics.
16. NULL Values
NULL represents missing, unknown or unavailable information.
It is not equivalent to:
- Zero.
- An empty string.
- False.
This distinction is important.
For example, a missing payment amount is not automatically equivalent to a payment of zero.
17. Testing for NULL
The correct approach is generally:
WHERE Phone_Number IS NULL;
or:
WHERE Phone_Number IS NOT NULL;
Using:
Phone_Number = NULL
does not correctly test for NULL.
18. BETWEEN
BETWEEN can be used to test whether a value falls within a range.
Example:
SELECT *
FROM Products
WHERE Price BETWEEN 1000 AND 5000;
The exact treatment of boundary values should be understood when using ranges.
19. IN
IN allows a value to be compared against a list.
Example:
SELECT *
FROM Customers
WHERE Region IN (‘Nairobi’, ‘Kiambu’, ‘Kisumu’);
This is often more readable than repeatedly using OR.
20. LIKE
LIKE is used for pattern matching.
For example:
SELECT *
FROM Customers
WHERE Customer_Name LIKE ‘A%’;
This searches for names beginning with A.
The exact wildcard behavior can depend on the SQL implementation.
21. String Functions
SQL implementations commonly provide functions for manipulating text.
Examples include functions that can:
- Convert case.
- Extract portions of strings.
- Determine string length.
- Concatenate text.
These can help clean or standardize business data.
22. Numeric Functions
SQL also provides functions for numerical analysis.
Examples may include:
- Rounding.
- Absolute values.
- Mathematical calculations.
For example:
SELECT ROUND(Revenue, 2)
FROM Sales;
The exact functions available may vary across database systems.
23. Date Functions
Business analysis frequently requires date manipulation.
Analysts may need to:
- Extract year.
- Extract month.
- Compare dates.
- Calculate periods.
- Group transactions by time.
For example:
SELECT Order_Date
FROM Orders;
can retrieve transaction dates for subsequent analysis.
24. LIMIT
Some SQL systems support LIMIT to restrict the number of returned rows.
Example:
SELECT *
FROM Products
ORDER BY Price DESC
LIMIT 10;
This can help identify the ten highest-priced products.
Different database systems may use different syntax for limiting results.
25. SQL and Business Questions
A business analyst should begin with the business question, not the SQL syntax.
For example:
Business question:
Which products have prices above KSh 10,000?
SQL:
SELECT Product_Name, Price
FROM Products
WHERE Price > 10000;
The SQL is simply the mechanism used to answer the business question.
26. SQL Query Accuracy
A query can be syntactically valid but analytically incorrect.
For example:
A query may execute successfully but:
- Count duplicate customers.
- Exclude important records.
- Misinterpret NULL values.
- Apply an incorrect date range.
- Use the wrong business definition.
Therefore:
Successful execution does not guarantee analytical correctness.
27. Query Validation
Business analysts should validate SQL results by asking:
- Does the row count make sense?
- Are expected records present?
- Are duplicates expected?
- Are NULL values affecting the result?
- Does the date range match the question?
- Does the result agree with known business totals?
Validation is a critical part of analytical work.
28. SQL Comments
Comments can document SQL logic.
For example:
— Retrieve high-value products
SELECT Product_Name, Price
FROM Products
WHERE Price > 10000;
Clear documentation improves maintainability.
29. SQL and Data Exploration
SQL is particularly useful during exploratory analysis.
An analyst may begin by examining:
- Number of records.
- Available categories.
- Date ranges.
- Missing values.
- Minimum and maximum values.
- Distinct values.
This helps determine whether the dataset is suitable for the intended analysis.
30. Practical Business Example
Suppose a company wants to identify corporate customers in Nairobi.
A query could be:
SELECT Customer_ID, Customer_Name
FROM Customers
WHERE Region = ‘Nairobi’
AND Customer_Type = ‘Corporate’;
The query directly translates the business conditions into SQL logic.
Lesson Summary
SQL allows business analysts to retrieve and manipulate relational data.
Core SQL concepts include:
- SELECT
- FROM
- WHERE
- DISTINCT
- ORDER BY
- AND
- OR
- NOT
- IN
- BETWEEN
- LIKE
- IS NULL
- Aliases.
- Calculated columns.
- Basic functions.
However, SQL competence is not merely about writing syntactically correct queries. The analyst must ensure that the query accurately represents the underlying business question.