Upload
james-newman
View
243
Download
2
Embed Size (px)
Citation preview
Queries
SELECT [DISTINCT] <columnlist>
FROM ( <table-list> {<alias>}|
<joined table>),...
[WHERE <condition>]
[GROUP BY <grouping columns>
[HAVING <group selection condition>]]
[ORDER BY <column name> [<order>],...]
The Basic Query Block
SELECT identifies what columns will be included (or displayed) in the query result
FROM identifies which table(s) to source rows
SELECT [DISTINCT] {SELECT [DISTINCT] {*,column [alias*,column [alias],...}],...}FROMFROM tabletableSELECT [DISTINCT] {SELECT [DISTINCT] {*,column [alias*,column [alias],...}],...}FROMFROM tabletable
Selecting All Columns, All Rows
SELECT SELECT **FROM sales_deptFROM sales_deptSELECT SELECT **FROM sales_deptFROM sales_dept
The simplest SELECT statement contains the following two clauses:– SELECT clause
• Asterisk (*) indicates all columns
– FROM clause
Selecting Specific Columns
List the columns in the SELECT clause. Separate columns by using a comma. Specify columns in the order you want
them to appear.
SELECT dept_id, lname, manager_idSELECT dept_id, lname, manager_idFROM sales_empFROM sales_empSELECT dept_id, lname, manager_idSELECT dept_id, lname, manager_idFROM sales_empFROM sales_emp
Arithmetic Expressions Create expressions on NUMBER and
DATE data types by using operators.• Add +• Subtract -• Multiply *• Divide /
e.g., Display the annual salary of employees:
SELECT lname, SELECT lname, salary * 12salary * 12, commission, commissionFROM sales_empFROM sales_empSELECT lname, SELECT lname, salary * 12salary * 12, commission, commissionFROM sales_empFROM sales_emp
Column Aliases
A column alias renames a column heading. Especially useful with calculations to provide a
meaningful column name. Immediately follows the column name in the
SELECT clause.– Optional AS keyword between column name and alias.
Double quotation marks are required if an alias contains spaces, special characters, or is case-sensitive.
Column Aliases
SELECT lname SELECT lname lastnamelastname, salary,, salary, 12 * salary + 10012 * salary + 100FROM sales_empFROM sales_emp
SELECT lname SELECT lname lastnamelastname, salary,, salary, 12 * salary + 10012 * salary + 100FROM sales_empFROM sales_emp
SELECT lname SELECT lname AS lastnameAS lastname, salary,, salary, 12 * salary + 100 12 * salary + 100 AS “new salary”AS “new salary”FROM sales_empFROM sales_emp
SELECT lname SELECT lname AS lastnameAS lastname, salary,, salary, 12 * salary + 100 12 * salary + 100 AS “new salary”AS “new salary”FROM sales_empFROM sales_emp
Optional AS keyword between column name and alias.Double quotation marks are required if an alias
contains spaces, special characters, or is case-sensitive.
DISTINCT Option
The default display of queries is all rows including duplicate rows.
Eliminate duplicate rows by using DISTINCT in the SELECT clause.
SELECT SELECT DISTINCTDISTINCT name nameFROM sales_deptFROM sales_deptSELECT SELECT DISTINCTDISTINCT name nameFROM sales_deptFROM sales_dept
SELECT nameSELECT nameFROM sales_deptFROM sales_deptSELECT nameSELECT nameFROM sales_deptFROM sales_dept
DISTINCT Option
DISTINCT applies to all columns in the SELECT list.
When DISTINCT is applied to multiple columns, the result represents the distinct combination of the columns (that is, no two resulting rows will have the same values for all their columns).
SELECT SELECT DISTINCTDISTINCT dept_id, title dept_id, titleFROM sales_empFROM sales_empSELECT SELECT DISTINCTDISTINCT dept_id, title dept_id, titleFROM sales_empFROM sales_emp
ORDER BY Clause Sort resulting rows with the ORDER BY
clause. – ASC – ascending order, default.– DESC – descending order.
ORDER BY clause appears last in a SELECT statement.
SELECT lname, dept_id, dstartSELECT lname, dept_id, dstartFROM sales_empFROM sales_empORDER BY lnameORDER BY lname
SELECT lname, dept_id, dstartSELECT lname, dept_id, dstartFROM sales_empFROM sales_empORDER BY lnameORDER BY lname
ORDER BY Clause
The default sort order is ascending. Use DESC to reverse the sort order. You can sort by expressions or aliases.
SELECT lname EMPLOYEE, dstartSELECT lname EMPLOYEE, dstartFROM sales_empFROM sales_empORDER BY EMPLOYEE DESCORDER BY EMPLOYEE DESC
SELECT lname EMPLOYEE, dstartSELECT lname EMPLOYEE, dstartFROM sales_empFROM sales_empORDER BY EMPLOYEE DESCORDER BY EMPLOYEE DESC
Null values are displayed
– Last for ascending sequences.
– First for descending sequences.
ORDER BY Clause You can order by position to save time.
SELECT lname, dept_id, salarySELECT lname, dept_id, salaryFROM sales_empFROM sales_empORDER BY dept_id, salary DESC,ORDER BY dept_id, salary DESC, commission ASCcommission ASC
SELECT lname, dept_id, salarySELECT lname, dept_id, salaryFROM sales_empFROM sales_empORDER BY dept_id, salary DESC,ORDER BY dept_id, salary DESC, commission ASCcommission ASC
SELECT lname, salary * 12SELECT lname, salary * 12FROM sales_empFROM sales_empORDER BY 2ORDER BY 2
SELECT lname, salary * 12SELECT lname, salary * 12FROM sales_empFROM sales_empORDER BY 2ORDER BY 2
You can sort by multiple columns.
The order of ORDER BY list is order of sort.
You can sort by a column that is not in the SELECT list.
WHERE Clause Restrict the rows returned by the query
using the WHERE clause. Follows the FROM clause. Conditions consist of the following:
– Column name, expression, constant– Comparison operator– Literal
SELECT lname, dept_id, salarySELECT lname, dept_id, salaryFROM sales_empFROM sales_empWHERE dept_id = 42WHERE dept_id = 42
SELECT lname, dept_id, salarySELECT lname, dept_id, salaryFROM sales_empFROM sales_empWHERE dept_id = 42WHERE dept_id = 42
WHERE Clause
Character strings and dates are enclosed within single quotation marks.
Character values are case-sensitive. The default date format is 'DD-MMM-YY'.
SELECT fname, lname, titleSELECT fname, lname, titleFROM sales_empFROM sales_empWHERE lname = 'Magee'WHERE lname = 'Magee'
SELECT fname, lname, titleSELECT fname, lname, titleFROM sales_empFROM sales_empWHERE lname = 'Magee'WHERE lname = 'Magee'
Comparison. Compare the value of one expression to the value of another expression.
Range. Test whether the value of an expression falls within a specified range of values.
Set membership. Test whether the value of an expression equals one of a set of values.
Pattern match. Test whether a string matches a specified pattern.
Null. Test whether a column has a null (unknown) value.
Basic Search Conditions
Comparison Search Condition Logical Comparison Operators
= > >= < <=
SQL Comparison Operators– BETWEEN ... AND...
– IN(list)
– LIKE
– IS NULL
Logical Operators– AND
– OR
– NOT
Comparison Search Condition
Sometimes it is easier to exclude rows you know you do not want.– Logical Comparison Operators
!= <> ^=
– Other SQL Operators• NOT BETWEEN
• NOT IN
• NOT LIKE
• IS NOT NULL
Set Membership Search Condition
SELECT id, name, region_idSELECT id, name, region_idFROM sales_deptFROM sales_deptWHEREWHERE region_id IN (1,3)region_id IN (1,3)
SELECT id, name, region_idSELECT id, name, region_idFROM sales_deptFROM sales_deptWHEREWHERE region_id IN (1,3)region_id IN (1,3)
Use the [NOT] IN operator to test for values in a list.
Pattern Match Search Condition
Use the LIKE operator to perform wildcard searches of valid search string values.
Search conditions can contain either literal characters or numbers.– "%" denotes none or many characters.– "_" denotes one character.
SELECT lnameSELECT lnameFROM sales_empFROM sales_empWHERE lname LIKE 'M%'WHERE lname LIKE 'M%'
SELECT lnameSELECT lnameFROM sales_empFROM sales_empWHERE lname LIKE 'M%'WHERE lname LIKE 'M%'
Pattern Match Search Condition
The LIKE operator can be used as a shortcut for some BETWEEN comparisons.
Pattern matching characters can be combined.
SELECT lnameSELECT lnameFROM sales_empFROM sales_empWHERE lname LIKE '_a%'WHERE lname LIKE '_a%'
SELECT lnameSELECT lnameFROM sales_empFROM sales_empWHERE lname LIKE '_a%'WHERE lname LIKE '_a%'
SELECT lname, dstartSELECT lname, dstartFROM sales_empFROM sales_empWHERE dstart LIKE '%91'WHERE dstart LIKE '%91'
SELECT lname, dstartSELECT lname, dstartFROM sales_empFROM sales_empWHERE dstart LIKE '%91'WHERE dstart LIKE '%91'
NULL Search Condition
Use the IS [NOT] NULL operator to test for null values.
Do not use the = operator.SELECT id, name, credit_ratingSELECT id, name, credit_ratingFROM FROM aless_customeraless_customerWHERE salesrep_id IS NULLWHERE salesrep_id IS NULL
SELECT id, name, credit_ratingSELECT id, name, credit_ratingFROM FROM aless_customeraless_customerWHERE salesrep_id IS NULLWHERE salesrep_id IS NULL
WHERE Clause: AND / OR Use AND or OR operators to create
complex conditions. AND requires both conditions to be TRUE.
OR requires either condition to be TRUE.
SELECT lname, salary, dept_id, titleSELECT lname, salary, dept_id, titleFROM sales_empFROM sales_empWHERE dept_id = 41 AND title = 'Clerk'WHERE dept_id = 41 AND title = 'Clerk'
SELECT lname, salary, dept_id, titleSELECT lname, salary, dept_id, titleFROM sales_empFROM sales_empWHERE dept_id = 41 AND title = 'Clerk'WHERE dept_id = 41 AND title = 'Clerk'
SELECT lname, salary, dept_id, titleSELECT lname, salary, dept_id, titleFROM sales_empFROM sales_empWHERE dept_id = 41 OR title = 'Clerk'WHERE dept_id = 41 OR title = 'Clerk'
SELECT lname, salary, dept_id, titleSELECT lname, salary, dept_id, titleFROM sales_empFROM sales_empWHERE dept_id = 41 OR title = 'Clerk'WHERE dept_id = 41 OR title = 'Clerk'
Overview of Functions in SQL
Use functions to -- Perform calculations on data. Modify individual data items. Manipulate output for groups of rows. Alter date formats for display. Convert column data types.
Two Types of SQL Functions
Single row functions– Character– Number– Date– Conversion
Multiple row functions– Group
SINGLESINGLEROWROW
MULTIMULTIROWROW
FUNCTIONFUNCTION
FUNCTIONFUNCTION
Single Row Functions
Manipulate data items. Accept arguments and return one value. Act on each row returned. Return one result per row. Modify the data type. Can be nested.
function_name function_name ((columncolumn||expressionexpression, ,
[[arg1, arg2,...arg1, arg2,...])])
function_name function_name ((columncolumn||expressionexpression, ,
[[arg1, arg2,...arg1, arg2,...])])
Group (Multiple Row) Functions
Also known as aggregate functions. Operate on a single column of a set of
rows in a table. Return a single value (or a list of values,
with one result for each group). Can be nested.
Group Functions
AVG (DISTINCT|ALL|n) SUM (DISTINCT|ALL|n) MAX (DISTINCT|ALL|expr) MIN (DISTINCT|ALL|expr) COUNT (DISTINCT|ALL|expr|*)
Group Functions: AVG, SUM
Use AVG and SUM functions to return the average and sum, respectively, of values in a column.
Accept only numeric data types.
SELECT AVG(salary), SUM(salary)SELECT AVG(salary), SUM(salary)FROM sales_empFROM sales_emp
WHERE UPPER(title) LIKE 'SALES%'WHERE UPPER(title) LIKE 'SALES%'
SELECT AVG(salary), SUM(salary)SELECT AVG(salary), SUM(salary)FROM sales_empFROM sales_emp
WHERE UPPER(title) LIKE 'SALES%'WHERE UPPER(title) LIKE 'SALES%'
Group Functions: MAX, MIN Use MAX and MIN functions to return
the maximum and minimum, respectively, values for a given column.
Accept any data type as argument.
SELECTSELECT MIN(lname), MAX(lname) MIN(lname), MAX(lname)FROMFROM sales_emp sales_empSELECTSELECT MIN(lname), MAX(lname) MIN(lname), MAX(lname)FROMFROM sales_emp sales_emp
SELECTSELECT MIN(salary), MAX(salary) MIN(salary), MAX(salary)FROMFROM sales_emp sales_empSELECTSELECT MIN(salary), MAX(salary) MIN(salary), MAX(salary)FROMFROM sales_emp sales_emp
SELECTSELECT MIN(dstart), MAX(dstart) MIN(dstart), MAX(dstart)FROMFROM sales_emp sales_empSELECTSELECT MIN(dstart), MAX(dstart) MIN(dstart), MAX(dstart)FROMFROM sales_emp sales_emp
Group Functions: COUNT
COUNT(*) returns the number of rows, including nulls and duplicates.SELECTSELECT COUNT(*)COUNT(*)FROMFROM sales_emp sales_empWHEREWHERE dept_id = 31dept_id = 31
SELECTSELECT COUNT(*)COUNT(*)FROMFROM sales_emp sales_empWHEREWHERE dept_id = 31dept_id = 31
Group Functions: COUNT
COUNT(expression) returns the number of non-null rows.
The use of DISTINCT before the column name eliminates duplicates.
SELECTSELECT COUNT(commission)COUNT(commission)FROMFROM sales_emp sales_empWHEREWHERE dept_id = 31dept_id = 31
SELECTSELECT COUNT(commission)COUNT(commission)FROMFROM sales_emp sales_empWHEREWHERE dept_id = 31dept_id = 31
SELECTSELECT COUNT(DISTINCT commission)COUNT(DISTINCT commission)FROMFROM sales_emp sales_empWHERE dept_id = 31WHERE dept_id = 31
SELECTSELECT COUNT(DISTINCT commission)COUNT(DISTINCT commission)FROMFROM sales_emp sales_empWHERE dept_id = 31WHERE dept_id = 31
Group Functions
If the SELECT clause includes an aggregate function and no GROUP BY clause is used to group data together, then no item in the SELECT list can include any reference to a column unless that column is the argument to an aggregate function.
The following is an illegal SQL statement:
SELECTSELECT id, COUNT(commission)id, COUNT(commission)FROMFROM sales_emp sales_emp
SELECTSELECT id, COUNT(commission)id, COUNT(commission)FROMFROM sales_emp sales_emp
Without the GROUP BY Clause
ID LAST_NAME DEPARTMENT-- --------- ----------2 Ngao 416 Urguhart 4116 Maduro 4117 Smith 41
Department 41 is displayed four times because it appears as the department number of four employees.
SELECTSELECT id, lname, dept_id DEPARTMENTid, lname, dept_id DEPARTMENT
FROM sales_empFROM sales_emp
WHERE dept_id = 41WHERE dept_id = 41
SELECTSELECT id, lname, dept_id DEPARTMENTid, lname, dept_id DEPARTMENT
FROM sales_empFROM sales_emp
WHERE dept_id = 41WHERE dept_id = 41
With the GROUP BY Clause
The GROUP BY clause displays one line of data for each department retrieved in the WHERE clause, and COUNT(*) displays the number of employees in each department (group) displayed.
SELECT dept_id, COUNT(*) ”Number” SELECT dept_id, COUNT(*) ”Number”
FROM sales_empFROM sales_emp
WHERE dept_id = 41WHERE dept_id = 41
GROUP BY dept_idGROUP BY dept_id
SELECT dept_id, COUNT(*) ”Number” SELECT dept_id, COUNT(*) ”Number”
FROM sales_empFROM sales_emp
WHERE dept_id = 41WHERE dept_id = 41
GROUP BY dept_idGROUP BY dept_id
DEPT_ID Number DEPT_ID Number
------- ------------- ------
41 4 41 4
DEPT_ID Number DEPT_ID Number
------- ------------- ------
41 4 41 4
GROUP BY Clause
List the number of customers in each credit rating.
SELECT credit_rating,SELECT credit_rating,
COUNT(*)COUNT(*) AS "# Customers" AS "# Customers"
FROM sales_customerFROM sales_customer
GROUP BY credit_ratingGROUP BY credit_rating
SELECT credit_rating,SELECT credit_rating,
COUNT(*)COUNT(*) AS "# Customers" AS "# Customers"
FROM sales_customerFROM sales_customer
GROUP BY credit_ratingGROUP BY credit_rating
GROUP BY Clause
List all job titles and the total monthly salary for each job title.
SELECT title, SELECT title, SUM(salary)SUM(salary) PAYROLL PAYROLL
FROM sales_empFROM sales_emp
WHERE title NOT LIKE 'VP%'WHERE title NOT LIKE 'VP%'
GROUP BY titleGROUP BY title
ORDER BY SUM(salary)ORDER BY SUM(salary)
SELECT title, SELECT title, SUM(salary)SUM(salary) PAYROLL PAYROLL
FROM sales_empFROM sales_emp
WHERE title NOT LIKE 'VP%'WHERE title NOT LIKE 'VP%'
GROUP BY titleGROUP BY title
ORDER BY SUM(salary)ORDER BY SUM(salary)
GROUP BY Clause
All columns in the SELECT list that are not in group functions must be in the GROUP BY clause.
The GROUP BY column does not have to be in the SELECT clause.
SELECT title, MAX(salary)SELECT title, MAX(salary)
FROM sales_empFROM sales_emp
GROUP BY titleGROUP BY title
SELECT title, MAX(salary)SELECT title, MAX(salary)
FROM sales_empFROM sales_emp
GROUP BY titleGROUP BY title
GROUP BY Clause
Any expression in the SELECT list that is not a group function must be listed in the GROUP BY clause. Otherwise, an error message will be displayed
SELECT region_id, COUNT(name)SELECT region_id, COUNT(name)
FROM sales_deptFROM sales_dept
ORA-00937: (region_id) not a single-ORA-00937: (region_id) not a single-
group group functiongroup group function
SELECT region_id, COUNT(name)SELECT region_id, COUNT(name)
FROM sales_deptFROM sales_dept
ORA-00937: (region_id) not a single-ORA-00937: (region_id) not a single-
group group functiongroup group function
GROUP BY Clause
Return summary results for groups and subgroups by listing more than one column in the GROUP BY clause.
Determine the default sort order of the results by the order of the columns in the GROUP BY clause.
SELECT dept_id, title, COUNT(*)SELECT dept_id, title, COUNT(*)
FROM sales_empFROM sales_emp
GROUP BY dept_id, titleGROUP BY dept_id, title
SELECT dept_id, title, COUNT(*)SELECT dept_id, title, COUNT(*)
FROM sales_empFROM sales_emp
GROUP BY dept_id, titleGROUP BY dept_id, title
GROUP Functions
WHERE clause cannot be used to restrict groups. Use the HAVING clause.
SELECT dept_id, AVG(salary)SELECT dept_id, AVG(salary)
FROM sales_empFROM sales_emp
WHERE AVG(salary) > 2000WHERE AVG(salary) > 2000
GROUP BY dept_idGROUP BY dept_id
ORA-00934: group function is not ORA-00934: group function is not
allowed hereallowed here
SELECT dept_id, AVG(salary)SELECT dept_id, AVG(salary)
FROM sales_empFROM sales_emp
WHERE AVG(salary) > 2000WHERE AVG(salary) > 2000
GROUP BY dept_idGROUP BY dept_id
ORA-00934: group function is not ORA-00934: group function is not
allowed hereallowed here
Recall: WHERE Clause
SELECT lname, titleSELECT lname, titleFROM sales_empFROM sales_empWHERE lname LIKE ’V%’WHERE lname LIKE ’V%’
LNAMELNAME TITLETITLE----------------------------------------------------VelasquezVelasquez PresidentPresident
Restrict Rows
Display a specific employee as restricted in the WHERE clause
Used to select rows to be displayed.
HAVING ClauseUsed to restrict groups.
– Step 1: Rows (that passed the WHERE condition) are grouped.
– Step 2: The group function is applied to each of the groups.
– Step 3: Groups matching the HAVING condition are displayed.
Column names used in the HAVING clause must also appear in the GROUP BY clause or be contained in the group functions.
SELECT title, TO_CHAR(12 * AVG(salary), SELECT title, TO_CHAR(12 * AVG(salary), ‘ ‘$99,999.99’) ”ANNUAL SALARY”, $99,999.99’) ”ANNUAL SALARY”, COUNT(*) ”NUMBER OF EMPLOYEES”COUNT(*) ”NUMBER OF EMPLOYEES”FROM sales_empFROM sales_empGROUP BY title GROUP BY title HAVING COUNT(*) > 2HAVING COUNT(*) > 2
SELECT title, TO_CHAR(12 * AVG(salary), SELECT title, TO_CHAR(12 * AVG(salary), ‘ ‘$99,999.99’) ”ANNUAL SALARY”, $99,999.99’) ”ANNUAL SALARY”, COUNT(*) ”NUMBER OF EMPLOYEES”COUNT(*) ”NUMBER OF EMPLOYEES”FROM sales_empFROM sales_empGROUP BY title GROUP BY title HAVING COUNT(*) > 2HAVING COUNT(*) > 2
TITLETITLE ANNUAL SALARYANNUAL SALARY NUMBER OF EMPLOYEESNUMBER OF EMPLOYEES---------------------------------------- ---------------------------- --------------------------------------Sales RepresentativeSales Representative $17,712.00$17,712.00 55Stock ClerkStock Clerk $11,388.00$11,388.00 1010Warehouse ManagerWarehouse Manager $14,776.80$14,776.80 55
Display specific groups of job titles as restricted in the HAVING clause.
HAVING Clause
HAVING Clause
The GROUP BY clause can be used even without using a group function in the SELECT clause.
To restrict rows based on the result of a group function, use a GROUP BY clause and a HAVING clause.SELECT dept_idSELECT dept_idFROM sales_empFROM sales_empGROUP BY dept_idGROUP BY dept_idHAVING SUM(salary) > 4000HAVING SUM(salary) > 4000
SELECT dept_idSELECT dept_idFROM sales_empFROM sales_empGROUP BY dept_idGROUP BY dept_idHAVING SUM(salary) > 4000HAVING SUM(salary) > 4000