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
Keyword | Description |
---|---|
ALL | Returns all rows, including duplicates (default). |
DISTINCT | Eliminates duplicate rows from the result set. |
TOP | Specifies the number of rows to return. |
WITH TIES | Includes rows that tie with the last row in the TOP set. |
SELECT list | Columns or expressions to return. |
FROM | Source tables, views, or joins. |
WHERE | Filters rows based on a condition. |
GROUP BY | Groups rows sharing a property for aggregate functions. |
HAVING | Filters groups based on a condition. |
ORDER BY | Specifies 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;