datarekha

SELECT basics

The fundamentals of a SQL query — choosing columns, filtering rows, sorting — and the surprising order they actually run in.

6 min read Beginner SQL Lesson 1 of 27

What you'll learn

  • How a SELECT statement is built up, clause by clause
  • The logical execution order — which is NOT the order you write it in
  • Why a SELECT alias can't be used back in WHERE

SELECT is the verb you will reach for more than any other in SQL. It asks a table a question and hands back rows. Throughout this lesson we will put the same small table of users on the desk and ask it things:

idnamecountrysignup_date
1AshaIN2024-01-15
2BoCN2024-02-03
3CarlosUS2024-02-20
4DiyaIN2024-03-28
5ErikUS2024-01-09

The simplest useful query names some columns and a source:

SELECT name, country
FROM   users;
namecountry
AshaIN
BoCN
CarlosUS
DiyaIN
ErikUS

The order you write is not the order it runs

Here is the thing most tutorials skip. SQL does not run a query top to bottom the way you typed it. It runs the clauses in a fixed logical order, and SELECT — the first word you write — runs almost last:

1FROMpick the source table(s)2WHEREfilter rows3GROUP BYcollapse into groups4HAVINGfilter groups5SELECTchoose the columns — written first!6ORDER BYsort7LIMITkeep only N rows

You write SELECT first, but it runs fifth — which is exactly why a column alias from SELECT can’t be used back in WHERE.

FROM picks the table, WHERE keeps the rows you want, and only then does SELECT choose which columns survive — followed by ORDER BY to sort and LIMIT to trim. Hold this order; it explains a surprising amount.

A quick tour of the clauses

Keep only some rows with WHERE:

SELECT name, signup_date
FROM   users
WHERE  country = 'IN';
namesignup_date
Asha2024-01-15
Diya2024-03-28

Sort the output with ORDER BY, and keep just the top few with LIMIT — here, the three most recent signups:

SELECT name, signup_date
FROM   users
ORDER BY signup_date DESC
LIMIT 3;
namesignup_date
Diya2024-03-28
Carlos2024-02-20
Bo2024-02-03

And rename a column on the way out with AS — an alias — which makes bigger, multi-table queries far easier to read:

SELECT name        AS user_name,
       signup_date AS joined_at
FROM   users
LIMIT 2;
user_namejoined_at
Asha2024-01-15
Bo2024-02-03

Notice why the alias rule from the diagram bites: a name you create in SELECT does not exist yet when WHERE runs, because WHERE ran two steps earlier. That single fact resolves the most common “why won’t this query compile?” beginners hit.

Practice

Quick check

0/3
Q1Why does SELECT name, COUNT(*) AS c FROM users WHERE c > 5 fail?
Q2Which WHERE clause finds rows where email is NULL?
Q3What is the difference between COUNT(*) and COUNT(email)?

Sign in to track your progress

Completed lessons, your XP, level, and streak save to your account — it's free and takes a few seconds.

Practice this in an interview

All questions

Related lessons

Explore further

Skip to content