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