Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI...

28
Dale Roberts 07/04/22 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail: [email protected] Complex Queries Complex Queries

Transcript of Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI...

Page 1: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts04/21/23 1

Department of Computer and Information Science,School of Science, IUPUI

Dale Roberts, Lecturer

Computer Science, IUPUI

E-mail: [email protected]

Complex QueriesComplex Queries

Page 2: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts2

Grouping Things TogetherGrouping Things TogetherANSI standard SQL Group functions:ANSI standard SQL Group functions:

AVG, COUNT, MAX, MIN, STDDEV, SUM, VARIANCEAVG, COUNT, MAX, MIN, STDDEV, SUM, VARIANCE

Others:Others:

88ii:: GROUPING GROUPING (used with(used with CUBE CUBE andand ROLLUP ROLLUP, see Ch.13), see Ch.13)

99i i statistical functions:statistical functions: CORR, COVAR_POP, COVAR_SAMP, CUME_DIST, CORR, COVAR_POP, COVAR_SAMP, CUME_DIST, DENSE_RANK, FIRST, FIRST_VALUE, GROUP_ID, GROUPING_ID, DENSE_RANK, FIRST, FIRST_VALUE, GROUP_ID, GROUPING_ID, LAST, PERCENTILE_CONT, PERCENTILE_DISC, PERCENT_RANK, LAST, PERCENTILE_CONT, PERCENTILE_DISC, PERCENT_RANK, RANK, REGR, STDDEV_POP, STDDEV_SAMP, VAR_POP, VAR_SAMPRANK, REGR, STDDEV_POP, STDDEV_SAMP, VAR_POP, VAR_SAMP

Obsolete? In 9Obsolete? In 9ii:: GLB, LUB GLB, LUB

Page 3: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts3

Grouping Things TogetherGrouping Things Together

A group function returns a single row for an entire group of queried A group function returns a single row for an entire group of queried rows. rows. NULL values are ignored in group functions.NULL values are ignored in group functions.Without a GROUP BY clause the data returned for a group function Without a GROUP BY clause the data returned for a group function is one row for the entire table. is one row for the entire table. WithWith a GROUP BY clause, one row is returned for a GROUP BY clause, one row is returned for eacheach group your group your data is subdivided into. data is subdivided into. The WHERE clause is evaluated before data are grouped in GROUP The WHERE clause is evaluated before data are grouped in GROUP BY clause. BY clause. The HAVING clause is similar to the WHERE clause, but it works on The HAVING clause is similar to the WHERE clause, but it works on entire groups of data.entire groups of data.DISTINCT keyword forces only unique occurrences to be DISTINCT keyword forces only unique occurrences to be considered in data groups.considered in data groups.When using a group by clause, these are the only selectable items:When using a group by clause, these are the only selectable items:

constants, constants, group functions, andgroup functions, andgroup expressions -- these must match exactly the group by clausegroup expressions -- these must match exactly the group by clause

Page 4: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts4

Grouping Things TogetherGrouping Things TogetherOrder of clause execution within select statements:Order of clause execution within select statements:

1.1. If the statement contains a WHERE clause, removes all rows that do not If the statement contains a WHERE clause, removes all rows that do not satisfy it.satisfy it.

2.2. Group rows together based on the GROUP BY clause.Group rows together based on the GROUP BY clause.

3.3. Calculate the results of the group functions for each group.Calculate the results of the group functions for each group.

4.4. Choose and eliminate groups based on the HAVING clause.Choose and eliminate groups based on the HAVING clause.

5.5. Order the results based on the ORDER BY clause.Order the results based on the ORDER BY clause.

Specify the GROUP BY and HAVING clauses after the WHERE clause. If Specify the GROUP BY and HAVING clauses after the WHERE clause. If both the GROUP BY and HAVING clauses are specified, they can appear in both the GROUP BY and HAVING clauses are specified, they can appear in either order.either order.

