SQL for Data Analysis
๐ SQL for Data Reporting and Analysis
This guide assumes zero prior SQL knowledge and uses entirely free tools. By the end, the reader will be able to retrieve data from databases and write complex queries efficiently.
๐ง Why Learn SQL?
All businesses store data in databases.
SQL (Structured Query Language) is the standard language for interacting with databases.
SQL enables retrieving, filtering, sorting, adding, updating, and removing data.
Anyone can learn SQLโno computer science degree required.
Applying SQL unlocks hidden insights in data, useful for roles such as business analyst, product manager, or researcher.
๐๏ธ What Is a Database?
A database is a collection of tables that have relationships with each other.
Major websites (e.g., Facebook, Twitter, LinkedIn) are powered by databases.
Example: The Kevin Cookie Company uses databases to track customers, orders, and product information.
Relational Database Management System (RDBMS)
An RDBMS is software used to interface with a database.
Popular options: Oracle, PostgreSQL, Microsoft SQL Server, MySQL.
This tutorial uses Microsoft SQL Server (Developer or Express edition) because:
Developer edition: full functionality, free, but only for development/testing.
Express edition: also free, limited to 10 GB database size and 4 cores, can be used for business.
Once one RDBMS is learned, core SQL concepts transfer to others with minor syntax differences.
๐ง Setting Up the Environment
1. Install SQL Server
Download Microsoft SQL Server (Developer or Express) from the official site.
Run the installer and choose Basic (or Custom/Download Media).
After installation, verify SQL Server is running via Configuration Manager (Start > All Apps > Microsoft SQL Server ... > Configuration Manager).
The SQL Server service should show a running state with start mode set to Automatic.
2. Install SQL Server Management Studio (SSMS)
SSMS is a graphical front end for writing queries.
Download it from the official site (free).
Launch SSMS; a Connect to Server prompt appears.
Server name: your PC name (can browse for it).
Authentication: Windows Authentication.
Click Connect.
3. Restore a Sample Database
Download a sample database backup file (e.g., for Kevin Cookie Company).
In SSMS Object Explorer, right-click Databases > Restore Database.
Choose Device, locate the backup file, and click OK.
The restored database (e.g.,
KCC) appears under Databases.
๐ Understanding Database Structure
Tables, Fields, Records
In Object Explorer, expand the database โ Tables.
Each table contains:
Fields (columns): represent attributes (e.g., CustomerName, Address).
Records (rows): individual data entries.
Tables are broken into separate entities to avoid repetitionโthis is called normalization.
Why Normalize?
A flat file repeats customer and product information many times.
Normalization splits data into separate tables (e.g., Customers, Orders, Products) connected by IDs.
Benefits: less storage space, easier data maintenance.
Schema
Every table belongs to a schema (here
dbo, the default).Schemas group tables and can control access permissions.
๐ Key Database Concepts
Primary Key
The primary key is the minimum number of columns that uniquely identifies each record in a table.
Example: In the
Customerstable,CustomerIDuniquely identifies each customer (name alone cannot because names may repeat).In the
Orderstable,OrderIDis the primary key;CustomerIDcan repeat (one customer can have many orders).A composite primary key uses multiple columns (e.g., in
OrderProducttable, bothOrderIDandProductIDtogether are needed).
Relationships Between Tables
Tables are related via foreign keys (e.g.,
Orders.CustomerIDreferencesCustomers.CustomerID).Database diagrams in SSMS visually show these relationships.
Expand Database Diagrams to see existing diagrams.
Symbols: key icon = primary key; infinity symbol = one-to-many relationship.
Data Types
Each column has a data type (e.g., integer, varchar, date).
View in design mode: right-click table > Design.
Important for queries: comparing/filtering must match the type (e.g., cannot compare integer column with letters).
โ๏ธ Writing Basic SQL Queries
SELECT Statement
SELECTretrieves data from a table.Syntax:
SELECT column1, column2 FROM table_nameExample:
SELECT CustomerName FROM dbo.CustomersUse
*to select all columns:SELECT * FROM dbo.Customers
Executing Queries
In SSMS, click New Query (Ctrl+N) or press F5 to execute.
Ensure the correct database is selected in the dropdown (e.g.,
KCC).Alternatively, qualify the table with database and schema:
KCC.dbo.Customers.
Column Aliases
Rename a column in the output using
AS:SELECT CustomerName AS [Customer Name] FROM dbo.Customers
DISTINCT
Removes duplicate rows from the result:
SELECT DISTINCT CustomerName FROM dbo.Customers
TOP
Limits the number of rows returned:
SELECT TOP 3 * FROM dbo.Customers
Comments
Single-line:
-- commentMulti-line:
/* comment */
๐ Filtering Data with WHERE
Basic WHERE
Filters rows based on a condition:
SELECT * FROM dbo.Customers WHERE State = 'Washington'
Comparison Operators
=equal,!=or<>not equal>greater than,<less than,>=greater than or equal,<=less than or equalExample:
WHERE OrderTotal > 1000
Logical Operators: AND, OR, IN, NOT IN
Combine conditions:
SELECT * FROM dbo.Customers WHERE State = 'Washington' OR State = 'New York'Simpler with
IN:WHERE State IN ('Washington', 'New York', 'Utah')Opposite:
NOT INUse parentheses to control evaluation order:
WHERE CustomerName = 'Tres Delicious' AND (Country = 'United States' OR Country = 'France')
Pattern Matching: LIKE
LIKEmatches patterns using%(any number of characters) and_(single character).Example: Names starting with 'A':
WHERE CustomerName LIKE 'A%'Negate with
NOT LIKE.
BETWEEN
Inclusive range for numeric or date values:
WHERE OrderTotal BETWEEN 1000 AND 2000
๐ Joining Tables
Joins combine data from multiple tables based on a related column.
INNER JOIN
Returns only rows that have matching values in both tables.
If you write only
JOIN, it defaults toINNER JOIN.Example: Orders with Customer details
SELECT O.OrderID, O.OrderDate, O.OrderTotal, C.CustomerName, C.Phone FROM dbo.Orders AS O INNER JOIN dbo.Customers AS C ON O.CustomerID = C.CustomerID
LEFT OUTER JOIN / RIGHT OUTER JOIN
LEFT OUTER JOIN: Returns all rows from the left table, and matching rows from the right table. If no match, right columns show
NULL.RIGHT OUTER JOIN: Oppositeโall rows from the right table.
Example: See all customers even if they have no orders:
SELECT O.OrderID, C.CustomerName FROM dbo.Orders O RIGHT OUTER JOIN dbo.Customers C ON O.CustomerID = C.CustomerID
Handling Ambiguous Columns
When both tables have a column with the same name (e.g.,
CustomerID), prefix with table alias:C.CustomerIDorO.CustomerID.
๐ Sorting with ORDER BY
ORDER BY column [ASC|DESC]sorts results.Default is ascending (
ASC).Example:
SELECT * FROM dbo.Orders ORDER BY OrderTotal DESC
๐ Using Functions
Date Functions
GETDATE()returns the current date and time.DATEADD(interval, number, date)adds/subtracts time.Example: Orders from the last month:
SELECT * FROM dbo.Orders WHERE OrderDate >= DATEADD(month, -1, GETDATE())
Aggregate Functions
COUNT(*)counts rows.SUM(column)totals a numeric column.AVG(column)average,MIN,MAX.
GROUP BY
Groups rows that have the same values in specified columns, often used with aggregates.
Example: Total revenue per customer in the last month:
SELECT CustomerID, SUM(OrderTotal) AS TotalRevenue FROM dbo.Orders WHERE OrderDate >= DATEADD(month, -1, GETDATE()) GROUP BY CustomerID
๐ฅ๏ธ Using the Query Designer
The Query Designer in SSMS helps build queries visually without writing SQL manually.
Right-click in query editor > Design Query in Editor.
Select tables to include.
Choose columns by checking them; the designer automatically generates the
SELECT,JOIN, and other clauses.Add aliases, filters, sort orders, and grouping in the grid.
After closing the designer, the generated SQL can be executed.
โ Summary of Key SQL Syntax
Operation | Syntax Example |
|---|---|
Select columns |
|
All columns |
|
Distinct |
|
Top rows |
|
Filter |
|
Pattern match |
|
Range |
|
List |
|
Sort | `ORDER BY Col ASC |
Inner join |
|
Outer join | `LEFT |
Grouping |
|
Functions |
|
๐ Next Steps
Practice writing queries on the sample database.
Experiment with different join types and aggregate functions.
Use the Query Designer to explore complex queries and then examine the generated SQL to learn by example.
Key takeaway: SQL is a powerful, accessible tool for uncovering insights from data. With the concepts covered hereโquerying, filtering, joining, aggregating, and groupingโanyone can start extracting meaningful information from databases.

Ask anything
We've read this whole study set, so questions about it get the best answers.