Upload
austin-wilkerson
View
214
Download
1
Embed Size (px)
Citation preview
Sorting data and Other selection Techniques
Ordering data results
Allows us to view our data in a more meaningful way. Rather than just a list of raw data, we can sort on one or many different criteria. This will allow us and/or the user to focus on the items of interest.
ORDER BY clause
Simplest form:
SELECT column
FROM table
ORDER BY column
Nested OrderingOrdering can occur on a number of levels. When you
ORDER BY on more than one column the first column takes highest precedence and goes down the line.
Example:SELECT author, price, title
FROM booksORDER BY price, title, author
The results would be ordered by price, then title and then author… in ascending order. Ascending order is the default.
Sort order
We can change sort order using the
DESC (for descending) and ASC (for
ascending) keywords.Example:
SELECT author, title, price
FROM books
ORDER BY price desc, author
Note: author would still be sorted ascending. DESC only affects the price column.
Ordering ExpressionsWhen we want to order expressions we
need to refer to the expression by its alias or its position.
Example:SELECT price * .9 disc, author, title
FROM booksORDER BY disc, title
orODER BY 1, title
Eliminating DuplicatesALL the default returns all qualified rows
DISTINCT returns only unique when more than 1 item in SELECT list, returns only the unique
combinations.
Both can only occur once and only at the beginning of the SELCT list.
SELECT DISTINCT book_storeFROM stores
Non-select list Order ByOn systems that allow it, having a
column listed in the ORDER BY and not in the SELECT list broadens the scope of the query to include that column as well.
The column is NOT displayed in the results. Only the affected rows.
Grouping data
Grouping data allows us to view aggregated data in reference to a field of interest. This makes for a powerful reporting tool.
GROUP BY clause
Groups results by column name
used with aggregate functions
SyntaxSELECT col_1, max(col_2) FROM table
GROUP BY col_1column in GROUP BY must be in SELECT listThere can be multiple columns in GROUP BY. Where their list order is their order of precedence.
Limitations
•There must be only 1 value returned for
each GROUP BY field.
•Should only use column names
•Due to these limitations, many vendors
provide report generators
Grouping and NullsNulls are assigned a group of there own
since they are, in a sense, their own datatype.
HAVING clauseSame as WHERE clause except it
allows aggregate functions
Formatting TextgetDate() - returns today’s dateSELECT getDate()
char_length(data) - returns the lengthSELECT char_length(‘John’)
upper(data) - returns the uppercaselower(data) - returns the lowercaseconcatonation SELECT (name +` `+address+`,`+state)