Write SELECT statements: the six clauses
This article explains the six principal clauses of the SELECT statement: SELECT, FROM, WHERE, GROUP BY, HAVING and ORDER BY. It covers aliases, DISTINCT and TOP, aggregations, the different types of join, the comparison operators and wildcards used for filtering, and how sorting treats ties and NULLs.
The six principal clauses
The SELECT statement has six principal clauses. In the order in which they are written, they are:
- SELECT – which columns or calculated values to show.
- FROM – the source data.
- WHERE – which rows to keep.
- GROUP BY – how to group rows together for aggregations.
- HAVING – which groups to keep, after the GROUP BY.
- ORDER BY – how to sort the result.
This article covers each clause in turn.
The SELECT clause
The SELECT clause is where you say what columns or calculated values to show.
Aliases
You can rename (alias) columns using OriginalName AS NewName. The word AS is optional, but is recommended.
If your names have a space or other special character, then they need to be enclosed in [ ] hard brackets. The use of special words, such as Name, as column names may be possible, but is not recommended.
DISTINCT and TOP
- You can use
DISTINCTto remove duplicates. - You can use
TOP numberorTOP (number)to show the first few rows. TOP is generally used in combination with ORDER BY.
Aggregations
You can use aggregations – for example, SUM, COUNT, MIN, MAX and AVG.
COUNT(*)counts all the rows.COUNT(ColumnName)only counts those rows where ColumnName IS NOT NULL.AVGis the SUM divided by the COUNT of the rows which are NOT NULL.SUMandAVGcan only be used for numerical data.
Important
If you have a SELECT clause which includes both aggregations and non-aggregated columns, you must use a GROUP BY clause.
The FROM clause
The FROM clause shows the source data. This can be a table, a view or a query.
- A query used as a source is called a “derived query”. If you use one, you will need to alias it.
- You can alias the source tables as well. This is more often used when you have more than one source.
Joins
If you are using more than one table, you will need to JOIN them together. All joins apart from the CROSS JOIN need an ON. This condition shows how the two sources are related.
| Join | Rows returned |
|---|---|
| INNER JOIN or JOIN | Rows where both sources match. |
| LEFT [OUTER] JOIN | All the rows from the first-mentioned source (before the word JOIN), and only those in the second source which match. |
| RIGHT [OUTER] JOIN | All the rows from the second source, and only those in the first source which match. |
| FULL [OUTER] JOIN | All the rows in both sources, after seeing what matched. |
| CROSS JOIN | Each row in the first source matches each row in the second source. This is not often used. |
The WHERE clause
The WHERE clause filters the rows, based on at least one condition.
Comparison operators
| Operator | Meaning |
|---|---|
| = | The same as, or equal to |
| > | Greater than |
| >= | Greater than or equal to |
| < | Less than |
| <= | Less than or equal to |
| <> or != | Not equal to |
Text and date literals
Text and date literals are enclosed in apostrophes.
- For NCHAR and NVARCHAR text literals, you add a capital N before the first apostrophe.
-
Date literals are generally written as
'yyyy-mm-dd', or, if you have a time as well,'yyyy-mm-dd hh:mm:ss.fffffffff'or'yyyy-mm-ddThh:mm:ss.fffffffff'.- You should use two digits for hours, minutes and seconds.
- The f stands for fractional seconds. You can use between 1 and 9 decimal places, depending on the data type.
LIKE and wildcards
Text comparisons can also use LIKE, which can compare with the start, middle and/or end of strings. You can use:
- the two wildcards:
%, which stands for 0, 1, 2 or more characters, and_, which stands for exactly one character; [BM], to search for either the character B or M;[B-M], to search for the characters from B to M; and[^B-M], to search for any characters apart from those between B and M.
You can also use NOT LIKE.
Collation
Text comparisons can also use COLLATE to change the collation (how text is sorted). This includes:
- CS or CI – case-sensitive or case-insensitive: whether ‘b’ is the same as ‘B’; and
- AS or AI – accent-sensitive or accent-insensitive: whether ‘í’ is the same as ‘i’.
Multiple conditions
You can also search for multiple conditions using:
AND– the conditions on both sides of the AND must be true for the entire condition to be true; andOR– either condition must be true.
You can also use NOT to change true to false, and false to true. You can use brackets (parentheses) to group conditions together, or to make the condition more readable.
Ranges and missing data
- You can use
BETWEENto search for an inclusive range:ColumnName BETWEEN FirstValue AND SecondValue. - To search for missing data, you can use
IS NULL. You can also useIS NOT NULL.
Important
You cannot use any aliases declared in the SELECT clause in the WHERE clause.
The GROUP BY clause
Whether you need a GROUP BY clause depends on what is in the SELECT clause:
- If you use only aggregations in the SELECT clause, you do not use a GROUP BY clause.
- If you use only non-aggregations in the SELECT clause, you need not use a GROUP BY clause. If you do use one, it acts like DISTINCT.
- If you use both aggregations and non-aggregations in the SELECT clause, you must use a GROUP BY clause. You must put in the GROUP BY clause all of the non-aggregated columns which are shown in the SELECT clause.
As with the WHERE clause, you cannot use any aliases declared in the SELECT clause.
The HAVING clause
The HAVING clause can be used in conjunction with the GROUP BY clause. If you want to filter the rows after the GROUP BY clause, you can do so in the HAVING clause.
This is generally used with conditions which involve an aggregation. Again, you cannot use any aliases declared in the SELECT clause.
Exam tip
Keep the two filters distinct. The WHERE clause filters rows before they are grouped, while the HAVING clause filters after the GROUP BY clause, generally using a condition which involves an aggregation.
The ORDER BY clause
The ORDER BY clause orders the result, either ascending or descending.
- You use
ASCorDESC, not ASCENDING or DESCENDING. The default is ASC. - You should specify the column name, using either the original name or the alias. You could also use the column position – for example, 2 – but that is not recommended.
- The use of ASC or DESC applies only to the column that it follows. You can use either multiple times in an ORDER BY clause, but just once per column sorted.
Ties and NULLs
If there are multiple rows tied after ordering, the final position is left to SQL Server. This is called a non-deterministic order.
NULLs are treated as being smaller than the smallest value. So in ascending order they are first, and in descending order they are last.
Note
Unlike the WHERE, GROUP BY and HAVING clauses, the ORDER BY clause can use an alias declared in the SELECT clause.
Continue studying DP-800
This article covers the six principal clauses of the SELECT statement, the T-SQL foundations that the rest of the DP-800 study guide builds on.