Retrieve rows from the database.
Summary Syntax:
[WITH common_table_expression]
SELECT [ALL|DISTINCT] [TOP n [PERCENT] [WITH TIES]] select_list [INTO new_table ]
[FROM table_source ]
[WHERE search_condition ]
[GROUP BY group_by_expression ]
[HAVING search_condition ]
[ORDER BY expression [ASC|DESC] ]
Key
select_list One or more Columns from a Table, View or Alias:
table.*, table.column1, table2.column3, view4.* ...
table_source Table_or_view
Table_or_view [AS] table_alias
rowset_function [AS] table_alias
user_defined_function [AS] table_alias
OPENXML XML clause
table_source [INNER JOIN] table_source
table_source {LEFT | RIGHT | FULL} [OUTER] JOIN table_source
In addition to the above the UNION, EXCEPT and INTERSECT operators can be used to combine multiple queries into a single set of results, each query_spec must return the same number of columns:
query_spec UNION [ALL] query_spec [...n ] ; query_spec EXCEPT query_spec [...n ] ] ; query_spec INTERSECT query_spec [...n ] ] ;
Select everything:
USE MyDatabase ;
GO
SELECT *
FROM myschema.mytable
ORDER BY mycolumn ASC ; GO
Select only a few columns:
SELECT mycolumn1, mycolumn2
FROM myschema.mytable; GO
Select using an alias:
SELECT My_alias.*
FROM myschema.mytable my_alias; GO
Select with an average:
SELECT mycolumn1, AVG(mycolumn3) AS 'Average Price'
FROM myschema.mytable
WHERE mycolumn3 > 750
GROUP BY mycolumn1
ORDER BY mycolumn1 ;
GO
Select positive and negative ratings and order the results By Average Rating:
SELECT widget_id, ((positive + 1.9208) / (positive + negative) - 1.96 * SQRT((positive * negative) / (positive + negative) + 0.9604) / (positive + negative)) / (1 + 3.8416 / (positive + negative)) AS ci_lower_bound FROM widgets WHERE positive + negative > 0 ORDER BY ci_lower_bound DESC;
โA synonym is a word you use when you can't spell the word you first thought ofโ ~ Burt Bacharach