Presentation is loading. Please wait.

Presentation is loading. Please wait.

Queries SELECT [DISTINCT] FROM ( { }| ),... [WHERE ] [GROUP BY [HAVING ]] [ORDER BY [ ],...]

Similar presentations


Presentation on theme: "Queries SELECT [DISTINCT] FROM ( { }| ),... [WHERE ] [GROUP BY [HAVING ]] [ORDER BY [ ],...]"— Presentation transcript:

1 Queries SELECT [DISTINCT] FROM ( { }| ),... [WHERE ] [GROUP BY [HAVING ]] [ORDER BY [ ],...]

2 The Basic Query Block 4 SELECT identifies what columns will be included (or displayed) in the query result 4 FROM identifies which table(s) to source rows SELECT [DISTINCT] {*,column [alias],...} FROMtable SELECT [DISTINCT] {*,column [alias],...} FROMtable

3 Selecting All Columns, All Rows SELECT * FROM sales_dept SELECT * FROM sales_dept 4 The simplest SELECT statement contains the following two clauses: –SELECT clause Asterisk (*) indicates all columns –FROM clause

4 Selecting Specific Columns 4 List the columns in the SELECT clause. 4 Separate columns by using a comma. 4 Specify columns in the order you want them to appear. SELECT dept_id, lname, manager_id FROM sales_emp SELECT dept_id, lname, manager_id FROM sales_emp

5 Arithmetic Expressions 4 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, salary * 12, commission FROM sales_emp SELECT lname, salary * 12, commission FROM sales_emp

6 Column Aliases 4 A column alias renames a column heading. 4 Especially useful with calculations to provide a meaningful column name. 4 Immediately follows the column name in the SELECT clause. –Optional AS keyword between column name and alias. 4 Double quotation marks are required if an alias contains spaces, special characters, or is case- sensitive.

7 Column Aliases SELECT lname lastname, salary, 12 * salary + 100 12 * salary + 100 FROM sales_emp SELECT lname lastname, salary, 12 * salary + 100 12 * salary + 100 FROM sales_emp SELECT lname AS lastname, salary, 12 * salary + 100 AS “new salary” 12 * salary + 100 AS “new salary” FROM sales_emp SELECT lname AS lastname, salary, 12 * salary + 100 AS “new salary” 12 * salary + 100 AS “new salary” FROM 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.

8 DISTINCT Option 4 The default display of queries is all rows including duplicate rows. 4 Eliminate duplicate rows by using DISTINCT in the SELECT clause. SELECT DISTINCT name FROM sales_dept SELECT DISTINCT name FROM sales_dept SELECT name FROM sales_dept SELECT name FROM sales_dept

9 DISTINCT Option 4 DISTINCT applies to all columns in the SELECT list. 4 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 DISTINCT dept_id, title FROM sales_emp SELECT DISTINCT dept_id, title FROM sales_emp

10 ORDER BY Clause 4 Sort resulting rows with the ORDER BY clause. –ASC – ascending order, default. –DESC – descending order. 4 ORDER BY clause appears last in a SELECT statement. SELECT lname, dept_id, dstart FROM sales_emp ORDER BY lname SELECT lname, dept_id, dstart FROM sales_emp ORDER BY lname

11 ORDER BY Clause 4 The default sort order is ascending. 4 Use DESC to reverse the sort order. 4 You can sort by expressions or aliases. SELECT lname EMPLOYEE, dstart FROM sales_emp ORDER BY EMPLOYEE DESC SELECT lname EMPLOYEE, dstart FROM sales_emp ORDER BY EMPLOYEE DESC Null values are displayed –Last for ascending sequences. –First for descending sequences.

12 ORDER BY Clause You can order by position to save time. SELECT lname, dept_id, salary FROM sales_emp ORDER BY dept_id, salary DESC, commission ASC commission ASC SELECT lname, dept_id, salary FROM sales_emp ORDER BY dept_id, salary DESC, commission ASC commission ASC SELECT lname, salary * 12 FROM sales_emp ORDER BY 2 SELECT lname, salary * 12 FROM sales_emp ORDER 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.

13 WHERE Clause 4 Restrict the rows returned by the query using the WHERE clause. 4 Follows the FROM clause. 4 Conditions consist of the following: –Column name, expression, constant –Comparison operator –Literal SELECT lname, dept_id, salary FROM sales_emp WHERE dept_id = 42 SELECT lname, dept_id, salary FROM sales_emp WHERE dept_id = 42

14 WHERE Clause 4 Character strings and dates are enclosed within single quotation marks. 4 Character values are case-sensitive. 4 The default date format is 'DD-MMM-YY'. SELECT fname, lname, title FROM sales_emp WHERE lname = 'Magee' SELECT fname, lname, title FROM sales_emp WHERE lname = 'Magee'

15 4 Comparison. Compare the value of one expression to the value of another expression. 4 Range. Test whether the value of an expression falls within a specified range of values. 4 Set membership. Test whether the value of an expression equals one of a set of values. 4 Pattern match. Test whether a string matches a specified pattern. 4 Null. Test whether a column has a null (unknown) value. Basic Search Conditions

16 Comparison Search Condition 4 Logical Comparison Operators = > >= < <= 4 SQL Comparison Operators –BETWEEN... AND... –IN(list) –LIKE –IS NULL 4 Logical Operators –AND –OR –NOT

17 Comparison Search Condition 4 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

18 Set Membership Search Condition SELECT id, name, region_id FROM sales_dept WHERE region_id IN (1,3) SELECT id, name, region_id FROM sales_dept WHERE region_id IN (1,3) 4 Use the [NOT] IN operator to test for values in a list.

19 Pattern Match Search Condition 4 Use the LIKE operator to perform wildcard searches of valid search string values. 4 Search conditions can contain either literal characters or numbers. –"%" denotes none or many characters. –"_" denotes one character. SELECT lname FROM sales_emp WHERE lname LIKE 'M%' SELECT lname FROM sales_emp WHERE lname LIKE 'M%'

20 Pattern Match Search Condition 4 The LIKE operator can be used as a shortcut for some BETWEEN comparisons. 4 Pattern matching characters can be combined. SELECT lname FROM sales_emp WHERE lname LIKE '_a%' SELECT lname FROM sales_emp WHERE lname LIKE '_a%' SELECT lname, dstart FROM sales_emp WHERE dstart LIKE '%91' SELECT lname, dstart FROM sales_emp WHERE dstart LIKE '%91'

21 NULL Search Condition 4 Use the IS [NOT] NULL operator to test for null values. 4 Do not use the = operator. SELECT id, name, credit_rating FROM aless_customer WHERE salesrep_id IS NULL SELECT id, name, credit_rating FROM aless_customer WHERE salesrep_id IS NULL

22 WHERE Clause: AND / OR 4 Use AND or OR operators to create complex conditions. 4 AND requires both conditions to be TRUE. 4 OR requires either condition to be TRUE. SELECT lname, salary, dept_id, title FROM sales_emp WHERE dept_id = 41 AND title = 'Clerk' SELECT lname, salary, dept_id, title FROM sales_emp WHERE dept_id = 41 AND title = 'Clerk' SELECT lname, salary, dept_id, title FROM sales_emp WHERE dept_id = 41 OR title = 'Clerk' SELECT lname, salary, dept_id, title FROM sales_emp WHERE dept_id = 41 OR title = 'Clerk'

23 Overview of Functions in SQL Use functions to -- 4 Perform calculations on data. 4 Modify individual data items. 4 Manipulate output for groups of rows. 4 Alter date formats for display. 4 Convert column data types.

24 Two Types of SQL Functions 4 Single row functions –Character –Number –Date –Conversion 4 Multiple row functions –Group SINGLEROW MULTIROW FUNCTION FUNCTION

25 Single Row Functions 4 Manipulate data items. 4 Accept arguments and return one value. 4 Act on each row returned. 4 Return one result per row. 4 Modify the data type. 4 Can be nested. function_name (column|expression, [arg1, arg2,...]) [arg1, arg2,...]) function_name (column|expression, [arg1, arg2,...]) [arg1, arg2,...])

26 Group (Multiple Row) Functions 4 Also known as aggregate functions. 4 Operate on a single column of a set of rows in a table. 4 Return a single value (or a list of values, with one result for each group). 4 Can be nested.

27 Group Functions 4 AVG (DISTINCT|ALL|n) 4 SUM (DISTINCT|ALL|n) 4 MAX (DISTINCT|ALL|expr) 4 MIN (DISTINCT|ALL|expr) 4 COUNT (DISTINCT|ALL|expr|*)

28 Group Functions: AVG, SUM 4 Use AVG and SUM functions to return the average and sum, respectively, of values in a column. 4 Accept only numeric data types. SELECT AVG(salary), SUM(salary) FROM sales_emp WHERE UPPER(title) LIKE 'SALES%' SELECT AVG(salary), SUM(salary) FROM sales_emp WHERE UPPER(title) LIKE 'SALES%'

29 Group Functions: MAX, MIN 4 Use MAX and MIN functions to return the maximum and minimum, respectively, values for a given column. 4 Accept any data type as argument. SELECT MIN(lname), MAX(lname) FROM sales_emp SELECT MIN(lname), MAX(lname) FROM sales_emp SELECT MIN(salary), MAX(salary) FROM sales_emp SELECT MIN(salary), MAX(salary) FROM sales_emp SELECT MIN(dstart), MAX(dstart) FROM sales_emp SELECT MIN(dstart), MAX(dstart) FROM sales_emp

30 Group Functions: COUNT 4 COUNT(*) returns the number of rows, including nulls and duplicates. SELECTCOUNT(*) FROM sales_emp WHEREdept_id = 31 SELECTCOUNT(*) FROM sales_emp WHEREdept_id = 31

31 Group Functions: COUNT 4 COUNT(expression) returns the number of non-null rows. 4 The use of DISTINCT before the column name eliminates duplicates. SELECTCOUNT(commission) FROM sales_emp WHEREdept_id = 31 SELECTCOUNT(commission) FROM sales_emp WHEREdept_id = 31 SELECTCOUNT(DISTINCT commission) FROM sales_emp WHERE dept_id = 31 SELECTCOUNT(DISTINCT commission) FROM sales_emp WHERE dept_id = 31

32 Group Functions 4 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. 4 The following is an illegal SQL statement: SELECTid, COUNT(commission) FROM sales_emp SELECTid, COUNT(commission) FROM sales_emp

33 Without the GROUP BY Clause IDLAST_NAMEDEPARTMENT --------------------- 2Ngao41 6Urguhart41 16Maduro41 17Smith41 Department 41 is displayed four times because it appears as the department number of four employees. SELECTid, lname, dept_id DEPARTMENT FROM sales_emp WHERE dept_id = 41 SELECTid, lname, dept_id DEPARTMENT FROM sales_emp WHERE dept_id = 41

34 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” FROM sales_emp WHERE dept_id = 41 GROUP BY dept_id DEPT_ID Number ------- ------ 41 4

35 GROUP BY Clause 4 List the number of customers in each credit rating. SELECT credit_rating, COUNT(*) AS "# Customers" COUNT(*) AS "# Customers" FROM sales_customer GROUP BY credit_rating SELECT credit_rating, COUNT(*) AS "# Customers" COUNT(*) AS "# Customers" FROM sales_customer GROUP BY credit_rating

36 GROUP BY Clause 4 List all job titles and the total monthly salary for each job title. SELECT title, SUM(salary) PAYROLL FROM sales_emp WHERE title NOT LIKE 'VP%' GROUP BY title ORDER BY SUM(salary) SELECT title, SUM(salary) PAYROLL FROM sales_emp WHERE title NOT LIKE 'VP%' GROUP BY title ORDER BY SUM(salary)

37 GROUP BY Clause 4 All columns in the SELECT list that are not in group functions must be in the GROUP BY clause. 4 The GROUP BY column does not have to be in the SELECT clause. SELECT title, MAX(salary) FROM sales_emp GROUP BY title SELECT title, MAX(salary) FROM sales_emp GROUP BY title

38 GROUP BY Clause 4 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) FROM sales_dept ORA-00937: (region_id) not a single- group group function group group function SELECT region_id, COUNT(name) FROM sales_dept ORA-00937: (region_id) not a single- group group function group group function

39 GROUP BY Clause 4 Return summary results for groups and subgroups by listing more than one column in the GROUP BY clause. 4 Determine the default sort order of the results by the order of the columns in the GROUP BY clause. SELECT dept_id, title, COUNT(*) FROM sales_emp GROUP BY dept_id, title SELECT dept_id, title, COUNT(*) FROM sales_emp GROUP BY dept_id, title

40 GROUP Functions 4 WHERE clause cannot be used to restrict groups. Use the HAVING clause. SELECT dept_id, AVG(salary) FROM sales_emp WHERE AVG(salary) > 2000 GROUP BY dept_id ORA-00934: group function is not allowed here allowed here SELECT dept_id, AVG(salary) FROM sales_emp WHERE AVG(salary) > 2000 GROUP BY dept_id ORA-00934: group function is not allowed here allowed here

41 Recall: WHERE Clause SELECT lname, title FROM sales_emp WHERE lname LIKE ’V%’ LNAMETITLE -------------------------- VelasquezPresident Restrict Rows Display a specific employee as restricted in the WHERE clause 4 Used to select rows to be displayed.

42 HAVING Clause 4 Used 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. 4 Column names used in the HAVING clause must also appear in the GROUP BY clause or be contained in the group functions.

43 SELECT title, TO_CHAR(12 * AVG(salary), ‘$99,999.99’) ”ANNUAL SALARY”, ‘$99,999.99’) ”ANNUAL SALARY”, COUNT(*) ”NUMBER OF EMPLOYEES” FROM sales_emp GROUP BY title HAVING COUNT(*) > 2 COUNT(*) ”NUMBER OF EMPLOYEES” FROM sales_emp GROUP BY title HAVING COUNT(*) > 2 SELECT title, TO_CHAR(12 * AVG(salary), ‘$99,999.99’) ”ANNUAL SALARY”, ‘$99,999.99’) ”ANNUAL SALARY”, COUNT(*) ”NUMBER OF EMPLOYEES” FROM sales_emp GROUP BY title HAVING COUNT(*) > 2 COUNT(*) ”NUMBER OF EMPLOYEES” FROM sales_emp GROUP BY title HAVING COUNT(*) > 2 TITLEANNUAL SALARYNUMBER OF EMPLOYEES ----------------------------------------------------- Sales Representative$17,712.005 Stock Clerk$11,388.0010 Warehouse Manager$14,776.805 Display specific groups of job titles as restricted in the HAVING clause. HAVING Clause

44 4 The GROUP BY clause can be used even without using a group function in the SELECT clause. 4 To restrict rows based on the result of a group function, use a GROUP BY clause and a HAVING clause. SELECT dept_id FROM sales_emp GROUP BY dept_id HAVING SUM(salary) > 4000 SELECT dept_id FROM sales_emp GROUP BY dept_id HAVING SUM(salary) > 4000


Download ppt "Queries SELECT [DISTINCT] FROM ( { }| ),... [WHERE ] [GROUP BY [HAVING ]] [ORDER BY [ ],...]"

Similar presentations


Ads by Google