MSDN Documentation

Microsoft Developer Network

SQL SELECT Statements

The SELECT statement is the cornerstone of data retrieval in SQL. It allows you to specify which columns you want to retrieve from one or more tables and to filter the rows based on certain criteria.

Basic Syntax

The most basic form of the SELECT statement retrieves all columns from a table:

SELECT *
FROM table_name;

To select specific columns, list their names after the SELECT keyword, separated by commas:

SELECT column1, column2, column3
FROM table_name;

Selecting Distinct Values

Use the DISTINCT keyword to return only unique values for a specified column:

SELECT DISTINCT column_name
FROM table_name;

Filtering Rows with WHERE Clause

The WHERE clause is used to extract only those records that fulfill a specified condition. For more information on the WHERE clause, refer to the WHERE Clause documentation.

SELECT column1, column2
FROM table_name
WHERE condition;

Sorting Results with ORDER BY Clause

The ORDER BY clause is used to sort the result-set in ascending or descending order. For more information, refer to the ORDER BY Clause documentation.

SELECT column1, column2
FROM table_name
ORDER BY column1 ASC|DESC;

Joining Tables

SELECT statements can also be used to retrieve data from multiple tables by using JOIN clauses. Refer to the JOIN Operations documentation for detailed explanations.

Aggregate Functions

SQL provides several aggregate functions that perform a calculation on a set of values and return a single value. Common aggregate functions include:

  • COUNT(): Returns the number of rows.
  • SUM(): Returns the total sum of a numeric column.
  • AVG(): Returns the average value of a numeric column.
  • MIN(): Returns the smallest value in a column.
  • MAX(): Returns the largest value in a column.

Example: Using Aggregate Functions

Calculate the total number of employees and the average salary:

SELECT COUNT(*) AS TotalEmployees, AVG(Salary) AS AverageSalary
FROM Employees;

Aliasing Columns and Tables

You can use aliases to give a temporary name to a table or a column. This can make queries more readable, especially when dealing with complex joins or aggregate functions.

SELECT column1 AS alias_name
FROM table_name AS alias_table_name;

Example: Aliasing

Select the first name and last name from the 'Customers' table, aliasing them for brevity.

SELECT FirstName AS FName, LastName AS LName
FROM Customers AS C;

Grouping Rows with GROUP BY Clause

The GROUP BY clause groups rows that have the same values in specified columns into summary rows, like "find the number of customers in each city". For more details, see the GROUP BY Clause documentation.

SELECT column1, COUNT(column2)
FROM table_name
WHERE condition
GROUP BY column1
ORDER BY column1;

Note: When using the GROUP BY clause, any column in the SELECT list that is not an aggregate function must be included in the GROUP BY clause.

Further Reading