1. Home
  2. Explore
  3. Computer Science
  4. SQL for Data Analysis

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

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 Customers table, CustomerID uniquely identifies each customer (name alone cannot because names may repeat).

  • In the Orders table, OrderID is the primary key; CustomerID can repeat (one customer can have many orders).

  • A composite primary key uses multiple columns (e.g., in OrderProduct table, both OrderID and ProductID together are needed).

Relationships Between Tables

  • Tables are related via foreign keys (e.g., Orders.CustomerID references Customers.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

  • SELECT retrieves data from a table.

  • Syntax:

    SELECT column1, column2 FROM table_name
  • Example:

    SELECT CustomerName FROM dbo.Customers
  • Use * 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: -- comment

  • Multi-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 equal

  • Example: 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 IN

  • Use parentheses to control evaluation order:

    WHERE CustomerName = 'Tres Delicious' AND (Country = 'United States' OR Country = 'France')

Pattern Matching: LIKE

  • LIKE matches 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 to INNER 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.CustomerID or O.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

SELECT Col1, Col2 FROM Table

All columns

SELECT * FROM Table

Distinct

SELECT DISTINCT Col FROM Table

Top rows

SELECT TOP N * FROM Table

Filter

WHERE Condition

Pattern match

WHERE Col LIKE 'A%'

Range

WHERE Col BETWEEN X AND Y

List

WHERE Col IN (v1, v2)

Sort

`ORDER BY Col ASC

Inner join

JOIN Table2 ON Table1.Col = Table2.Col

Outer join

`LEFT

Grouping

GROUP BY Col

Functions

COUNT(Col), SUM(Col), DATEADD(month, -1, GETDATE())


๐Ÿš€ 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.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent