Chapter 6: Querying Data with SELECT

The SELECT statement is what you will use 80–90% of the time when working with databases. It’s how you ask questions to your data and get answers back.

Today we’ll master:

  • Selecting only the columns we want
  • Filtering rows with WHERE (the real power!)
  • Sorting results with ORDER BY
  • Limiting how many rows we see with LIMIT & OFFSET
  • Giving nice names to columns with Aliases (AS)

First – let’s make sure we have good sample data Run this in your my_coaching database to reset and fill the students table with nice, varied data:

SQL

Now run:

SQL

You should see 8 students with different join dates, genders, and one with NULL phone and one inactive.

1. Selecting Specific Columns (Instead of *)

SQL

Result (only these 3 columns):

text

Why do this?

  • Faster (less data transferred)
  • Cleaner output
  • You only show what the user needs

2. WHERE Clause – Filtering Rows (This is the magic!)

Syntax:

SQL

Common Operators:

Operator Meaning Example
= Equal gender = ‘F’
> / < Greater / Less than join_date > ‘2025-02-01’
>= / <= Greater or equal / Less or equal date_of_birth <= ‘2008-01-01’
!= / <> Not equal gender != ‘M’
LIKE Pattern matching full_name LIKE ‘P%’ (starts with P)
IN Match any in list gender IN (‘F’, ‘O’)
BETWEEN Range (inclusive) join_date BETWEEN ‘2025-01-01’ AND ‘2025-01-31’
IS NULL Value is empty (NULL) phone IS NULL
IS NOT NULL Value exists email IS NOT NULL

Examples – Try these one by one!

A. Only female students

SQL

B. Students who joined in January 2025

SQL

C. Students whose name starts with ‘A’ or ‘R’

SQL

D. Students with no phone number

SQL

E. Active students born after 2008

SQL

F. Students from specific emails

SQL

3. ORDER BY – Sorting Results

Syntax:

SQL
  • ASC = Ascending (small → big, A → Z) → default
  • DESC = Descending (big → small, Z → A)

Examples:

A. Sort by join date (oldest first)

SQL

B. Sort by name alphabetically

SQL

C. Newest students first (latest join date)

SQL

D. Multiple columns – First by gender, then by name

SQL

4. LIMIT and OFFSET – Show Only Some Rows

Syntax:

SQL
  • LIMIT 5 → Show only first 5 rows
  • OFFSET 10 → Skip first 10 rows

Very useful for pagination (like showing 10 students per page)

Examples:

A. Show only first 3 students (alphabetical order)

SQL

B. Show students 4 to 6 (page 2 if 3 per page)

SQL

5. Aliases (AS) – Giving Friendly Names to Columns

Syntax:

SQL

Example – Make output beautiful

SQL

You can also alias expressions:

SQL

That’s it for Chapter 6! 🎉 You now know how to ask almost any question from your data!

Homework for today (do it right now – very important!) Run these queries and paste the final output here:

SQL

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *