The SELECT Statement
The SELECT statement retrieves data from a database. It's the most common SQL command.
💡 SELECT is how you ask your database questions. You specify WHAT columns and WHERE to find them.
Basic Syntax
SELECT column1, column2
FROM table_name;
Select All Columns
SELECT * FROM customers;
| id | first_name | last_name | city | |
|---|---|---|---|---|
| 1 | Alice | Johnson | alice@email.com | New York |
| 2 | Bob | Smith | bob@email.com | Los Angeles |
⚠️ SELECT * is convenient but avoid it in production. It returns ALL columns, which is slower and breaks if the schema changes.
Select Specific Columns
SELECT first_name, last_name, email FROM customers;
| first_name | last_name | |
|---|---|---|
| Alice | Johnson | alice@email.com |
| Bob | Smith | bob@email.com |
Expressions in SELECT
SELECT
name,
price,
price * 1.08 AS price_with_tax,
price * stock AS inventory_value
FROM products;
| name | price | price_with_tax | inventory_value |
|---|---|---|---|
| Mouse | 29.99 | 32.39 | 4498.50 |
| Keyboard | 89.99 | 97.19 | 6749.25 |
SELECT Without a Table
SELECT 1 + 1 AS result; -- 2
SELECT CURRENT_DATE AS today; -- 2024-01-15
SELECT 'Hello, World!' AS greeting; -- Hello, World!
Column Aliases
SELECT
first_name AS "First Name",
last_name AS "Last Name",
salary * 12 AS annual_salary
FROM employees;
SQL Execution Order
SELECT ... -- 3. Return these columns
FROM ... -- 1. Get data from these tables
WHERE ... -- 2. Filter rows
ORDER BY ... -- 4. Sort the results
✏️ Exercise: Write a query to select 'name' and 'price' from 'products', and calculate a 10% discount as 'discounted_price'
See Solution
SELECT
name,
price,
price * 0.9 AS discounted_price
FROM products;
✅ Key Takeaways
- SELECT retrieves data from a database
- Use specific column names instead of * in production
- Expressions can compute new values in your query
- Aliases (AS) make your output cleaner
- SQL executes in a specific order: FROM → WHERE → SELECT → ORDER BY