A side effect of GROUP BY is a ordered result, same effect as having an A side effect of GROUP BY is a ordered result, same effect as having an ORDER BY clause of the GROUP BY columns.ORDER BY clause of the GROUP BY columns.

Page 5: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts5

Grouping Things TogetherGrouping Things TogetherViews over groups, commonly used for percent of total calculations.Views over groups, commonly used for percent of total calculations.

Inline view example from p. 214:Inline view example from p. 214:select categoryname, counter, select categoryname, counter, (counter/bookcount)*100 “pct” (counter/bookcount)*100 “pct” from category_count, from category_count, (select count(*) as bookcount from bookshelf) (select count(*) as bookcount from bookshelf)order by categoryname;order by categoryname;

Group expressions can be used in the HAVING clause, even those not Group expressions can be used in the HAVING clause, even those not used in the SELECT clause.used in the SELECT clause.

Page 6: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts6

When One Query Depends upon AnotherWhen One Query Depends upon Another

Equi-Joins vs. Correlated SubqueriesEqui-Joins vs. Correlated Subqueries

Exists and IN SubqueriesExists and IN Subqueries

Outer Join, 8i and 9i syntaxOuter Join, 8i and 9i syntax

NOT IN replaced by Outer Join and NOT EXISTSNOT IN replaced by Outer Join and NOT EXISTS

NATURAL joins, INNER joinsNATURAL joins, INNER joins

UNION, INTERSECT, MINUSUNION, INTERSECT, MINUS

Page 7: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts7

Equi-joins vs. Correlated SubqueriesEqui-joins vs. Correlated SubqueriesSELECT W.Name, W.LodgingSELECT W.Name, W.Lodging

FROM Worker W, FROM Worker W, Workerskill WS, Workerskill WS, Lodging LLodging L

WHERE W.Name = WS.NameWHERE W.Name = WS.Name

and W.Lodging = L.Lodgingand W.Lodging = L.Lodging

and Skill = ‘COMBINE DRIVER’and Skill = ‘COMBINE DRIVER’

and Address LIKE ‘%EDMESTON%’;and Address LIKE ‘%EDMESTON%’;

SELECT Name, SELECT Name, LodgingLodging

FROM Worker FROM Worker

WHERE Name IN WHERE Name IN

(select Name FROM Workerskill(select Name FROM Workerskill

where Skill = ‘COMBINE DRIVER’where Skill = ‘COMBINE DRIVER’

and and LodgingLodging IN IN

(select Lodging FROM Lodging(select Lodging FROM Lodging

WHERE Address WHERE Address

LIKE ‘%EDMESTON%’)); LIKE ‘%EDMESTON%’));

Example from 8, 8i text.

Page 8: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts8

Another Correlated Subquery ExampleAnother Correlated Subquery ExampleThe following statement returns data about The following statement returns data about employees whose salaries exceed the employees whose salaries exceed the averages for their departments. The averages for their departments. The following statement assigns an alias to following statement assigns an alias to EMP, the table containing the salary EMP, the table containing the salary information, and then uses the alias in a information, and then uses the alias in a correlated subquery:correlated subquery:

SELECT deptno, ename, salSELECT deptno, ename, sal

FROM emp xFROM emp x

WHERE sal > WHERE sal > (SELECT AVG(sal)(SELECT AVG(sal)

FROM empFROM emp

WHERE x.deptno = deptno)WHERE x.deptno = deptno)

ORDER BY deptnoORDER BY deptno

For each row of the EMP table, the parent For each row of the EMP table, the parent query uses the correlated subquery to query uses the correlated subquery to compute the average salary for members of compute the average salary for members of the same department. The correlated the same department. The correlated subquery performs these steps for each row subquery performs these steps for each row of the EMP table:of the EMP table:

1. The DEPTNO of the row is 1. The DEPTNO of the row is determined.determined.

2. The DEPTNO is then used to 2. The DEPTNO is then used to evaluate the parent evaluate the parent query.query.

3. If that row’s salary is greater 3. If that row’s salary is greater than the average salary than the average salary for that for that row’s department, then the row is returned.row’s department, then the row is returned.

The subquery is evaluated once for each The subquery is evaluated once for each row of the EMP table.row of the EMP table.

Page 9: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts9

Exists and IN SubqueriesExists and IN SubqueriesThe EXISTS keyword is similar IN. EXISTS tests for the existence of any row. Unlike The EXISTS keyword is similar IN. EXISTS tests for the existence of any row. Unlike IN however, EXISTS does not match columns. Many times it is used with a correlated IN however, EXISTS does not match columns. Many times it is used with a correlated subquery.subquery.

select AuthorName, Titlefrom BOOKSHELF_AUTHOR BAwhere EXISTS (select * from BOOKSHELF_AUTHOR BA2 where BA.AuthorName =

BA2.AuthorNamegroup by BA2.AuthorNamehaving COUNT(BA2.Title) > 1)order by AuthorName, Title;

select AuthorName, Titlefrom BOOKSHELF_AUTHOR BAwhere AuthorName IN (select AuthorNam from BOOKSHELF_AUTHOR group by AuthorName having COUNT(Title) > 1)order by AuthorName, Title;

Page 10: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts10

Outer Join, Oracle 8i syntaxOuter Join, Oracle 8i syntax

The outer join extends the result of a simple join. An outer join returns all The outer join extends the result of a simple join. An outer join returns all rows that satisfy the join condition and those rows from one table for rows that satisfy the join condition and those rows from one table for which no rows from the other satisfy the join condition. Such rows are not which no rows from the other satisfy the join condition. Such rows are not returned by a simple join. returned by a simple join.

To write a query that performs an outer join of tables A and B and returns To write a query that performs an outer join of tables A and B and returns all rows from A, apply the outer join operator (+) to all columns of B in the all rows from A, apply the outer join operator (+) to all columns of B in the join condition. join condition.

For all rows in A that have no matching rows in B, Oracle returns NULL for For all rows in A that have no matching rows in B, Oracle returns NULL for any select list expressions containing columns of B. any select list expressions containing columns of B.

This is the basic syntax of an outer join of two tables:This is the basic syntax of an outer join of two tables:

SELECT table1.columnSELECT table1.column

FROM table1, table2FROM table1, table2

WHERE table1.column = table2.column(+)WHERE table1.column = table2.column(+)

Page 11: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts11

Outer Join RulesOuter Join RulesThe (+) operator can only appear in the The (+) operator can only appear in the WHERE clause, not in the select list, and WHERE clause, not in the select list, and can only be applied to a column of a table or can only be applied to a column of a table or view.view.If A and B are joined by multiple join If A and B are joined by multiple join conditions, the (+) operator must be used in conditions, the (+) operator must be used in all of these conditions.all of these conditions.The (+) operator can only be applied to a The (+) operator can only be applied to a column, rather than to an arbitrary column, rather than to an arbitrary expression, although an arbitrary expression, although an arbitrary expression can contain a column marked expression can contain a column marked with the (+) operator.with the (+) operator.A condition containing the (+) operator A condition containing the (+) operator cannot be combined with another condition cannot be combined with another condition using the OR logical operator.using the OR logical operator.A condition cannot use the IN comparison A condition cannot use the IN comparison operator to compare a column marked with operator to compare a column marked with the (+) operator to another expression.the (+) operator to another expression.A condition cannot compare a column A condition cannot compare a column marked with the (+) operator to a subquery.marked with the (+) operator to a subquery.

If the WHERE clause contains a condition If the WHERE clause contains a condition that compares a column from table B to a that compares a column from table B to a constant, the (+) operator must be applied to constant, the (+) operator must be applied to the column so that the rows from table A for the column so that the rows from table A for which Oracle has generated NULLs for this which Oracle has generated NULLs for this column are returned.column are returned.

In a query that performs outer joins of more In a query that performs outer joins of more than two pairs of tables, a single table can than two pairs of tables, a single table can only be the NULL–generated table for one only be the NULL–generated table for one other table. For this reason, you cannot other table. For this reason, you cannot apply the (+) operator to columns of B in the apply the (+) operator to columns of B in the join condition for A and B and the join join condition for A and B and the join condition for B and C. condition for B and C.

Page 12: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts12

Outer Join, 8i vs. 9i syntaxOuter Join, 8i vs. 9i syntax

NEW 9i syntax, right outer join:select B.Title, MAX(…)from BOOKSHELF_CHECKOUT BC

right outer join BOOKSHELF B

on BC.Title = B.Titlegroup by B.Title;This also returns same result:select B.Title, MAX(…)from BOOKSHELF_CHECKOUT BC

right outer join BOOKSHELF B

using (Title)group by B.Title;

Left outer join – changes the driving table to the left (2nd) table. Full outer join – can be achieved by a right and a left outer join queries

combined together with a UNION operator.

Pre 9i syntax:select B.Title, MAX(…)from BOOKSHELF_CHECKOUT BC, BOOKSHELF Bwhere BC.Title(+) = B.Titlegroup by B.Title;

Page 13: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts13

NOT IN replaced by Outer Join NOT IN replaced by Outer Join

Left and right queries return the same result, but NOT IN query on Left and right queries return the same result, but NOT IN query on left is much less efficient. left is much less efficient.

select Titleselect Title from BOOKSHELF from BOOKSHELF where Title NOT INwhere Title NOT IN (select Title (select Title from BOOKSHELF_CHECKOUT)from BOOKSHELF_CHECKOUT) order by Title;order by Title;

NOT IN queries use full table scans.NOT IN queries use full table scans.

Outer join queries can use indexes.Outer join queries can use indexes.

select distinct B.Title from BOOKSHELF_CHECKOUT BC, BOOKSHELF B where BC.Title(+) = B.Title and BC.Title IS NULL order by Title;

Page 14: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts14

NOT IN replaced by NOT EXISTSNOT IN replaced by NOT EXISTS

NOT EXISTS queries eliminate rows that cannot be joined, uses a NOT EXISTS queries eliminate rows that cannot be joined, uses a correlated subquery which can utilize indexes rather than full correlated subquery which can utilize indexes rather than full scans.scans.

select Titleselect Title from BOOKSHELF from BOOKSHELF where Title NOT INwhere Title NOT IN (select Title (select Title from BOOKSHELF_CHECKOUT)from BOOKSHELF_CHECKOUT) order by Title;order by Title;

select B.Title from BOOKSHELF B where not exists (select ‘x’ from BOOKSHELF_COUNT BC where BC.Title = B.Title)order by B.Title;

Page 15: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts15

NATURAL and INNER joinsNATURAL and INNER joins

Both are new Oracle9i syntax alternatives to Both are new Oracle9i syntax alternatives to traditional equi-join syntax.traditional equi-join syntax.

NATURAL join uses columns of same name in NATURAL join uses columns of same name in join.join.

select Titleselect Title from BOOK_ORDER natural join BOOKSHELF;from BOOK_ORDER natural join BOOKSHELF;

INNER join. INNER join. select BO.Titleselect BO.Title from BOOK_ORDER BO inner join BOOKSHELF Bfrom BOOK_ORDER BO inner join BOOKSHELF B on BO.Title = B.Title;on BO.Title = B.Title;

Page 16: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts16

UNION, INTERSECT, MINUSUNION, INTERSECT, MINUS

UNIONUNION returns distinct rows returns distinct rows for the combination of two for the combination of two select statements.select statements.

UNION ALLUNION ALL returns all rows returns all rows for the combination of two for the combination of two select statements regardless select statements regardless of duplication.of duplication.

INTERSECTINTERSECT returns distinct returns distinct rows for the combination of rows for the combination of two select statements where two select statements where data matches.data matches.

MINUSMINUS return the rows from return the rows from one select statement one select statement excluding the rows of a excluding the rows of a second select statementsecond select statement

Page 17: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts17

Set Operator ExamplesSet Operator Examples

An obvious example:An obvious example:select Name from Longtimeselect Name from Longtime minus minusselect Name from Prospectselect Name from Prospect

A subtle example:A subtle example:select Name, Lodging from Longtimeselect Name, Lodging from Longtime minus minusselect Name, Address from Prospectselect Name, Address from Prospect

Columns must be compatible for set Columns must be compatible for set operations, but not necessarily the same.operations, but not necessarily the same.

Page 18: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts18

Some Complex PossibilitiesSome Complex Possibilities

New 9i Statistical FunctionsNew 9i Statistical Functions

New 9i Temporary TablesNew 9i Temporary Tables

ROLLUP, GROUPING, CUBE (Oracle 8i)ROLLUP, GROUPING, CUBE (Oracle 8i)

START WITH, CONNECT BY, LEVEL (Oracle 7.x)START WITH, CONNECT BY, LEVEL (Oracle 7.x)

Page 19: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts19

Statistical FunctionsStatistical Functions

RANK is one of many new statistical functions in 9i.RANK is one of many new statistical functions in 9i. select RANK(3)select RANK(3)

within group (order by Counter desc)within group (order by Counter desc)

from CATEGORY_COUNT;from CATEGORY_COUNT;

PERCENT_RANK is another new statistical function.PERCENT_RANK is another new statistical function. select PERCENT_RANK(8)select PERCENT_RANK(8)

within group (order by Counter desc)within group (order by Counter desc)

from CATEGORY_COUNT;from CATEGORY_COUNT;

These have been added for new Oracle data warehousing These have been added for new Oracle data warehousing capabilities. capabilities.

Page 20: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts20

Statistical FunctionsStatistical Functions

Oracle example: 19-13 Hypothetical Rank and Distribution SyntaxOracle example: 19-13 Hypothetical Rank and Distribution Syntaxfrom from 19 SQL for Analysis in Data Warehouses 19 SQL for Analysis in Data Warehouses http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96520/analysis.htmhttp://download-west.oracle.com/docs/cd/B10501_01/server.920/a96520/analysis.htm

Using the list price data from the Using the list price data from the productsproducts table used throughout this table used throughout this section, you can calculate the section, you can calculate the RANKRANK, , PERCENT_RANKPERCENT_RANK and and CUME_DISTCUME_DIST for a hypothetical sweater with a price of $50 for how it fits within each of for a hypothetical sweater with a price of $50 for how it fits within each of the sweater subcategories. The query and results are:the sweater subcategories. The query and results are:

SELECT prod_subcategory, SELECT prod_subcategory, RANK(50) WITHIN GROUP (ORDER BY prod_list_price DESC) AS HRANK, RANK(50) WITHIN GROUP (ORDER BY prod_list_price DESC) AS HRANK, TO_CHAR(PERCENT_RANK(50) WITHIN GROUP (ORDER BY prod_list_price),'9.999') AS TO_CHAR(PERCENT_RANK(50) WITHIN GROUP (ORDER BY prod_list_price),'9.999') AS HPERC_RANK, HPERC_RANK, TO_CHAR(CUME_DIST (50) WITHIN GROUP (ORDER BY prod_list_price),'9.999') AS TO_CHAR(CUME_DIST (50) WITHIN GROUP (ORDER BY prod_list_price),'9.999') AS HCUME_DIST HCUME_DIST FROM products FROM products WHERE prod_subcategory LIKE 'Sweater%' WHERE prod_subcategory LIKE 'Sweater%' GROUP BY prod_subcategory; GROUP BY prod_subcategory;

PROD_SUBCATEGORY HRANK HPERC_RANK HCUME_DIST PROD_SUBCATEGORY HRANK HPERC_RANK HCUME_DIST ---------------- ----- ---------- ---------- ---------------- ----- ---------- ---------- Sweaters - Boys 16 .911 .912 Sweaters - Boys 16 .911 .912 Sweaters - Girls 1 1.000 1.000 Sweaters - Girls 1 1.000 1.000 Sweaters - Men 240 .351 .352 Sweaters - Men 240 .351 .352 Sweaters - Women 21 .783 .785 Sweaters - Women 21 .783 .785

Page 21: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts21

Temporary TablesTemporary TablesNew Oracle 9i feature.New Oracle 9i feature.Used to support aggregation/rollups of data.Used to support aggregation/rollups of data.To create a temp table, use the CREATE GLOBAL TEMPORARY To create a temp table, use the CREATE GLOBAL TEMPORARY TABLE command instead of CREATE TABLE.TABLE command instead of CREATE TABLE.For temp table for this session, use ON COMMIT PRESERVE ROWS For temp table for this session, use ON COMMIT PRESERVE ROWS clause.clause.For temp table only for this transaction, use ON COMMIT DELTE For temp table only for this transaction, use ON COMMIT DELTE ROWS clause.ROWS clause.

create global temporary table YEAR_ROLLUP (create global temporary table YEAR_ROLLUP ( YearYear NUMBER (4), NUMBER (4), Month VARCHAR2(9),Month VARCHAR2(9), Counter NUMBER)Counter NUMBER) on commit preserve rows;on commit preserve rows;

Page 22: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts22

ROLLUP, GROUPING, CUBEROLLUP, GROUPING, CUBENew Oracle 8i feature, provides OLAP like capability.New Oracle 8i feature, provides OLAP like capability.Provides similar feature as SQLPLUS’s compute sum/break on.Provides similar feature as SQLPLUS’s compute sum/break on.

ROLLUP – used in GROUP BY clause, adds rows to the groups that ROLLUP – used in GROUP BY clause, adds rows to the groups that includes total and subtotal rows.includes total and subtotal rows.GROUPING – used in SELECT, WHERE, HAVING clauses, returns a GROUPING – used in SELECT, WHERE, HAVING clauses, returns a value of 1 if the row is produced by the ROLLUP function in the value of 1 if the row is produced by the ROLLUP function in the GROUP BY clause. Often GROUPING is combined with DECODE.GROUP BY clause. Often GROUPING is combined with DECODE.CUBE – used instead of ROLLUP in GROUP BY clause. This will CUBE – used instead of ROLLUP in GROUP BY clause. This will return a subtotal line for all combinations the group by columns.return a subtotal line for all combinations the group by columns.

More Oracle documentation and examples:More Oracle documentation and examples:SQL for Aggregation in Data Warehouses SQL for Aggregation in Data Warehouses http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96520/aggreg.htm http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96520/aggreg.htm

Page 23: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts23

Hierarchical QueriesHierarchical QueriesCONNECT BY – used to indicate CONNECT BY – used to indicate relationship within hierarchy. relationship within hierarchy. PRIOR keyword indicates parent.PRIOR keyword indicates parent.START WITH – indicates root node.START WITH – indicates root node.LEVEL – pseudocolumn function thatLEVEL – pseudocolumn function thatreturns 1 for root, 2 for children of root,returns 1 for root, 2 for children of root,3 for next child level, etc. Usually 3 for next child level, etc. Usually combined with LPAD function.combined with LPAD function.

SELECT employee_id, last_name, manager_id, LEVEL SELECT employee_id, last_name, manager_id, LEVEL FROM employees FROM employees CONNECT BY PRIOR employee_id = manager_id;CONNECT BY PRIOR employee_id = manager_id;

