Pathubs SQL Curriculum • Module 01

SQL SELECT Statement

The fundamental building block of all data querying. Learn how to extract, project, alias, calculate, and deduplicate data from relational database tables.

⏱️ Estimated Time:45 Minutes
🎯 Level:Beginner First
📊 Track:Data Analytics & Engineering
✨ Mode:Interactive Lab + Deep Dive
1

Introduction

In relational database management systems (RDBMS) such as PostgreSQL, MySQL, SQL Server, SQLite, and Snowflake, data is stored in structured tables. The SELECT statement is the undisputed foundation of SQL: it is the primary command used to retrieve and read data from these tables.

Whether you are extracting monthly transactions for an e-commerce platform, pulling patient histories in a hospital application, analyzing customer churn, or building an executive reporting dashboard, every data workflow begins with SELECT.

💡
Key Principle: SELECT is strictly a read-only query statement. Executing a SELECT query does not alter, insert, modify, or delete the underlying data stored inside your database. It simply reads the data and projects it into a virtual, formatted view called a Result Set.
2

Understanding a SQL Table

Before writing SQL queries, you must understand how data is organized within a relational database. A database consists of one or more Tables, which are organized in a two-dimensional grid of rows and columns:

ConceptDatabase TermDescriptionRealistic Example (Customers Table)
TableEntity / RelationThe entire 2D collection of organized recordscustomers table
RowRecord / TupleA single horizontal entry representing one entityCustomer ID 101: Rahul Sharma, Bangalore
ColumnField / AttributeA vertical category with a specific data typeemail, city, signup_date
ValueCell / Data PointThe exact intersection of one row and one column"Bangalore" or 75000

SQL queries allow you to request specific columns across all or filtered rows from this grid.

Diagram 1: The Basic SELECT Flow
📦 Database Table
(5 columns, 10,000 rows)
SELECT name, city FROM customers;
(Column Projection Request)
📋 Result Set
(2 requested columns in memory)
3

Your First SELECT Query

The simplest SQL query contains two essential clauses: SELECT and FROM.

SELECT name
FROM customers;

Let us break down every element of this query:

  • SELECT: Tells the database query processor: "Extract and return the following column(s) in the result."
  • name: The specific column name you want to retrieve.
  • FROM: Specifies the source table where the data lives.
  • customers: The exact table name in the database schema.
  • ; (Semicolon): The standard SQL statement terminator indicating the end of the query command.
4

Selecting Specific Columns

In real-world applications, tables often contain dozens of columns (e.g. metadata, system timestamps, encrypted hashes). You can select a single column or multiple columns by separating them with commas:

-- Selecting a single column
SELECT name
FROM customers;

-- Selecting multiple specific columns
SELECT name, email, city
FROM customers;
ℹ️
Column Order in Result Set: The output columns will appear in the exact order you list them in the SELECT clause, regardless of how they are arranged in the original table definition.
5

SELECT * (The Wildcard)

The asterisk (*) is known as the wildcard selector. It commands the SQL engine to return every single column available in the table in its default schema order:

SELECT *
FROM customers;
When SELECT * is GreatWhy Avoid SELECT * in Production
✅ Fast initial data exploration❌ Transfers unnecessary megabytes across the network
✅ Inspecting newly created or unfamiliar tables❌ Consumes excessive application server memory
✅ Quick interactive debugging in SQL client❌ Schema changes (adding/removing columns) can break downstream backend code
6

Column Aliases (The AS Keyword)

Database column names are often terse or follow strict database naming conventions (such as usr_fnm, cust_addr_loc, or emp_sal_amt). You can use the AS keyword to give columns a user-friendly alias in the result set:

SELECT first_name AS name, cust_city AS location
FROM customers;

Aliasing renames the column header in the returned result set. It does not change the permanent column name inside the database table.

7

Selecting Expressions & Calculated Values

A SELECT clause is not limited to returning static stored columns. You can evaluate mathematical expressions on the fly for each row.

-- Calculating line total for an e-commerce order
SELECT product_name, price, quantity, price * quantity AS total
FROM products;

The SQL engine evaluates the expression price * quantity for every individual row and assigns the calculated value to the new virtual column labeled total.

Diagram 2: SELECT Mental Model
1. Read Source Table
FROM employees
2. Extract Columns / Compute Math
SELECT name, salary * 12 AS annual
3. Deliver Result Set
[name, annual]
8

SELECT DISTINCT — Basic Introduction

If multiple rows contain duplicate values in the selected columns, standard SELECT returns all of them. Adding the DISTINCT keyword instructs SQL to eliminate duplicate rows from the final result set:

SELECT DISTINCT city
FROM customers;
Diagram 3: DISTINCT Deduplication
Raw Output (SELECT city)
Mumbai
Mumbai
Delhi
Pune
Mumbai
➔ DISTINCT ➔
Unique Output (SELECT DISTINCT city)
Mumbai
Delhi
Pune
9

