The SELECT statement is used to retrieve data from one or more tables in a database.
Basic syntax:
- SELECT → Specifies which columns you want to retrieve.
- FROM → Specifies the table from which to retrieve the data.
Step 1: Selecting all columns
To retrieve all columns from a table, you use *.
Example:
Assume we have a table Employees:
| EmployeeID | FirstName | LastName | Department | Salary |
|---|---|---|---|---|
| 1 | John | Doe | IT | 5000 |
| 2 | Jane | Smith | HR | 4500 |
| 3 | Mike | Brown | IT | 6000 |
Result:
| EmployeeID | FirstName | LastName | Department | Salary |
|---|---|---|---|---|
| 1 | John | Doe | IT | 5000 |
| 2 | Jane | Smith | HR | 4500 |
| 3 | Mike | Brown | IT | 6000 |
*means all columns.
Step 2: Selecting specific columns
You don’t always need all columns. You can select only the ones you need.
Result:
| FirstName | LastName | Department |
|---|---|---|
| John | Doe | IT |
| Jane | Smith | HR |
| Mike | Brown | IT |
Step 3: Using WHERE to filter rows
The WHERE clause allows you to filter data based on conditions.
Result:
| EmployeeID | FirstName | LastName | Department | Salary |
|---|---|---|---|---|
| 1 | John | Doe | IT | 5000 |
| 3 | Mike | Brown | IT | 6000 |
You can use operators like
=,>,<,>=,<=,<>(not equal) and combine conditions withAND/OR.
Step 4: Sorting with ORDER BY
ORDER BY lets you sort the results by one or more columns.
Result (sorted by salary descending):
| FirstName | LastName | Salary |
|---|---|---|
| Mike | Brown | 6000 |
| John | Doe | 5000 |
| Jane | Smith | 4500 |
ASCis ascending (default),DESCis descending.
Step 5: Using aliases with AS
You can give columns or tables temporary names using AS.
Result:
| Name | Income |
|---|---|
| John | 5000 |
| Jane | 4500 |
| Mike | 6000 |
Step 6: Using TOP to limit rows
TOP allows you to retrieve only a certain number of rows.
Result (top 2 salaries):
| EmployeeID | FirstName | LastName | Department | Salary |
|---|---|---|---|---|
| 3 | Mike | Brown | IT | 6000 |
| 1 | John | Doe | IT | 5000 |
Step 7: Using DISTINCT to remove duplicates
DISTINCT removes duplicate values from a column.
Result:
| Department |
|---|
| IT |
| HR |
