SELECT Statement
The SELECT statement is used to retrieve data from one or more tables in SQL Server. It is one of the most frequently used SQL statements.
With SELECT, we can retrieve all columns, specific columns, filtered records, sorted records and a limited set of rows.
Basic SELECT Syntax
SELECT column_name
FROM table_name;
The SELECT keyword specifies the columns that we want to retrieve, while FROM specifies the table from which the data should be retrieved.
Sample Students Table
| StudentId | StudentName | Age | City |
|---|---|---|---|
| 101 | Rahul | 22 | Pune |
| 102 | Priya | 23 | Mumbai |
| 103 | Amit | 21 | Pune |
SELECT All Columns
The asterisk * is used when we want to retrieve all columns from a table.
SELECT *
FROM Students;
Output
| StudentId | StudentName | Age | City |
|---|---|---|---|
| 101 | Rahul | 22 | Pune |
| 102 | Priya | 23 | Mumbai |
| 103 | Amit | 21 | Pune |
SELECT Specific Columns
We can retrieve only the columns that are required instead of selecting every column.
SELECT StudentName, Age
FROM Students;
Output
| StudentName | Age |
|---|---|
| Rahul | 22 |
| Priya | 23 |
| Amit | 21 |
SELECT with WHERE
The WHERE clause is used to filter records based on a specified condition.
SELECT *
FROM Students
WHERE Age > 21;
Output
| StudentId | StudentName | Age | City |
|---|---|---|---|
| 101 | Rahul | 22 | Pune |
| 102 | Priya | 23 | Mumbai |
SELECT with AND
The AND operator is used when multiple conditions must be satisfied.
SELECT *
FROM Students
WHERE Age > 20
AND City = 'Pune';
SELECT with OR
The OR operator is used when at least one of multiple conditions should be satisfied.
SELECT *
FROM Students
WHERE City = 'Pune'
OR City = 'Mumbai';
SELECT with ORDER BY
ORDER BY is used to sort the result in ascending or descending order.
Ascending Order
SELECT *
FROM Students
ORDER BY Age ASC;
Descending Order
SELECT *
FROM Students
ORDER BY Age DESC;
SELECT DISTINCT
DISTINCT is used to return only unique values from the selected column or columns.
SELECT DISTINCT City
FROM Students;
SELECT TOP
TOP is used to return a specified number of rows from the result.
SELECT TOP 2 *
FROM Students;
SELECT Statement Flow
SELECT
↓
FROM
↓
WHERE
↓
ORDER BY
↓
Result
SELECT Statement Quick Reference
| Clause / Keyword | Purpose |
|---|---|
| SELECT | Specifies the columns to retrieve. |
| FROM | Specifies the table. |
| WHERE | Filters records. |
| ORDER BY | Sorts the result. |
| DISTINCT | Returns unique values. |
| TOP | Returns a specified number of rows. |
Summary
The SELECT statement is used to retrieve data from SQL Server tables. We learned how to select all or specific columns, filter records using WHERE, combine conditions using AND and OR, sort results using ORDER BY, retrieve unique values using DISTINCT and limit the number of rows using TOP.