SELECT (Transact-SQL)

Overview

The SELECT statement retrieves rows from one or more tables or views. It is the most commonly used Transact‑SQL command for querying data.

Syntax

SELECT [ ALL | DISTINCT ] 
    [TOP ( expression ) [ PERCENT ] [ WITH TIES ]]
    select_list
FROM    { table_source [ ,...n ] }
[ WHERE search_condition ]
[ GROUP BY group_by_expression [ ,...n ] ]
[ HAVING search_condition ]
[ ORDER BY { column_expression [ ASC | DESC ] } [ ,...n ] ];

Parameters

KeywordDescription
ALLReturns all rows, including duplicates (default).
DISTINCTEliminates duplicate rows from the result set.
TOPSpecifies the number of rows to return.
WITH TIESIncludes rows that tie with the last row in the TOP set.
SELECT listColumns or expressions to return.
FROMSource tables, views, or joins.
WHEREFilters rows based on a condition.
GROUP BYGroups rows sharing a property for aggregate functions.
HAVINGFilters groups based on a condition.
ORDER BYSpecifies the order of the result set.

Examples

Basic SELECT

SELECT FirstName, LastName
FROM dbo.Employee
WHERE HireDate > '2020-01-01'
ORDER BY LastName;

Using DISTINCT and TOP

SELECT DISTINCT TOP (10) Country
FROM dbo.Customer
ORDER BY Country;

Aggregate with GROUP BY

SELECT DepartmentID, COUNT(*) AS EmployeeCount, AVG(Salary) AS AvgSalary
FROM dbo.Employee
GROUP BY DepartmentID
HAVING COUNT(*) > 5
ORDER BY EmployeeCount DESC;

Related topics