The SELECT & FROM Foundation 🔍
Every analytical journey in SQL begins with two fundamental keywords: SELECT and FROM.
SELECT column1, column2FROM table_name;It looks remarkably simple, but beneath this declarative statement lies the foundation of relational algebra (projection and relation scanning).
Let's explore how to query data properly from day one.
1. Our Practice Database: The employees Table 👥
Throughout this chapter, imagine we are querying the following employees table:
Table: employees
┌────┬──────────────┬─────────────┬────────────┬────────┬────────────┐
│ id │ first_name │ last_name │ department │ salary │ hired_date │
├────┼──────────────┼─────────────┼────────────┼────────┼────────────┤
│ 1 │ Aarav │ Sharma │ Engineering│ 95000 │ 2024-01-15 │
│ 2 │ Rahul │ Sharma │ Marketing │ 62000 │ 2023-06-01 │
│ 3 │ Priya │ Patel │ Engineering│ 98000 │ 2022-11-20 │
│ 4 │ Amit │ Verma │ Sales │ 55000 │ 2024-03-10 │
│ 5 │ Neha │ Gupta │ Marketing │ 64000 │ 2023-09-15 │
└────┴──────────────┴─────────────┴────────────┴────────┴────────────┘
2. Retrieving Specific Columns vs. SELECT * 🎯
Method A: Retrieving Specific Columns (Recommended!)
To retrieve only the names and departments:
SELECT first_name, last_name, departmentFROM employees;Result:
┌────────────┬───────────┬─────────────┐
│ first_name │ last_name │ department │
├────────────┼───────────┼─────────────┤
│ Aarav │ Sharma │ Engineering │
│ Rahul │ Sharma │ Marketing │
│ Priya │ Patel │ Engineering │
│ Amit │ Verma │ Sales │
│ Neha │ Gupta │ Marketing │
└────────────┴───────────┴─────────────┘
Method B: The Wildcard SELECT * (Use with Caution!)
The asterisk * means "give me every single column in the table":
SELECT * FROM employees;⚠️ Why Senior Engineers Avoid
SELECT *in Production Code:
- Network & I/O Overhead: If your table has 50 columns (including large
TEXTorJSONblobs), fetching*transfers megabytes of unnecessary data across the network for every request.- Index Disqualification: Queries asking for specific indexed columns can be served directly from memory (Covering Index).
SELECT *forces the database engine to hit physical disk for every single row.- Application Fragility: If a database administrator adds or reorders columns, code expecting specific positional indexes will break!
3. Column Aliases: Renaming Columns with AS 🏷️
By default, the result table uses the database column names. You can rename output columns using the AS keyword:
SELECT first_name AS "First Name", salary AS monthly_compensationFROM employees;- If the alias contains spaces or special characters, wrap it in double quotes (
"First Name"). - The
ASkeyword does not rename the column in the physical database table; it only formats the label in the query result.
4. Computed Expressions & Arithmetic Operations 🧮
SELECT is not restricted to existing column values—you can calculate new values on the fly:
SELECT first_name, salary, salary * 1.10 AS salary_with_10pct_bonus, salary / 12 AS monthly_salaryFROM employees;You can even use SQL like a calculator without referencing any table (in PostgreSQL, SQLite, and MySQL):
SELECT (50 * 4) + 25 AS total_calculation;5. String Concatenation 🧵
Often, you want to combine first_name and last_name into a single full_name column:
In PostgreSQL, SQLite, and Oracle (|| operator):
SELECT first_name || ' ' || last_name AS full_nameFROM employees;In MySQL (CONCAT function):
SELECT CONCAT(first_name, ' ', last_name) AS full_nameFROM employees;Result:
┌─────────────────┐
│ full_name │
├─────────────────┤
│ Aarav Sharma │
│ Rahul Sharma │
│ Priya Patel │
└─────────────────┘
6. Removing Duplicates with DISTINCT ✨
If you run:
SELECT department FROM employees;You get: Engineering, Marketing, Engineering, Sales, Marketing.
Notice the duplicate entries! To get a unique list of departments, place the DISTINCT keyword immediately after SELECT:
SELECT DISTINCT departmentFROM employees;Result:
┌─────────────┐
│ department │
├─────────────┤
│ Engineering │
│ Marketing │
│ Sales │
└─────────────┘
Pro Tip:
DISTINCTevaluates the combination of all selected columns.SELECT DISTINCT department, salaryreturns unique pairs of department and salary.
7. How SQL Queries Actually Execute (Written vs. Logical Order) ⚙️
Here is a foundational principle every software engineer and data analyst must understand:
SQL queries are NOT executed in the order they are written!
In most programming languages, code runs sequentially top-to-bottom. But SQL is declarative: you write SELECT first to declare what output columns you want, but the database engine cannot compute columns until it first scans the storage disk (FROM), evaluates join conditions (JOIN), discards disqualified rows (WHERE), partitions buckets (GROUP BY), and filters aggregated groups (HAVING).
Interactive SQL Execution Lifecycle Stepper 🕹️
Step through each phase below to see which clause executes first, what happens to the rows in memory, and the critical rules behind each step:
The database engine identifies the target table ('employees') on disk or buffer cache and loads all 5 raw records into working memory.
employees table5 rows in memory8. Interactive Practice: Live SQL Playground ⚡
Try running your own queries right now inside your browser! Edit the query below, click "Run Query" (or press Ctrl + Enter), and watch SQLite compute the result instantly:
9. Hands-on Challenge: Write Your First Query 🎯
Put your skills to the test! Write a query to solve this challenge:
Challenge: Distinct Department RosterBeginner
Flashcard Checkpoint 🎴
Why should you avoid using SELECT * in production backend APIs?
2. It prevents the database from using fast covering indexes.
3. It creates fragile code if table schemas change in the future.
What does the DISTINCT keyword do, and where must it be placed in a SQL query?