SELECT statement
In SQL, SELECT statements return sets of results from data collections like tables or views. SELECT statements can be used with various other clauses like WHERE, GROUP BY, or ORDER BY to further refine the desired results.
Basic SELECT from table
Section titled “Basic SELECT from table”Select all columns from some table (system table in this case):
SELECT *FROM sys.objectsOr, select just some specific columns:
SELECT object_id, name, type, create_dateFROM sys.objectsFilter rows using WHERE clause
Section titled “Filter rows using WHERE clause”WHERE clause filters only those rows that satisfy some condition:
SELECT *FROM sys.objectsWHERE type = 'IT'Sort results using ORDER BY
Section titled “Sort results using ORDER BY”ORDER BY clause sorts rows in the returned result set by some column or expression:
SELECT *FROM sys.objectsORDER BY create_dateGroup result using GROUP BY
Section titled “Group result using GROUP BY”GROUP BY clause groups rows by some value:
SELECT type, count(*) as cFROM sys.objectsGROUP BY typeYou can apply some function on each group (aggregate function) to calculate sum or count of the records in the group.
|type|c |---|---|---|--- |SQ|3 |S|72 |IT|16 |PK|1 |U|5
Filter groups using HAVING clause
Section titled “Filter groups using HAVING clause”HAVING clause removes groups that do not satisfy condition:
SELECT type, count(*) as cFROM sys.objectsGROUP BY typeHAVING count(*) < 10|type|c |---|---|---|--- |SQ|3 |PK|1 |U|5
Returning only first N rows
Section titled “Returning only first N rows”TOP clause returns only first N rows in the result:
SELECT TOP 10 *FROM sys.objectsPagination using OFFSET FETCH
Section titled “Pagination using OFFSET FETCH”OFFSET FETCH clause is more advanced version of TOP. It enables you to skip N1 rows and take next N2 rows:
SELECT *FROM sys.objectsORDER BY object_idOFFSET 50 ROWS FETCH NEXT 10 ROWS ONLYYou can use OFFSET without fetch to just skip first 50 rows:
SELECT *FROM sys.objectsORDER BY object_idOFFSET 50 ROWSSELECT without FROM (no data souce)
Section titled “SELECT without FROM (no data souce)”SELECT statement can be executed without FROM clause:
declare @var int = 17;
SELECT @var as c1, @var + 2 as c2, 'third' as c3In this case, one row with values/results of expressions are returned.