SELECT Statement
Master the SELECT statement to retrieve data from databases.
Introduction to SELECT
The SELECT statement is the most important and frequently used SQL command. It's how you retrieve (or "query") data from a database. Think of it as asking the database a question: "Show me this information."
Every time you search for something, view a list, or see data on a website, there's likely a SELECT statement running behind the scenes!
A SQL command used to retrieve data from one or more tables. It specifies which columns you want to see and which table to get them from.
Basic Syntax:
SELECT column1, column2, ...
FROM table_name;
Let's explore SELECT with a realistic example. Here's our employees table:
id | first_name | last_name | department | salary | hire_date |
|---|---|---|---|---|---|
| 1 | Alice | Johnson | Engineering | 75000 | 2022-01-15 |
| 2 | Bob | Smith | Marketing | 65000 | 2021-06-20 |
| 3 | Charlie | Davis | Engineering | 85000 | 2020-03-10 |
| 4 | Diana | Wilson | Sales | 70000 | 2022-08-01 |
| 5 | Eve | Martinez | Marketing | 68000 | 2021-11-12 |
Selecting All Columns (SELECT *)
The simplest SELECT statement uses * (asterisk) to retrieve all columns from a table.
SELECT * FROM employees;*When to use SELECT :
- Exploring a new table to see what columns it has
- Quick debugging or testing
- You genuinely need all columns
But be careful! In production code, it's better to specify exact columns (we'll see why next).
Tip: The semicolon (;) marks the end of a SQL statement. Always include it, especially when running multiple queries!
Selecting Specific Columns
Most of the time, you don't need all columns - just specific ones. List the column names you want, separated by commas.
SELECT first_name, last_name, department
FROM employees;*Why specify columns instead of using ?
- Performance: Fetching only needed columns is faster, especially with large tables
- Clarity: Makes your code self-documenting - others know exactly what data you need
- Maintainability: If the table structure changes (new columns added), your query still works
- Network efficiency: Less data transferred between database and application
Best Practice: Always specify column names in production code. Only use SELECT * for quick exploration or when you truly need every column.
Column Order and Multiple Columns
The order you list columns determines the order they appear in results. You can also select the same column multiple times!
-- Columns appear in the order you specify
SELECT salary, first_name, last_name
FROM employees;Selecting just one column:
SELECT department FROM employees;Notice that "Engineering" and "Marketing" appear multiple times. This is expected - SELECT returns all rows by default, including duplicates.
Using DISTINCT
To remove duplicate values and see only unique results, use the DISTINCT keyword.
SELECT DISTINCT department
FROM employees;DISTINCT with multiple columns returns unique combinations:
SELECT DISTINCT department, hire_date
FROM employees;Each row shows a unique combination of department and hire_date. Even though Engineering appears twice, the dates are different, so both rows are included.
Performance Note: DISTINCT requires the database to check for duplicates, which can be slow on large tables. Use it only when necessary!
Calculated Columns and Expressions
SELECT isn't limited to existing columns - you can perform calculations and create new values on the fly!
Arithmetic operations:
SELECT first_name, salary, salary * 12 AS annual_salary
FROM employees;The AS keyword creates a column alias (a temporary name). You can use any name you like!
String concatenation (combining text):
SELECT first_name, last_name,
CONCAT(first_name, ' ', last_name) AS full_name
FROM employees;More calculations:
SELECT first_name,
salary,
salary * 0.85 AS after_tax,
salary * 0.15 AS tax_amount
FROM employees;Column Aliases (AS Keyword)
Column aliases make your results more readable. They're especially useful for calculated columns or when column names are unclear.
Syntax | Description | Example |
|---|---|---|
| `column AS alias` | Standard syntax (recommended) | `salary AS monthly_pay` |
| `column alias` | AS is optional | `salary monthly_pay` |
| `"alias name"` | Use quotes for spaces | `salary AS "Monthly Salary"` |
SELECT first_name AS "First Name",
department AS dept,
salary AS "Monthly Salary"
FROM employees;Tip: Aliases only affect how data is displayed in the result. They don't change the actual table or column names in the database.
Selecting Literal Values
You can include literal values (fixed text or numbers) in your SELECT statement. This is useful for adding context to results.
SELECT first_name,
'Employee' AS record_type,
2024 AS report_year,
department
FROM employees;Every row gets the same literal value - "Employee" and 2024 in this case. This is helpful when combining data from different sources or adding metadata to reports.
Practical Example: Employee Report
Let's combine everything we've learned to create a comprehensive employee report:
SELECT id AS employee_id,
CONCAT(first_name, ' ', last_name) AS full_name,
department,
salary AS monthly_salary,
salary * 12 AS annual_salary,
YEAR(hire_date) AS year_hired
FROM employees;This query demonstrates:
- Column aliases for clarity
- String concatenation (full name)
- Mathematical calculations (annual salary)
- Date functions (extracting year)
- Professional formatting
Common Mistakes to Avoid
Don't make these mistakes:
-
Missing comma between columns:
SELECT first_name last_name❌- Correct:
SELECT first_name, last_name✓
- Correct:
-
Comma after last column:
SELECT first_name, last_name,❌- Correct:
SELECT first_name, last_name✓
- Correct:
-
Missing FROM clause:
SELECT first_name❌- Correct:
SELECT first_name FROM employees✓
- Correct:
-
Selecting non-existent columns:
SELECT namee FROM employees❌- Will cause an error! Check spelling carefully
-
Using
SELECT *in production: Slow and unpredictable ❌- Specify columns:
SELECT id, name, email✓
- Specify columns:
SELECT Query Checklist
Component | Required? | Purpose | Example |
|---|---|---|---|
| SELECT | ✅ Yes | Specify columns to retrieve | `SELECT first_name, salary` |
| FROM | ✅ Yes | Specify which table | `FROM employees` |
| DISTINCT | ❌ Optional | Remove duplicates | `SELECT DISTINCT department` |
| AS | ❌ Optional | Create column aliases | `salary AS monthly_pay` |
| Calculations | ❌ Optional | Perform math/concatenation | `salary * 12` |
Key Takeaways
What you learned:
✅ SELECT retrieves data from tables ✅ **SELECT *** gets all columns (use sparingly!) ✅ Specify columns by listing them with commas ✅ DISTINCT removes duplicate values ✅ Calculations let you create new values on the fly ✅ AS creates readable column aliases ✅ Column order in SELECT determines display order
Next steps: In the upcoming lessons, we'll learn how to filter results with WHERE, sort data with ORDER BY, and limit the number of rows returned. The SELECT statement becomes even more powerful when combined with these tools!
Practice Exercise: Try writing SELECT statements to:
- Get all unique departments
- Calculate a 10% bonus for each employee
- Display full names with their annual salaries
- Show only first names and departments