SQL Server: SELECT Statement
The SQL Server (Transact-SQL) SELECT statement is used to retrieve records from one or more tables in a SQL Server database. The result is stored in a table, called the result-set.
Syntax example :
SELECT expressions
FROM tables
[ WHERE conditions ] ;
eg.
SELECT * FROM [ table name ] ;
SELECT [ column name 1] , [ column name 2 ]
FROM [ table name ] ;
SELECT [ ALL | DISTINCT ]
[ TOP ( top_value ) ]
expressions
FROM [ table name ]
[ WHERE conditions ]
[ GROUP BY expressions ]
[ HAVING condition ]
[ ORDER BY expression [ ASC | DESC ] ] ;
eg.
SELECT
TOP ( 10 )
[ column name 1 ] , [ column name 2 ]
FROM [ table name ]
WHERE [ column name 1 ] >= 50
AND [ column name 2 ] = 'Column Value'
ORDER BY [ column name 1 ] DESC, [ column name 2 ] ASC ;
Different Parameters or Arguments
Optional. Returns all matching rows.
eg. SELECT * FROM [ table name ] ;
2) DISTINCT
Optional. Removes duplicates from the result set. Learn more about the DISTINCT clause.
eg. SELECT DISTINCT [ column name 1 ] FROM [ table name ] ;
3) TOP (value)
Optional. If specified, it will return the top number of rows in the result set based on top_value. For example, TOP(10) would return the top 10 rows from the full result set.
eg. SELECT TOP 10 FROM [ table name ] ;
4) PERCENT
Optional. If specified, then the top rows are based on a percentage of the total result set (as specfied by the top_value). For example, TOP(10) PERCENT would return the top 10% of the full result set.
5) WHERE conditions
Optional. The conditions that must be met for the records to be selected.
eg. SELECT * FROM [ table name ] [ WHERE conditions ] ;
6) GROUP BY expressions
Optional. It collects data across multiple records and groups the results by one or more columns.
eg.
SELECT [ column name 1 ]
FROM [ table name ]
[ GROUP BY [ column name 1 ] ] ;
7) HAVING condition
Optional. It is used in combination with the GROUP BY to restrict the groups of returned rows to only those whose the condition is TRUE.
eg.
SELECT [ column name 1 ]
FROM [ table name ]
[ GROUP BY [ column name 1 ] ]
[ HAVING condition ] ;
8) ORDER BY expression
Optional. It is used to sort the records in your result set. ASC sorts in ascending order and DESC sorts in descending order.
eg.
SELECT [ column name 1 ]
FROM [ table name ]
ORDER BY [ column name 1 ] DESC ;