EMPLOYEE_ID LAST_NAME MANAGER_ID LEVEL EMPLOYEE_ID LAST_NAME MANAGER_ID LEVEL ----------- ------------------------- ---------- --------------------- ------------------------- ---------- ---------- 101 Kochhar 100 1 101 Kochhar 100 1 108 Greenberg 101 2 108 Greenberg 101 2 109 Faviet 108 3 109 Faviet 108 3 110 Chen 108 3 110 Chen 108 3

More Oracle documentation and examples: More Oracle documentation and examples: Hierarchical QueriesHierarchical Querieshttp://download-west.oracle.com/docs/cd/B10501_01/server.920/a96540/queries4a.htm#2053937http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96540/queries4a.htm#2053937

Page 24: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts24

SQL*PLUSSQL*PLUSAdvanced FormattingAdvanced Formatting

break on column/row/reportbreak on column/row/reportcompute avg/count/max/min/num/sum/std/varcompute avg/count/max/min/num/sum/std/varttitle, btitle left/right/centerttitle, btitle left/right/centerNEW_VALUE NEW_VALUE sql.pnosql.pnonoprintnoprintskip n/pageskip n/pageset termout on/offset termout on/offfold_after, fold_before fold_after, fold_before (p.276)(p.276)

VariablesVariablesDefine without parameters it shows defined variables.Define without parameters it shows defined variables.Define with a variable name it sets that variable.Define with a variable name it sets that variable.Variables can also be defined with a ACCEPT command.Variables can also be defined with a ACCEPT command.‘‘&’ signifies the start of a variable name, ‘.’ ends a variable name.&’ signifies the start of a variable name, ‘.’ ends a variable name.

Select company from STOCKSelect company from STOCKwhere company = ‘&xCompany’;where company = ‘&xCompany’;

Page 25: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts25

Spooled Substitution of Variables Spooled Substitution of Variables

Spooled Substitution – making the output of a SQL script define Spooled Substitution – making the output of a SQL script define the value for a variable. the value for a variable.

set heading offset heading off

spool slave.sql spool slave.sql

select 'define myvar = '||itemselect 'define myvar = '||item

from LEDGERfrom LEDGER

where rate = (select max(rate) from LEDGER)where rate = (select max(rate) from LEDGER)

//

spool offspool off

@slave@slave

Page 26: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts26

DECODEDECODE

Decode is Oracle non-standard SQL. Extremely powerful, yet Decode is Oracle non-standard SQL. Extremely powerful, yet underutilized.underutilized.

Decode works similar to if/then/else Decode works similar to if/then/else

DECODE (DECODE (valuevalue, , if1if1, , then1then1, , if2if2, , then2then2,…, ,…, defaultdefault ) )

Common use illustrated in the text:Common use illustrated in the text:

Aggregating groups of data into a single column. Aggregating groups of data into a single column.

Flip a table on its side, ie rows become columns. Flip a table on its side, ie rows become columns.

Dividing data into sections based on row number. This is done in Dividing data into sections based on row number. This is done in conjunction with the MOD function. conjunction with the MOD function.

Complex computations that require if/then logic. Complex computations that require if/then logic.

Page 27: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts27

CASECASE

CASE, new in 9i, works just like DECODE Uses WHEN, THEN, ELSE, and END keywords

select distinct Decode(Category, ‘A’, ‘Adult’, ‘F’, ‘Fiction’, ‘N’, ‘Non-Fiction’, ‘C’, ‘Children’,

Category)from BOOKSHELF;

select distinct CASE Category when ‘A’ then ‘Adult’ when ‘F’ then ‘Fiction’ when ‘N’ then ‘Non-Fiction’ when ‘C’ then ‘Children’

else Category ENDfrom BOOKSHELF;

Page 28: Dale Roberts 12/6/2015 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI E-mail:

Dale Roberts04/21/23 28

AcknowledgementsAcknowledgements

Loney, Oracle Database 10g The Complete ReferenceLoney, Oracle Database 10g The Complete Reference