Understanding Result Sets

Whenever you run a query, the SQL engine constructs a Result Set. Think of a result set as a temporary, read-only table created in memory specifically to satisfy your query.

When you run SELECT DISTINCT department, city FROM employees;, SQL examines the combination of department and city across all rows, ensuring that no pair of (department, city) is repeated.

10

Reading and Understanding a SELECT Query

While humans read code from top to bottom, SQL query execution follows a specific logical order:

  1. Step 1 (FROM): Identify the table where the data is stored.
  2. Step 2 (SELECT): Select the columns, perform calculations, rename with aliases, and apply DISTINCT if requested.
  3. Step 3 (Output): Emit the formatted result set back to the client.
Live Interactive SELECT Query Lab
📦 Source Database Table: employees8 Total Rows
idnamedepartmentsalarycity
1Rahul SharmaEngineering75,000Bangalore
2Priya PatelMarketing62,000Mumbai
3Amit VermaEngineering82,000Bangalore
4Sneha RaoHR55,000Pune
5Vikram SinghMarketing64,000Delhi
6Ananya GuptaFinance90,000Mumbai
7Rohan DeshmukhEngineering78,000Pune
8Pooja NairHR57,000Bangalore
✍️ SQL Editor● Ready
🔍 Query Execution Breakdown
Target Table (FROM)
employees (8 scanned rows)
Projections (SELECT)
name, department, salary
11

Common Beginner Mistakes

1. Forgetting the FROM clause
❌ SELECT name, city employees;
✅ SELECT name, city FROM employees;
2. Missing commas between columns
❌ SELECT name department salary FROM employees;
✅ SELECT name, department, salary FROM employees;
3. Confusing column names with literal strings
❌ SELECT 'name' FROM employees; -- Prints the literal word "name" on every row!
✅ SELECT name FROM employees; -- Retrieves employee name values from table
4. Misspelling table or column names
❌ SELECT departmnt FROM employee; -- Typo in column and table name
✅ SELECT department FROM employees;
🛠️ Interactive Challenge: Fix The Query (1 of 4)

Fix the query so that it retrieves both the name and department of every employee.

SELECT name department FROM employees;
12

Practical SELECT Exercises

Task GoalRequired QueryOutput Concept
1. Select One ColumnSELECT email FROM customers;Single-column projection
2. Select Multiple ColumnsSELECT name, department, salary FROM employees;Comma-separated column list
3. Rename Output ColumnSELECT first_name AS customer_name FROM users;Output header aliasing with AS
4. Compute Derived ValueSELECT unit_price * quantity AS subtotal FROM order_items;Row-by-row arithmetic expression
5. Deduplicate Unique ValuesSELECT DISTINCT country FROM suppliers;Removes repeating country names
13

SELECT Best Practices

  • Capitalize SQL Keywords: Use uppercase for SELECT, FROM, AS, and DISTINCT to clearly separate keywords from column identifiers.
  • Explicit Column Naming in Production: Avoid SELECT * in production queries and APIs. Always request only the specific columns needed by the application.
  • Provide Meaningful Aliases: Whenever calculating expressions (e.g. salary * 12), always assign a clean alias with AS annual_salary so column headers remain clear.
  • Consistent Line Formatting: Break complex queries across multiple lines with SELECT on one line and FROM on the next.
14

What You Should Know Now

You have mastered the foundation of SQL querying! Here is your core competencies checklist:

  • SELECT Keyword: Instructs SQL which columns to extract
  • FROM Clause: Identifies the source database table
  • Multiple Columns: Comma-separated column list
  • Wildcard (*): Selects all columns defined in table
  • Aliases (AS): Renames output headers in result set
  • Expressions: Evaluates math on the fly row-by-row
  • DISTINCT: Eliminates duplicate rows in the result
  • Result Sets: Temporary virtual output tables in memory

🎯 Knowledge Check Quiz: SQL SELECT

Test your understanding of SELECT syntax, result sets, expressions, aliases, and query predictions.

1. What is the primary purpose of the SQL SELECT statement?
2. What does the asterisk (*) represent in "SELECT * FROM employees;"?
3. How do you select multiple columns (e.g., name, email, and city) in SQL?
4. What does column aliasing with "AS" accomplish?
5. Predict the result: What will "SELECT DISTINCT department FROM employees;" return for our sample dataset (4 Engineering, 2 Marketing, 2 HR, 1 Finance)?
6. Predict the result: If a table has columns [price: 100, qty: 5], what does "SELECT price, price * qty AS total_cost FROM items;" produce?
7. Which of the following is a common syntax error when writing SELECT queries?
8. Why is explicitly naming required columns (e.g., SELECT id, name) generally preferred over SELECT * in production applications?