Copyright 2017, Oracle and/or its aff iliates. All rights reserved.

Size: px
Start display at page:

Download "Copyright 2017, Oracle and/or its aff iliates. All rights reserved."

Transcription

1

2 Safe Harbor Statement The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle s products remains at the sole discretion of Oracle.

3 Window functions in MySQL 8 Dag H. Wanvik Senior database engineer MySQL optimizer team Sep. 2017

4 Program Agenda Introduction: what & why What's supported Ranking and analytical wfs Implementation & performance

5 PART I Gentle intro in which we meet the SUM aggregate used as a window function and get introduced to window partitions and window frames

6 Why window functions? Part of SQL standard since 2003, with later additions Frequently requested feature(s) for data analysis Improves readability and often performance Most vendors support it, but to varying degrees (YMMV)

7 Why window functions? SELECT name o_name, department_id, salary AS o_salary, (SELECT SUM(salary) AS sum FROM employee WHERE salary <= o_salary AND NOT (salary = o_salary AND o_name > name)) AS sum FROM employee ORDER BY sum, name; SELECT name, department_id, salary, SUM(salary) OVER w AS sum FROM employee WINDOW w AS (ORDER BY salary, name ROWS UNBOUNDED PRECEDING) ORDER BY sum, name; name department_id salary sum Dag 10 NULL NULL Frederik Jon Lena Paula Michael William Nils NULL Nils Erik Rose Readability Performance my laptop: 50,000 rows: 16m vs 0.14s Or use self join, but tricky

8 What's a SQL window function? Short answer: a function that gets its arguments from a set of rows; a window defined by a partition and a frame. OK, but what is partitioned data? what is a frame? what does a window function look like? Hint: OVER keyword

9 Running ex: employees SELECT name, department_id, salary FROM employee ORDER BY department_id, name; name department_id salary Nils NULL Dag 10 NULL Erik Frederik Jon Michael Lena Nils Paula Rose William

10 Salaries per dept Query: find sums of salaries per department SELECT department_id, SUM(salary) FROM employee GROUP BY department_id ORDER BY department_id; name department_id salary Nils NULL Dag 10 NULL Erik Frederik Jon Michael Lena Nils Paula Rose William department_id SUM(salary) NULL

11 Grouping loss SELECT department_id, SUM(salary) FROM employee GROUP BY department_id; Identity of names and salaries lost. Lena Nils Paula

12 Windowing SELECT name, department_id, salary FROM employee ORDER BY department_id, name; name department_id salary Nils NULL Dag 10 NULL Erik Frederik Jon Michael Lena Nils Paula Rose William

13 Windowing, rows kept SELECT name, department_id, salary, SUM(salary) OVER () sum FROM employee ORDER BY department_id, name; name department_id salary sum Nils NULL Dag 10 NULL Erik Frederik Jon Michael Lena Nils Paula Rose William

14 Windowing, «grouped» SELECT name, department_id, salary, SUM(salary) OVER (PARTITION BY department_id) sum FROM employee ORDER BY department_id, name; name department_id salary sum Nils NULL Dag 10 NULL Erik Frederik Jon Michael Lena Nils Paula Rose William

15 Partition == frame SELECT name, department_id, salary, SUM(salary) OVER (PARTITION BY department_id) sum FROM employee ORDER BY department_id, name; name department_id salary sum Nils NULL Dag 10 NULL Erik Frederik Jon Michael Lena Nils Paula Rose William All salaries in partition added: the window frame is the entire partition

16 Windowing, rows kept SELECT name, salary, department_id, SUM(salary) OVER (PARTITION BY department_id) sum FROM employee ORDER BY department_id; Identity of department names and salaries kept: no rows are lost => A window function is similar to a scalar function: adds a result column => BUT: can read data from other rows than its own: within its WINDOW partition or frame Lena Nils Paula

17 Default partition SELECT name, department_id, salary, SUM(salary) OVER () sum FROM employee ORDER BY department_id, name; name department_id salary sum Nils NULL Dag 10 NULL Erik Frederik Jon Michael Lena Nils Paula Rose William No partition specified: the window frame is the entire result set

18 Cumulative sum SELECT name, department_id, salary, SUM(salary) OVER (ORDER BY department_id, name ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) sum FROM employee ORDER BY department_id, name; name department_id salary sum Nils NULL Dag 10 NULL Erik Frederik Jon Michael Lena Nils Paula Rose William No partition specified: the window frame grows

19 Cumulative sum SELECT name, department_id, salary, SUM(salary) OVER (ORDER BY department_id, name ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) sum FROM employee ORDER BY department_id, name; name department_id salary sum Nils NULL Dag 10 NULL Erik Frederik Jon Michael Lena Nils Paula Rose William No partition specified: the window frame grows

20 Cumulative sum SELECT name, department_id, salary, SUM(salary) OVER (ORDER BY department_id, name ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) sum FROM employee ORDER BY department_id, name; name department_id salary sum Nils NULL Dag 10 NULL Erik Frederik Jon Michael Lena Nils Paula Rose William No partition specified: the window frame grows

21 Cumulative sum SELECT name, department_id, salary, SUM(salary) OVER (ORDER BY department_id, name ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) sum FROM employee ORDER BY department_id, name; name department_id salary sum Nils NULL Dag 10 NULL Erik Frederik Jon Michael Lena Nils Paula Rose William No partition specified: the window frame grows

22 Cumulative sum SELECT name, department_id, salary, SUM(salary) OVER (ORDER BY department_id, name ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) sum FROM employee ORDER BY department_id, name; name department_id salary sum Nils NULL Dag 10 NULL Erik Frederik Jon Michael Lena Nils Paula Rose William No partition specified: the window frame grows

23 Cumulative sum, partitioned SELECT name, department_id, salary, SUM(salary) OVER (PARTITION BY department_id ORDER BY name ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) sum FROM employee ORDER BY department_id, name; name department_id salary sum Nils NULL Dag 10 NULL NULL Erik Frederik Jon Michael Lena Nils Paula Rose William No partition specified: the window frame grows New partition: reset sum

24 Cumulative sum, partitioned SELECT name, department_id, salary, SUM(salary) OVER (PARTITION BY department_id ORDER BY name ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) sum FROM employee ORDER BY department_id, name; name department_id salary sum Nils NULL Dag 10 NULL NULL Erik Frederik Jon Michael Lena Nils Paula Rose William No partition specified: the window frame grows

25 Cumulative sum, partitioned SELECT name, department_id, salary, SUM(salary) OVER (PARTITION BY department_id ORDER BY name ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) sum FROM employee ORDER BY department_id, name; name department_id salary sum Nils NULL Dag 10 NULL NULL Erik Frederik Jon Michael Lena Nils Paula Rose William No partition specified: the window frame grows

26 Parts of window function SELECT name, department_id, salary, SUM(salary) OVER (PARTITION BY department_id ORDER BY name ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) sum FROM employee ORDER BY department_id, name; Function call + OVER keyword signals a window function

27 Parts of window function SELECT name, department_id, salary, SUM(salary) OVER (PARTITION BY department_id ORDER BY name ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) sum FROM employee ORDER BY department_id, name; An optional partition specification: PARTITION BY <expression> {, <expression}* A partition divides up the result set in disjoint sets A window function does not see rows in partitions other than that of the current row for which it is being evaluated

28 Parts of window function SELECT name, department_id, salary, SUM(salary) OVER (PARTITION BY department_id ORDER BY name ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) sum FROM employee ORDER BY department_id, name; An optional ordering specification: ORDER BY <expression> {, <expression}* Orders the row within the partition Not the same as a final query ORDER BY and makes no guarantees of final query row ordering.

29 ORDER BY: growing frame Some window functions need row ordering to be useful, e.g. RANK Peers: same value for ORDER BY expression(s) SELECT name, department_id, salary, SUM(salary) OVER (ORDER BY salary DESC) AS sum FROM employee; name department_id salary sum Rose Erik Nils Nils NULL Michael William Lena Paula Frederik Jon Dag 10 NULL

30 ORDER BY: growing frame Some window functions need row ordering to be useful, e.g. RANK Peers: same value for ORDER BY expression(s) SELECT name, department_id, salary, SUM(salary) OVER (ORDER BY salary DESC) AS sum FROM employee; name department_id salary sum Rose Erik Nils Nils NULL Michael William Lena Paula Frederik Jon Dag 10 NULL

31 ORDER BY: growing frame Some window functions need row ordering to be useful, e.g. RANK Peers: same value for ORDER BY expression(s) SELECT name, department_id, salary, SUM(salary) OVER (ORDER BY salary DESC) AS sum FROM employee; name department_id salary sum Rose Erik Nils Nils NULL Michael William Lena Paula Frederik Jon Dag 10 NULL

32 ORDER BY: growing frame Some window functions need row ordering to be useful, e.g. RANK Peers: same value for ORDER BY expression(s) SELECT name, department_id, salary, SUM(salary) OVER (ORDER BY salary DESC) AS sum FROM employee; name department_id salary sum Rose Erik Nils Nils NULL Michael William Lena Paula Frederik Jon Dag 10 NULL

33 ORDER BY: growing frame PEERS Some window functions need row ordering to be useful, e.g. RANK Peers: same value for ORDER BY expression(s) SELECT name, department_id, salary, SUM(salary) OVER (ORDER BY salary DESC) AS sum FROM employee; name department_id salary sum Rose Erik Nils Nils NULL Michael William Lena Paula Frederik Jon Dag 10 NULL What happened here? Answer: Two rows are peers w.r.t. salary This is an example of a RANGE frame (implicit)

34 Parts of window function SELECT name, department_id, salary, SUM(salary) OVER (PARTITION BY department_id ORDER BY name ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) sum FROM employee ORDER BY department_id, name; An optional frame specification A subset of rows within a partition Extent can depend on the current row Default frame: partition Not all window functions heed frame

35 Frame anatomy partition n PRECEDING m FOLLOWING UNBOUNDED PRECEDING CURRENT ROW UNBOUNDED FOLLOWING Examples: ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW RANGE CURRENT ROW ROWS BETWEEN CURRENT ROW AND 3 FOLLOWING ROWS BETWEEN 2 PRECEDING AND 2 FOLLOWING n: numeric or temporal RANGE INTERVAL 6 DAY PRECEDING

36 Frame anatomy partition n PRECEDING m FOLLOWING UNBOUNDED PRECEDING CURRENT ROW UNBOUNDED FOLLOWING Examples: ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW RANGE CURRENT ROW ROWS BETWEEN CURRENT ROW AND 3 FOLLOWING ROWS BETWEEN 2 PRECEDING AND 2 FOLLOWING n: numeric or temporal RANGE INTERVAL 6 DAY PRECEDING

37 Frame anatomy partition UNBOUNDED PRECEDING CURRENT ROW Examples: ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW RANGE CURRENT ROW ROWS BETWEEN CURRENT ROW AND 3 FOLLOWING ROWS BETWEEN 2 PRECEDING AND 2 FOLLOWING n: numeric or temporal RANGE INTERVAL 6 DAY PRECEDING

38 Frame anatomy partition Examples: ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW CURRENT ROW and peers RANGE CURRENT ROW ROWS BETWEEN CURRENT ROW AND 3 FOLLOWING ROWS BETWEEN 2 PRECEDING AND 2 FOLLOWING RANGE INTERVAL 6 DAY PRECEDING

39 Frame anatomy partition Examples: 3 FOLLOWING CURRENT ROW ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW RANGE CURRENT ROW ROWS BETWEEN CURRENT ROW AND 3 FOLLOWING ROWS BETWEEN 2 PRECEDING AND 2 FOLLOWING RANGE INTERVAL 6 DAY PRECEDING

40 Frame anatomy partition 3 PRECEDING 2 FOLLOWING CURRENT ROW Examples: ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW RANGE CURRENT ROW ROWS BETWEEN CURRENT ROW AND 3 FOLLOWING ROWS BETWEEN 2 PRECEDING AND 2 FOLLOWING RANGE INTERVAL 6 DAY PRECEDING

41 ROWS vs. RANGE Frame boundaries: physical (ROWS) or logical (RANGE) ROWS: bound N: # rows. Peers are ignored. RANGE requires ORDER BY on a single numeric or temporal expression RANGE: bound N: rows with value for ascending ORDER BY expression within N lower (PRECEDING) and M higher (FOLLOWING) of value of the current row. Peers are always included in frame. Ex: ORDER BY date RANGE BETWEEN INTERVAL 6 DAY PRECEDING AND CURRENT ROW specifies all rows within last week. Default (std): OVER (ORDER BY n) == OVER (ORDER BY n RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)

42 Determinacy SELECT name, department_id, salary, SUM(salary) OVER (PARTITION BY department_id ORDER BY name ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) sum FROM employee; In general, window queries are not deterministic unless one orders on enough expressions to designate the row uniquely. Minimum guarantee by SQL std: several equivalent non-deterministic orderings in same query give the same order (within query).

43 Determinacy SELECT name, department_id, salary, SUM(salary) OVER (PARTITION BY department_id ORDER BY name ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) sum FROM employee ORDER BY department_id, name; A final ORDER BY is still required if ordering is desired: no guarantees from window. In general, window queries are not deterministic unless one orders on enough expressions to designate the row uniquely. Minimum guarantee by SQL std: several equivalent non-deterministic orderings in same query give the same order (within query).

44 Example: salary analysis Question: find the employees with the largest difference between their wage and that of the department average SELECT name, department_id, salary, AVG(salary) OVER (PARTITION BY department_id) AS avg, salary - AVG(salary) OVER (PARTITION BY department_id) AS diff FROM employee ORDER BY diff desc; name department_id salary avg diff Rose Erik Nils Nils NULL Michael Lena Paula Frederik Jon William Dag 10 NULL NULL

45 Example: salary analysis Question: find the employees with the largest difference between their wage and that of the department average SELECT name, department_id, salary, AVG(salary) OVER (PARTITION BY department_id) AS avg, salary - AVG(salary) OVER (PARTITION BY department_id) AS diff FROM employee ORDER BY diff desc; Here: two distinct windows A query can use have any number of windows Logically evaluated in multiple phases

46 Example: named window Question: find the employees with the largest difference between their wage and that of the department average SELECT name, department_id, salary, AVG(salary) OVER w AS avg, salary - AVG(salary) OVER w AS diff FROM employee WINDOW w as (PARTITION BY department_id) ORDER BY diff desc; Named window w References to w Multiple window functions per window Will be evaluated in same phase (efficiency) Better readability

47 Ex: moving AVG, smoothing CREATE TABLE sales(id INT AUTO_INCREMENT PRIMARY KEY, date DATE, sale INT);...; SELECT * FROM sales; id date sale

48 Ex: moving AVG, smoothing Sum up sales per month SELECT MONTH(date), SUM(sale) FROM sales GROUP BY MONTH(date); MONTH(date) SUM(sale)

49 Ex: moving AVG, smoothing Moving AVG over 3 months SELECT MONTH(date), SUM(sale), AVG(SUM(sale)) OVER w AS sliding_avg FROM sales GROUP BY MONTH(date) WINDOW w AS (ORDER BY MONTH(date) RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING); MONTH(date) SUM(sale) sliding_avg

50 Ex: moving AVG, smoothing Moving AVG over 3 months SELECT MONTH(date), SUM(sale), AVG(SUM(sale)) OVER w AS sliding_avg FROM sales GROUP BY MONTH(date) WINDOW w AS (ORDER BY MONTH(date) RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING); MONTH(date) SUM(sale) sliding_avg

51 Ex: moving AVG, smoothing Moving AVG over 3 months SELECT MONTH(date), SUM(sale), AVG(SUM(sale)) OVER w AS sliding_avg FROM sales GROUP BY MONTH(date) WINDOW w AS (ORDER BY MONTH(date) RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING); MONTH(date) SUM(sale) sliding_avg moving frame

52 Ex: moving AVG, smoothing Moving AVG over 3 months SELECT MONTH(date), SUM(sale), AVG(SUM(sale)) OVER w AS sliding_avg FROM sales GROUP BY MONTH(date) WINDOW w AS (ORDER BY MONTH(date) RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING); MONTH(date) SUM(sale) sliding_avg

53 Ex: moving AVG, smoothing Moving AVG over 3 months SELECT MONTH(date), SUM(sale), AVG(SUM(sale)) OVER w AS sliding_avg FROM sales GROUP BY MONTH(date) WINDOW w AS (ORDER BY MONTH(date) RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING); MONTH(date) SUM(sale) sliding_avg

54 Ex: moving AVG, smoothing Moving AVG over 3 months SELECT MONTH(date), SUM(sale), AVG(SUM(sale)) OVER w AS sliding_avg FROM sales GROUP BY MONTH(date) WINDOW w AS (ORDER BY MONTH(date) RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING); MONTH(date) SUM(sale) sliding_avg

55 Ex: moving AVG, smoothing Moving AVG over 3 months SELECT MONTH(date), SUM(sale), AVG(SUM(sale)) OVER w AS sliding_avg FROM sales GROUP BY MONTH(date) WINDOW w AS (ORDER BY MONTH(date) RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING); MONTH(date) SUM(sale) sliding_avg

56 Windowing in an SQL query JOIN GROUP BY, HAVING WINDOW 1 WINDOW n ORDER BY/ DISTINCT/ LIMIT Window functions see query result set after grouping/having - filtering on wf results requires subquery Ordering not semantically significant Window functions can't use window functions in same query (without using subqueries) In practice, ordering matters. The optimizer can is allowed to - reorder to minimize sorting required - merge window phases if equivalent

57 Program Agenda Introduction: what & why What's supported Ranking and analytical wfs Implementation & performance

58 PART II in which we learn which window functions are supported by MySQL

59 MySQL 8.0 Most aggregate functions in MySQL can be used as window functions: COUNT, SUM, AVG, MAX, MIN, STDDEV_POP (& synonyms), STDDEV_SAMP, VAR_POP (& synonym), VAR_SAMP Limitation: No DISTINCT in aggregates yet All SQL standard specialized window functions ROW_NUMBER, RANK, DENSE_RANK, PERCENT_RANK, CUME_DIST, NTILE, LEAD, LAG, FIRST_VALUE, LAST_VALUE, NTH_VALUE Next phase (probably post-ga), more aggregates: BIT_OR, BIT_XOR, BIT_AND, JSON_ARRAYAGG, JSON_OBJECTAGG [ GROUP_CONCAT ]

60 Std compliance: extensions Target SQL standard semantics, but Expression (not only column) allowed in PARTITION BY Benefit: more flexible Missing ORDER BY tolerated even if useless (all rows are peers) except for RANGE <value>: requires single ORDER BY expression Tolerate frame clause even for window functions that operate on entire partition (std is stricter) Benefit: Many wfs can use same window definition

61 Std compliance: restrictions Target SQL standard semantics, but Valued frame bounds must be static in query No GROUPS in frame clause (Feature T620) No EXCLUDE in frame clause No DISTINCT in aggregates with windowing IGNORE NULLS not supported FROM LAST not supported (NTH_VALUE) No nested window functions (Feature T619) No row pattern recognition in window clause (Feature R020) Operator subqueries with windowing only if materializable (WL#10431)

62 Program Agenda Introduction: what & why What's supported Ranking and analytical wfs Implementation & performance

63 PART III in which we learn about the specialized window functions Ranking: ROW_NUMBER, RANK, DENSE_RANK, PERCENT_RANK, CUME_DIST, NTILE Analytical: LEAD, LAG, NTH_VALUE, FIRST_VALUE, LAST_VALUE Blue ones use frames, the others work on the entire partition.

64 ROW_NUMBER Assign number to row in ascending order Example: give employees a number according to their salary SELECT name, department_id AS dept, salary, ROW_NUMBER() OVER w AS `row#` FROM employee WINDOW w AS (PARTITION BY department_id ORDER BY salary DESC, name ASC) ORDER BY department_id, `row#`; name dept salary row# Nils NULL Erik Michael Frederik Jon Dag 10 NULL 5 Nils Lena Paula Rose William

65 RANK Rows that are the same w.r.t any ordering have the same rank Example: rank employees within each department according to their salary SELECT name, department_id AS dept, salary,.., RANK() OVER w AS `rank` FROM employee WINDOW w AS (PARTITION BY department_id ORDER BY salary DESC) ORDER BY department_id, `row#`; name dept salary row# rank Nils NULL Erik Michael Frederik Jon Dag 10 NULL 5 5 Nils Lena Paula Rose William Peer rows w.r.t ordering, skip rank 4.

66 DENSE_RANK Rows that are the same wrt any ordering have the same rank Example: rank employees within each department according to their salary SELECT name, department_id AS dept, salary,.., DENSE_RANK() OVER w AS dense FROM employee WINDOW w AS (PARTITION BY department_id ORDER BY salary DESC) ORDER BY department_id, `row#`; name dept salary row# rank dense Nils NULL Erik Michael Frederik Jon Dag 10 NULL Nils Lena Paula Rose William Peer rows w.r.t ordering, do not skip rank 4.

67 PERCENT_RANK Relative rank: (rank - 1) / (total p.rows - 1), or 0 if one row in partition Example: rank employees within each department according to their salary SELECT name, department_id AS dept, salary,.., PERCENT_RANK() OVER w AS `%rank` FROM employee WINDOW w AS (PARTITION BY department_id ORDER BY salary DESC) ORDER BY department_id, `row#`; name dept salary row# rank dense %rank Nils NULL Erik Michael Frederik Jon Dag 10 NULL Nils Lena Paula Rose William (3-1)/(5-1)=0.5

68 CUME_DIST Cumulative relative rank: preceding rows incl. peers / total p.rows Example: cumulative rank of employees within each department according to their salary SELECT name, department_id AS dept, salary,.., CUME_DIST() OVER w AS cume FROM employee WINDOW w AS (PARTITION BY department_id ORDER BY salary DESC) ORDER BY department_id, `row#`; name dept salary row# rank dense %rank cume Nils NULL Erik Michael Frederik Jon Dag 10 NULL Nils Lena Paula Rose William /5=0.8

69 NTILE Divides an ordered partition into a specified number of groups aka buckets as evenly as possible and assigns a bucket number to each row in the partition. In spite of name, not the same as percentile! SELECT name, department_id AS dept, salary,.., NTILE(3) OVER w AS `3-tile` FROM employee WINDOW w AS (PARTITION BY department_id ORDER BY salary DESC) ORDER BY department_id, `row#`; name dept salary row# rank dense %rank cume 3-tile Nils NULL Erik Michael Frederik Jon Dag 10 NULL Nils Lena Paula Rose William

70 LEAD, LAG Returns value evaluated at the row that is offset rows after/before the current row within the partition; if there is no such row, instead return an optional default expression (which must be of the same type as value). Both offset and default expr are evaluated with respect to the current row. If omitted, offset defaults to 1 and default expr to null Syntax: LEAD( <expr> [, <offset> [, <default expr> ] ] ) [ <RESPECT NULLS> ] Example: LEAD(date) OVER (..) Note: IGNORE NULLS not supported, RESPECT NULLS is default but can be specified. Any window frame is ignored

71 LEAD SELECT name, department_id AS dept, salary, LEAD(salary, 1) OVER w AS `lead` FROM employee WINDOW w AS (ORDER BY salary DESC); name dept salary lead Rose Erik Nils Nils NULL Michael William : Lena Paula Frederik Jon Dag 10 NULL

72 LEAD SELECT name, department_id AS dept, salary, LEAD(salary, 1) OVER w AS `lead` FROM employee WINDOW w AS (ORDER BY salary DESC); name dept salary lead Rose Erik Nils Nils NULL Michael William Lena Paula Frederik Jon Dag 10 NULL

73 LEAD SELECT name, department_id AS dept, salary, LEAD(salary, 1) OVER w AS `lead` FROM employee WINDOW w AS (ORDER BY salary DESC); name dept salary lead Rose Erik Nils Nils NULL Michael William Lena Paula Frederik Jon Dag 10 NULL

74 LEAD SELECT name, department_id AS dept, salary, LEAD(salary, 1) OVER w AS `lead` FROM employee WINDOW w AS (ORDER BY salary DESC); name dept salary lead Rose Erik Nils Nils NULL Michael William Lena Paula Frederik Jon NULL Dag 10 NULL NULL

75 LEAD SELECT name, department_id AS dept, salary, LEAD(salary, 1, 77000) OVER w AS `lead` FROM employee WINDOW w AS (ORDER BY salary DESC); name dept salary lead Rose Erik Nils Nils NULL Michael William Lena Paula Frederik Jon NULL Dag 10 NULL default

76 LEAD - gap detection Classic example: CREATE TABLE t(i INT); INSERT INTO t VALUES (1), (2), (4), (5), (6), (8), (9), (10); SELECT i, l FROM (SELECT i, LEAD(i) OVER (ORDER BY i) AS l FROM t) d WHERE i + 1 <> l; i l

77 FIRST_VALUE, LAST_VALUE Returns value evaluated at the first, last in the frame of the current row within the partition; if there is no nth row (frame is too small), the NTH_VALUE returns NULL. Note: IGNORE NULLS is not supported, RESPECT NULLS is default but can be specified.

78 FIRST_VALUE Difference between employee wages and best paid in department SELECT name, department_id AS dept, salary, FIRST_VALUE(salary) OVER w - salary AS diff FROM employee WINDOW w AS (PARTITION BY department_id ORDER BY salary DESC) name dept salary diff Nils NULL Erik Michael Frederik Jon Dag 10 NULL NULL Nils Lena Paula Rose William

79 NTH_VALUE Returns value evaluated at the nth in the frame of the current row within the partition; if there is no nth row (frame is too small), the NTH_VALUE returns NULL. Note: IGNORE NULLS is not supported, RESPECT NULLS is used but can be specified. Note: For NTH_VALUE, FROM LAST is not supported, FROM FIRST is used but can be specified

80 Program Agenda Introduction: what & why What's supported Ranking and analytical wfs Implementation & performance

81 PART IV is where we look at implementation and performance aspects

82 Windowing in an SQL query JOIN GROUP BY, HAVING WINDOW 1 WINDOW n ORDER BY/ DISTINCT/ LIMIT Window functions see query result set after grouping/having - filtering on wf results requires subquery Ordering not semantically significant Window functions can't use window functions in same query (without using subqueries) In practice, ordering matters. The optimizer is allowed to - reorder to minimize sorting required - merge window phases if equivalent

83 Processing window functions JOIN GROUP BY WINDOW 1 WINDOW n ORDER BY/ DISTINCT/ LIMIT Sort by concatenation of PARTITION BY and ORDER BY Tmp table between each windowing step Optimization: re-order windows to eliminate sorting steps: when equal PARTITION BY/ORDER BY expressions SELECT name, SUM(salary) OVER () FROM employee LIMIT name SUM(salary) OVER () Dag Erik Frederik Need to read all rows to get SUM before we can output row 1: need buffering to merge original row with result of window function

84 Processing window functions JOIN GROUP BY WINDOW 1 WINDOW n ORDER BY/ DISTINCT/ LIMIT Row addressable buffer aka frame buffer in-memory tmp table; overflows automatically to disk if needed Permits re-reading rows when frame moves

85 Streaming window functions Frame buffer not needed for streaming window functions: ROW_NUMBER, RANK, DENSE_RANK Aggregates with ROW frame and dynamically growing upper bound, e.g. SELECT SUM(salary) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) FROM employee; Non-streaming (need buffer), e.g. CUME_DIST, SUM() OVER () Row addressable buffer aka frame buffer => a function on what window function and which frame specification If in doubt, check with EXPLAIN FORMAT=JSON

86 EXPLAIN: streaming EXPLAIN format=json SELECT SUM(salary) OVER (ROWS UNBOUNDED PRECEDING) FROM employee; "query_block": { "select_id": 1, "cost_info": { "query_cost": "1.35" }, "windowing": { "windows": [ { "name": "<unnamed window>", "functions": [ "sum" ] } ], "table": { "table_name": "employee", "access_type": "ALL", "rows_examined_per_scan": 11, "rows_produced_per_join": 11, "filtered": "100.00", "cost_info": { "read_cost": "0.25", "eval_cost": "1.10", "prefix_cost": "1.35", "data_read_per_join": "1K" }, "used_columns": [ "salary" ] } } } }

87 EXPLAIN: frame buffer EXPLAIN format=json SELECT COUNT(salary) OVER () FROM employee; "query_block": { "select_id": 1, "cost_info": { "query_cost": "1.35" }, "windowing": { "windows": [ { "name": "<unnamed window>", "frame_buffer": { "using_temporary_table": true, "optimized_frame_evaluation": true }, "functions": [ "count" ] } ], "table": { "table_name": "employee", "access_type": "ALL", "rows_examined_per_scan": 11, "rows_produced_per_join": 11, "filtered": "100.00", "cost_info": { "read_cost": "0.25", "eval_cost": "1.10", "prefix_cost": "1.35", "data_read_per_join": "1K" }, "used_columns": [ "salary" ] } } }

88 Frame buffer processing JOIN GROUP BY WINDOW 1 WINDOW n ORDER BY/ DISTINCT/ LIMIT Row addressable buffer aka frame buffer in-memory; overflows automatically to disk if needed Permits re-reading rows when frame moves SELECT name, SUM(salary) OVER () FROM employee LIMIT name SUM(salary) OVER () Dag Erik Frederik Optimization 1: Compute SUM only once (static frame) But what if frame changes?

89 Frame buffer processing Case: expanding frame SELECT name, salary, SUM(salary) OVER (ORDER BY name) AS `sum` FROM employee LIMIT name salary sum Dag NULL NULL Erik Frederik Optimization 2: Remember SUM and adjust: here add next row's contribution: (NULL+100k)+60k=160k But what if we have a moving frame?

90 Inversion Case: moving frame: Sales over this month and last SELECT MONTH(date) AS month, SUM(sale) AS monthly, SUM(SUM(sale)) OVER (ORDER BY MONTH(date) RANGE 1 PRECEDING) AS `this&last` FROM sales GROUP BY MONTH(date); month monthly this&last Optimization 3: Remember SUM and adjust: here remove last contribution from 2 PRECEDING, then add current row's contribution: inversion NOTE: Ok only if: a + b - a + c = b + c This isn't always the case for aggregates Penalty if we can't do this for large window frames: O(#partition size) vs. O(#partition size * #frame size)

91 Conditional inversion When: a + b - a + c b + c Floating aggregates, standard deviation and variance aggregates mysql> show variables like '%high%'; Variable_name Value windowing_use_high_precision ON recomputes: slow, but guaranteed same results as grouped aggregates SET windowing_use_high_precision= off; linear performance For variance, the differences are only in the last significant few digits to the the incremental algorithm yielding slightly different results (usually insignificant) For floats, this can matter of if summing very large and small numbers: mysql> select E E+307; E E

92 Performance hints Use named windows to eliminate several windowing steps whenever possible Possibility: analyze and collapse windows where semantics allow it. We might want to add this capability to the optimizer if large demand. Streaming window functions faster than those that need buffering MAX/MIN do not support inversion, so can slow with large frames unless the expression is a prefix of the ORDER BY expressions JSON_OBJECTAGG is not invertible, so can slow with large frames

93 Q&A Thank you for using MySQL! Blog:

94 Safe Harbor Statement The preceding is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle s products remains at the sole discretion of Oracle.

95

96

Chapter 6 Windowed Tables and Window Functions in SQL

Chapter 6 Windowed Tables and Window Functions in SQL Prof. Dr.-Ing. Stefan Deßloch AG Heterogene Informationssysteme Geb. 36, Raum 329 Tel. 0631/205 3275 dessloch@informatik.uni-kl.de Chapter 6 Windowed Tables and Window Functions in SQL Recent Developments

More information

Chapter 9 Windowed Tables and Window Functions in SQL. Recent Development for Data Models 2016 Stefan Deßloch

Chapter 9 Windowed Tables and Window Functions in SQL. Recent Development for Data Models 2016 Stefan Deßloch Chapter 9 Windowed Tables and Window Functions in SQL Recent Development for Data Models 2016 Stefan Deßloch Windowed Table Functions Windowed table function operates on a window of a table returns a value

More information

Chapter 6 Windowed Tables and Window Functions in SQL

Chapter 6 Windowed Tables and Window Functions in SQL Prof. Dr.-Ing. Stefan Deßloch AG Heterogene Informationssysteme Geb. 36, Raum 329 Tel. 0631/205 3275 dessloch@informatik.uni-kl.de Chapter 6 Windowed Tables and Window Functions in SQL Outline Overview

More information

Postgres Window Magic

Postgres Window Magic Postgres Window Magic BRUCE MOMJIAN This presentation explains the many window function facilities and how they can be used to produce useful SQL query results. Creative Commons Attribution License http://momjian.us/presentations

More information

Chapter 6 Windowed Tables and Window Functions in SQL

Chapter 6 Windowed Tables and Window Functions in SQL Prof. Dr.Ing. Stefan Deßloch AG Heterogene Informationssysteme Geb., Raum Tel. 0/0 dessloch@informatik.unikl.de Chapter Windowed Tables and Window Functions in SQL WS0/0 Outline Overview I. ObjectRelational

More information

MySQL 8.0 Common Table Expressions & Windowing Functions

MySQL 8.0 Common Table Expressions & Windowing Functions 1 / 66 2 / 66 MySQL 8.0 Common Table Expressions & Windowing Functions Dave Stokes - MySQL Community Manager - Oracle 3 / 66 Safe Harbor Statement The following is intended to outline our general product

More information

Greenplum SQL Class Outline

Greenplum SQL Class Outline Greenplum SQL Class Outline The Basics of Greenplum SQL Introduction SELECT * (All Columns) in a Table Fully Qualifying a Database, Schema and Table SELECT Specific Columns in a Table Commas in the Front

More information

Advanced Data Management Technologies

Advanced Data Management Technologies ADMT 2017/18 Unit 11 J. Gamper 1/48 Advanced Data Management Technologies Unit 11 SQL Analytic Functions J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE Acknowledgements: I

More information

20461: Querying Microsoft SQL Server 2014 Databases

20461: Querying Microsoft SQL Server 2014 Databases Course Outline 20461: Querying Microsoft SQL Server 2014 Databases Module 1: Introduction to Microsoft SQL Server 2014 This module introduces the SQL Server platform and major tools. It discusses editions,

More information

Still using. Windows 3.1? So why stick to -

Still using. Windows 3.1? So why stick to - Still using Windows 3.1? So why stick to SQL-92? @ModernSQL - http://modern-sql.com/ @MarkusWinand SQL:1999 LATERAL LATERAL Before SQL:1999 Derived tables (from clause subqueries) cannot see outside: SELECT

More information

SQL Server Windowing Functions

SQL Server Windowing Functions SQL Server Windowing Functions Enrique Catalá Bañuls Mentor, SolidQ MAP 2012 Microsoft Technical Ranger Microsoft Certified Trainer ecatala@solidq.com Twitter: @enriquecatala Enrique Catalá Bañuls Computer

More information

COURSE OUTLINE MOC 20461: QUERYING MICROSOFT SQL SERVER 2014

COURSE OUTLINE MOC 20461: QUERYING MICROSOFT SQL SERVER 2014 COURSE OUTLINE MOC 20461: QUERYING MICROSOFT SQL SERVER 2014 MODULE 1: INTRODUCTION TO MICROSOFT SQL SERVER 2014 This module introduces the SQL Server platform and major tools. It discusses editions, versions,

More information

Andrea Martorana Tusa. T-SQL Advanced: Grouping and Windowing

Andrea Martorana Tusa. T-SQL Advanced: Grouping and Windowing Andrea Martorana Tusa T-SQL Advanced: Grouping and Windowing Sponsor Organizzatori GetLatestVersion. it Speaker info First name: Andrea. Last name: Martorana Tusa. Italian, working by Widex a danish company

More information

SQL Saturday Cork Welcome to Cork. Andrea Martorana Tusa T-SQL advanced: Grouping and Windowing

SQL Saturday Cork Welcome to Cork. Andrea Martorana Tusa T-SQL advanced: Grouping and Windowing SQL Saturday Cork Welcome to Cork Andrea Martorana Tusa T-SQL advanced: Grouping and Windowing Andrea Martorana Tusa T-SQL Advanced: Grouping and Windowing Speaker info First name: Andrea. Last name: Martorana

More information

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables INDEX Exercise No Title 1 Basic SQL Statements 2 Restricting and Sorting Data 3 Single Row Functions 4 Displaying data from multiple tables 5 Creating and Managing Tables 6 Including Constraints 7 Manipulating

More information

PostgreSQL to MySQL A DBA's Perspective. Patrick

PostgreSQL to MySQL A DBA's Perspective. Patrick PostgreSQL to MySQL A DBA's Perspective Patrick King @mr_mustash Yelp s Mission Connecting people with great local businesses. My Database Experience Started using Postgres 7 years ago Postgres 8.4 (released

More information

Aster Data Basics Class Outline

Aster Data Basics Class Outline Aster Data Basics Class Outline CoffingDW education has been customized for every customer for the past 20 years. Our classes can be taught either on site or remotely via the internet. Education Contact:

More information

Aster Data SQL and MapReduce Class Outline

Aster Data SQL and MapReduce Class Outline Aster Data SQL and MapReduce Class Outline CoffingDW education has been customized for every customer for the past 20 years. Our classes can be taught either on site or remotely via the internet. Education

More information

What Are Group Functions? Reporting Aggregated Data Using the Group Functions. Objectives. Types of Group Functions

What Are Group Functions? Reporting Aggregated Data Using the Group Functions. Objectives. Types of Group Functions What Are Group Functions? Group functions operate on sets of rows to give one result per group. Reporting Aggregated Data Using the Group Functions Maximum salary in table Copyright 2004, Oracle. All rights

More information

20461: Querying Microsoft SQL Server

20461: Querying Microsoft SQL Server 20461: Querying Microsoft SQL Server Length: 5 days Audience: IT Professionals Level: 300 OVERVIEW This 5 day instructor led course provides students with the technical skills required to write basic Transact

More information

Querying Microsoft SQL Server

Querying Microsoft SQL Server Course Code: M20461 Vendor: Microsoft Course Overview Duration: 5 RRP: POA Querying Microsoft SQL Server Overview This 5-day instructor led course provides delegates with the technical skills required

More information

Optimizing Queries with EXPLAIN

Optimizing Queries with EXPLAIN Optimizing Queries with EXPLAIN Sheeri Cabral Senior Database Administrator Twitter: @sheeri What is EXPLAIN? SQL Extension Just put it at the beginning of your statement Can also use DESC or DESCRIBE

More information

After completing this course, participants will be able to:

After completing this course, participants will be able to: Querying SQL Server T h i s f i v e - d a y i n s t r u c t o r - l e d c o u r s e p r o v i d e s p a r t i c i p a n t s w i t h t h e t e c h n i c a l s k i l l s r e q u i r e d t o w r i t e b a

More information

Querying Microsoft SQL Server

Querying Microsoft SQL Server Querying Microsoft SQL Server 20461D; 5 days, Instructor-led Course Description This 5-day instructor led course provides students with the technical skills required to write basic Transact SQL queries

More information

AVANTUS TRAINING PTE LTD

AVANTUS TRAINING PTE LTD [MS20461]: Querying Microsoft SQL Server 2014 Length : 5 Days Audience(s) : IT Professionals Level : 300 Technology : SQL Server Delivery Method : Instructor-led (Classroom) Course Overview This 5-day

More information

SQL Data Query Language

SQL Data Query Language SQL Data Query Language André Restivo 1 / 68 Index Introduction Selecting Data Choosing Columns Filtering Rows Set Operators Joining Tables Aggregating Data Sorting Rows Limiting Data Text Operators Nested

More information

Querying Microsoft SQL Server (MOC 20461C)

Querying Microsoft SQL Server (MOC 20461C) Querying Microsoft SQL Server 2012-2014 (MOC 20461C) Course 21461 40 Hours This 5-day instructor led course provides students with the technical skills required to write basic Transact-SQL queries for

More information

Modern SQL: Evolution of a dinosaur

Modern SQL: Evolution of a dinosaur Modern SQL: Evolution of a dinosaur Markus Winand Kraków, 9-11 May 2018 Still using Windows 3.1? So why stick with SQL-92? @ModernSQL - https://modern-sql.com/ @MarkusWinand SQL:1999 WITH (Common Table

More information

DB2 SQL Class Outline

DB2 SQL Class Outline DB2 SQL Class Outline The Basics of SQL Introduction Finding Your Current Schema Setting Your Default SCHEMA SELECT * (All Columns) in a Table SELECT Specific Columns in a Table Commas in the Front or

More information

Querying Microsoft SQL Server 2008/2012

Querying Microsoft SQL Server 2008/2012 Querying Microsoft SQL Server 2008/2012 Course 10774A 5 Days Instructor-led, Hands-on Introduction This 5-day instructor led course provides students with the technical skills required to write basic Transact-SQL

More information

MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9)

MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9) Technology & Information Management Instructor: Michael Kremer, Ph.D. Class 6 Professional Program: Data Administration and Management MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9) AGENDA

More information

Querying Microsoft SQL Server

Querying Microsoft SQL Server Querying Microsoft SQL Server Duration: 5 Days (08:30-16:00) Overview: This course provides students with the technical skills required to write basic Transact-SQL queries for Microsoft SQL Server. This

More information

Querying Microsoft SQL Server

Querying Microsoft SQL Server Querying Microsoft SQL Server Course 20461D 5 Days Instructor-led, Hands-on Course Description This 5-day instructor led course is designed for customers who are interested in learning SQL Server 2012,

More information

QUERYING MICROSOFT SQL SERVER COURSE OUTLINE. Course: 20461C; Duration: 5 Days; Instructor-led

QUERYING MICROSOFT SQL SERVER COURSE OUTLINE. Course: 20461C; Duration: 5 Days; Instructor-led CENTER OF KNOWLEDGE, PATH TO SUCCESS Website: QUERYING MICROSOFT SQL SERVER Course: 20461C; Duration: 5 Days; Instructor-led WHAT YOU WILL LEARN This 5-day instructor led course provides students with

More information

COURSE OUTLINE: Querying Microsoft SQL Server

COURSE OUTLINE: Querying Microsoft SQL Server Course Name 20461 Querying Microsoft SQL Server Course Duration 5 Days Course Structure Instructor-Led (Classroom) Course Overview This 5-day instructor led course provides students with the technical

More information

Database Management Systems,

Database Management Systems, Database Management Systems SQL Query Language (3) 1 Topics Aggregate Functions in Queries count sum max min avg Group by queries Set Operations in SQL Queries Views 2 Aggregate Functions Tables are collections

More information

Querying Microsoft SQL Server

Querying Microsoft SQL Server 20461 - Querying Microsoft SQL Server Duration: 5 Days Course Price: $2,975 Software Assurance Eligible Course Description About this course This 5-day instructor led course provides students with the

More information

Aggregate Functions. Eng. Mohammed Alokshiya. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Dept. Database Lab (ECOM 4113)

Aggregate Functions. Eng. Mohammed Alokshiya. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Dept. Database Lab (ECOM 4113) Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Database Lab (ECOM 4113) Lab 4 Aggregate Functions Eng. Mohammed Alokshiya October 26, 2014 Unlike single-row functions, group

More information

MySQL 8.0 What s New in the Optimizer

MySQL 8.0 What s New in the Optimizer MySQL 8.0 What s New in the Optimizer Manyi Lu Director MySQL Optimizer & GIS Team, Oracle October 2016 Copyright Copyright 2 015, 2016,Oracle Oracle and/or and/or its its affiliates. affiliates. All All

More information

Course 20461C: Querying Microsoft SQL Server

Course 20461C: Querying Microsoft SQL Server Course 20461C: Querying Microsoft SQL Server Audience Profile About this Course This course is the foundation for all SQL Serverrelated disciplines; namely, Database Administration, Database Development

More information

Data Warehousing and Data Mining OLAP Operations

Data Warehousing and Data Mining OLAP Operations Data Warehousing and Data Mining OLAP Operations SQL table expression query specification query expression OLAP GROUP BY extensions: rollup, cube, grouping sets SQL for analysis and reporting: ranking,

More information

"Charting the Course to Your Success!" MOC D Querying Microsoft SQL Server Course Summary

Charting the Course to Your Success! MOC D Querying Microsoft SQL Server Course Summary Course Summary Description This 5-day instructor led course provides students with the technical skills required to write basic Transact-SQL queries for Microsoft SQL Server 2014. This course is the foundation

More information

Querying Microsoft SQL Server 2012/2014

Querying Microsoft SQL Server 2012/2014 Page 1 of 14 Overview This 5-day instructor led course provides students with the technical skills required to write basic Transact-SQL queries for Microsoft SQL Server 2014. This course is the foundation

More information

Subquery: There are basically three types of subqueries are:

Subquery: There are basically three types of subqueries are: Subquery: It is also known as Nested query. Sub queries are queries nested inside other queries, marked off with parentheses, and sometimes referred to as "inner" queries within "outer" queries. Subquery

More information

Analytic SQL Features in Oracle9i. An Oracle Technical White Paper December 2001

Analytic SQL Features in Oracle9i. An Oracle Technical White Paper December 2001 Analytic SQL Features in Oracle9i An Oracle Technical White Paper December 2001 Analytic SQL Features in Oracle9i Introduction... 3 Analytic Functions... 4 Analytic Functions Family List... 4 Inverse Percentile

More information

20461D: Querying Microsoft SQL Server

20461D: Querying Microsoft SQL Server 20461D: Querying Microsoft SQL Server Course Details Course Code: Duration: Notes: 20461D 5 days This course syllabus should be used to determine whether the course is appropriate for the students, based

More information

FUN WITH ANALYTIC FUNCTIONS UTOUG TRAINING DAYS 2017

FUN WITH ANALYTIC FUNCTIONS UTOUG TRAINING DAYS 2017 FUN WITH ANALYTIC FUNCTIONS UTOUG TRAINING DAYS 2017 ABOUT ME Born and raised here in UT In IT for 10 years, DBA for the last 6 Databases and Data are my hobbies, I m rather quite boring This isn t why

More information

Microsoft Querying Microsoft SQL Server 2014

Microsoft Querying Microsoft SQL Server 2014 1800 ULEARN (853 276) www.ddls.com.au Microsoft 20461 - Querying Microsoft SQL Server 2014 Length 5 days Price $4290.00 (inc GST) Version D Overview Please note: Microsoft have released a new course which

More information

Reporting Aggregated Data Using the Group Functions. Copyright 2004, Oracle. All rights reserved.

Reporting Aggregated Data Using the Group Functions. Copyright 2004, Oracle. All rights reserved. Reporting Aggregated Data Using the Group Functions Copyright 2004, Oracle. All rights reserved. Objectives After completing this lesson, you should be able to do the following: Identify the available

More information

Querying Microsoft SQL Server 2014

Querying Microsoft SQL Server 2014 Querying Microsoft SQL Server 2014 Código del curso: 20461 Duración: 5 días Acerca de este curso This 5 day instructor led course provides students with the technical skills required to write basic Transact

More information

Why Relational Databases? Relational databases allow for the storage and analysis of large amounts of data.

Why Relational Databases? Relational databases allow for the storage and analysis of large amounts of data. DATA 301 Introduction to Data Analytics Relational Databases Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca DATA 301: Data Analytics (2) Why Relational Databases? Relational

More information

Introduction to Query Processing and Query Optimization Techniques. Copyright 2011 Ramez Elmasri and Shamkant Navathe

Introduction to Query Processing and Query Optimization Techniques. Copyright 2011 Ramez Elmasri and Shamkant Navathe Introduction to Query Processing and Query Optimization Techniques Outline Translating SQL Queries into Relational Algebra Algorithms for External Sorting Algorithms for SELECT and JOIN Operations Algorithms

More information

When and How to Take Advantage of New Optimizer Features in MySQL 5.6. Øystein Grøvlen Senior Principal Software Engineer, MySQL Oracle

When and How to Take Advantage of New Optimizer Features in MySQL 5.6. Øystein Grøvlen Senior Principal Software Engineer, MySQL Oracle When and How to Take Advantage of New Optimizer Features in MySQL 5.6 Øystein Grøvlen Senior Principal Software Engineer, MySQL Oracle Program Agenda Improvements for disk-bound queries Subquery improvements

More information

ASSIGNMENT NO Computer System with Open Source Operating System. 2. Mysql

ASSIGNMENT NO Computer System with Open Source Operating System. 2. Mysql ASSIGNMENT NO. 3 Title: Design at least 10 SQL queries for suitable database application using SQL DML statements: Insert, Select, Update, Delete with operators, functions, and set operator. Requirements:

More information

CSC Web Programming. Introduction to SQL

CSC Web Programming. Introduction to SQL CSC 242 - Web Programming Introduction to SQL SQL Statements Data Definition Language CREATE ALTER DROP Data Manipulation Language INSERT UPDATE DELETE Data Query Language SELECT SQL statements end with

More information

Based on the following Table(s), Write down the queries as indicated: 1. Write an SQL query to insert a new row in table Dept with values: 4, Prog, MO

Based on the following Table(s), Write down the queries as indicated: 1. Write an SQL query to insert a new row in table Dept with values: 4, Prog, MO Based on the following Table(s), Write down the queries as indicated: 1. Write an SQL query to insert a new row in table Dept with values: 4, Prog, MO INSERT INTO DEPT VALUES(4, 'Prog','MO'); The result

More information

MIS NETWORK ADMINISTRATOR PROGRAM

MIS NETWORK ADMINISTRATOR PROGRAM NH107-7475 SQL: Querying and Administering SQL Server 2012-2014 136 Total Hours 97 Theory Hours 39 Lab Hours COURSE TITLE: SQL: Querying and Administering SQL Server 2012-2014 PREREQUISITE: Before attending

More information

Slicing and Dicing Data in CF and SQL: Part 1

Slicing and Dicing Data in CF and SQL: Part 1 Slicing and Dicing Data in CF and SQL: Part 1 Charlie Arehart Founder/CTO Systemanage carehart@systemanage.com SysteManage: Agenda Slicing and Dicing Data in Many Ways Handling Distinct Column Values Manipulating

More information

More SQL in MySQL 8.0

More SQL in MySQL 8.0 More SQL in MySQL 8.0 Norvald H. Ryeng Sofware Development Senior Manager MySQL Optmizer Team November, 08 Program Agenda 3 4 Common table expressions (CTEs) Window functons JSON_TABLE Demo 5 6 7 3 Theory

More information

Data warehousing in Oracle

Data warehousing in Oracle Data warehousing in Oracle Materialized views and SQL extensions to analyze data in Oracle data warehouses SQL extensions for data warehouse analysis 1 Available OLAP functions Computation windows window

More information

Analytic Functions in Oracle 8i

Analytic Functions in Oracle 8i Analytic Functions in Oracle 8i Srikanth Bellamkonda, Tolga Bozkaya, Bhaskar Ghosh Abhinav Gupta, John Haydu, Sankar Subramanian, Andrew Witkowski Oracle Corporation, 500 Oracle Parkway 4op7,Redwood Shores,

More information

KORA. RDBMS Concepts II

KORA. RDBMS Concepts II RDBMS Concepts II Outline Querying Data Source With SQL Star & Snowflake Schemas Reporting Aggregated Data Using the Group Functions What Are Group Functions? Group functions operate on sets of rows to

More information

Oracle Database 11g: SQL and PL/SQL Fundamentals

Oracle Database 11g: SQL and PL/SQL Fundamentals Oracle University Contact Us: +33 (0) 1 57 60 20 81 Oracle Database 11g: SQL and PL/SQL Fundamentals Duration: 5 Days What you will learn In this course, students learn the fundamentals of SQL and PL/SQL

More information

Chapter 3: Introduction to SQL

Chapter 3: Introduction to SQL Chapter 3: Introduction to SQL Database System Concepts, 6 th Ed. See www.db-book.com for conditions on re-use Chapter 3: Introduction to SQL Overview of the SQL Query Language Data Definition Basic Query

More information

Oracle Syllabus Course code-r10605 SQL

Oracle Syllabus Course code-r10605 SQL Oracle Syllabus Course code-r10605 SQL Writing Basic SQL SELECT Statements Basic SELECT Statement Selecting All Columns Selecting Specific Columns Writing SQL Statements Column Heading Defaults Arithmetic

More information

Database Lab Queries. Fall Term 2017 Dr. Andreas Geppert

Database Lab Queries. Fall Term 2017 Dr. Andreas Geppert Database Lab Queries Fall Term 2017 Dr. Andreas Geppert geppert@acm.org Topics conceptual design logical design consistency constraints data manipulation queries transactions views stored procedures and

More information

Intermediate SQL: Aggregated Data, Joins and Set Operators

Intermediate SQL: Aggregated Data, Joins and Set Operators Intermediate SQL: Aggregated Data, Joins and Set Operators Aggregated Data and Sorting Objectives After completing this lesson, you should be able to do the following: Identify the available group functions

More information

1 Writing Basic SQL SELECT Statements 2 Restricting and Sorting Data

1 Writing Basic SQL SELECT Statements 2 Restricting and Sorting Data 1 Writing Basic SQL SELECT Statements Objectives 1-2 Capabilities of SQL SELECT Statements 1-3 Basic SELECT Statement 1-4 Selecting All Columns 1-5 Selecting Specific Columns 1-6 Writing SQL Statements

More information

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL)

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management Tenth Edition Chapter 7 Introduction to Structured Query Language (SQL) Objectives In this chapter, students will learn: The basic commands and

More information

Algorithms for Query Processing and Optimization. 0. Introduction to Query Processing (1)

Algorithms for Query Processing and Optimization. 0. Introduction to Query Processing (1) Chapter 19 Algorithms for Query Processing and Optimization 0. Introduction to Query Processing (1) Query optimization: The process of choosing a suitable execution strategy for processing a query. Two

More information

SQL Queries. COSC 304 Introduction to Database Systems SQL. Example Relations. SQL and Relational Algebra. Example Relation Instances

SQL Queries. COSC 304 Introduction to Database Systems SQL. Example Relations. SQL and Relational Algebra. Example Relation Instances COSC 304 Introduction to Database Systems SQL Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca SQL Queries Querying with SQL is performed using a SELECT statement. The general

More information

Chapter 3: Introduction to SQL

Chapter 3: Introduction to SQL Chapter 3: Introduction to SQL Database System Concepts, 6 th Ed. See www.db-book.com for conditions on re-use Chapter 3: Introduction to SQL Overview of the SQL Query Language Data Definition Basic Query

More information

GIFT Department of Computing Science. CS-217: Database Systems. Lab-4 Manual. Reporting Aggregated Data using Group Functions

GIFT Department of Computing Science. CS-217: Database Systems. Lab-4 Manual. Reporting Aggregated Data using Group Functions GIFT Department of Computing Science CS-217: Database Systems Lab-4 Manual Reporting Aggregated Data using Group Functions V3.0 4/28/2016 Introduction to Lab-4 This lab further addresses functions. It

More information

Aster Data Database Administration Class Outline

Aster Data Database Administration Class Outline Aster Data Database Administration Class Outline CoffingDW education has been customized for every customer for the past 20 years. Our classes can be taught either on site or remotely via the internet.

More information

SQL Recursion, Window Queries

SQL Recursion, Window Queries SQL Recursion, Window Queries PG 7.8; 3.5 & 9.21 Dr. Chris Mayfield Department of Computer Science James Madison University Mar 20, 2019 WITH clause Basic syntax: WITH R AS

More information

SQL functions fit into two broad categories: Data definition language Data manipulation language

SQL functions fit into two broad categories: Data definition language Data manipulation language Database Principles: Fundamentals of Design, Implementation, and Management Tenth Edition Chapter 7 Beginning Structured Query Language (SQL) MDM NUR RAZIA BINTI MOHD SURADI 019-3932846 razia@unisel.edu.my

More information

Optional SQL Feature Summary

Optional SQL Feature Summary Optional SQL Feature Summary The following table lists all optional features included in the SQL standard, from SQL- 2003 to SQL-2016. It also indicates which features that are currently supported by Mimer

More information

The SQL data-definition language (DDL) allows defining :

The SQL data-definition language (DDL) allows defining : Introduction to SQL Introduction to SQL Overview of the SQL Query Language Data Definition Basic Query Structure Additional Basic Operations Set Operations Null Values Aggregate Functions Nested Subqueries

More information

ISO/IEC JTC 1/SC 32 N 0426

ISO/IEC JTC 1/SC 32 N 0426 ISO/IEC JTC 1/SC 32 N 0426 Date: 2000-01-25 REPLACES: -- ISO/IEC JTC 1/SC 32 Data Management and Interchange Secretariat: United States of America (ANSI) Administered by Pacific Northwest National Laboratory

More information

Oracle Database: SQL and PL/SQL Fundamentals NEW

Oracle Database: SQL and PL/SQL Fundamentals NEW Oracle Database: SQL and PL/SQL Fundamentals NEW Duration: 5 Days What you will learn This Oracle Database: SQL and PL/SQL Fundamentals training delivers the fundamentals of SQL and PL/SQL along with the

More information

20761 Querying Data with Transact SQL

20761 Querying Data with Transact SQL Course Overview The main purpose of this course is to give students a good understanding of the Transact-SQL language which is used by all SQL Server-related disciplines; namely, Database Administration,

More information

T-SQL Training: T-SQL for SQL Server for Developers

T-SQL Training: T-SQL for SQL Server for Developers Duration: 3 days T-SQL Training Overview T-SQL for SQL Server for Developers training teaches developers all the Transact-SQL skills they need to develop queries and views, and manipulate data in a SQL

More information

Oracle Database: SQL and PL/SQL Fundamentals Ed 2

Oracle Database: SQL and PL/SQL Fundamentals Ed 2 Oracle University Contact Us: Local: 1800 103 4775 Intl: +91 80 67863102 Oracle Database: SQL and PL/SQL Fundamentals Ed 2 Duration: 5 Days What you will learn This Oracle Database: SQL and PL/SQL Fundamentals

More information

COSC 304 Introduction to Database Systems SQL. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 304 Introduction to Database Systems SQL. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 304 Introduction to Database Systems SQL Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca SQL Queries Querying with SQL is performed using a SELECT statement. The general

More information

SQL Data Querying and Views

SQL Data Querying and Views Course A7B36DBS: Database Systems Lecture 04: SQL Data Querying and Views Martin Svoboda Faculty of Electrical Engineering, Czech Technical University in Prague Outline SQL Data manipulation SELECT queries

More information

A Window into Your Data. Using SQL Window Functions

A Window into Your Data. Using SQL Window Functions A Window into Your Data Using SQL Window Functions Welcome to PASS SQL Saturday #435 Thank you Sponsors! o Please visit the sponsors during the vendor break from 2:45 3:15 and enter their end-of-day raffles

More information

Oracle Database SQL Basics

Oracle Database SQL Basics Oracle Database SQL Basics Kerepes Tamás, Webváltó Kft. tamas.kerepes@webvalto.hu 2015. február 26. Copyright 2004, Oracle. All rights reserved. SQL a history in brief The relational database stores data

More information

Querying Microsoft SQL Server 2014

Querying Microsoft SQL Server 2014 Querying Microsoft SQL Server 2014 Referencia MOC 20461 Duración (horas) 25 Última actualización 27 marzo 2018 Modalidades Presencial, a medida Examen 70-461 Introducción This 5-day instructor led course

More information

MySQL Query Tuning 101. Sveta Smirnova, Alexander Rubin April, 16, 2015

MySQL Query Tuning 101. Sveta Smirnova, Alexander Rubin April, 16, 2015 MySQL Query Tuning 101 Sveta Smirnova, Alexander Rubin April, 16, 2015 Agenda 2 Introduction: where to find slow queries Indexes: why and how do they work All about EXPLAIN More tools Where to find more

More information

Institute of Aga. Microsoft SQL Server LECTURER NIYAZ M. SALIH

Institute of Aga. Microsoft SQL Server LECTURER NIYAZ M. SALIH Institute of Aga 2018 Microsoft SQL Server LECTURER NIYAZ M. SALIH Database: A Database is a collection of related data organized in a way that data can be easily accessed, managed and updated. Any piece

More information

Querying Data with Transact SQL

Querying Data with Transact SQL Course 20761A: Querying Data with Transact SQL Course details Course Outline Module 1: Introduction to Microsoft SQL Server 2016 This module introduces SQL Server, the versions of SQL Server, including

More information

Chapter 3. Algorithms for Query Processing and Optimization

Chapter 3. Algorithms for Query Processing and Optimization Chapter 3 Algorithms for Query Processing and Optimization Chapter Outline 1. Introduction to Query Processing 2. Translating SQL Queries into Relational Algebra 3. Algorithms for External Sorting 4. Algorithms

More information

"Charting the Course... Oracle18c SQL (5 Day) Course Summary

Charting the Course... Oracle18c SQL (5 Day) Course Summary Course Summary Description This course provides a complete, hands-on introduction to SQL including the use of both SQL Developer and SQL*Plus. This coverage is appropriate for users of Oracle11g and higher.

More information

Institute of Aga. Network Database LECTURER NIYAZ M. SALIH

Institute of Aga. Network Database LECTURER NIYAZ M. SALIH 2017 Institute of Aga Network Database LECTURER NIYAZ M. SALIH Database: A Database is a collection of related data organized in a way that data can be easily accessed, managed and updated. Any piece of

More information

Informix OLAP and Advanced SQL Functions by Lester Knutsen

Informix OLAP and Advanced SQL Functions by Lester Knutsen Advanced DataTools Webcast Informix OLAP and Advanced SQL Functions by Lester Knutsen March 7, 2019 at 2:00pm EDT 1 Lester Knutsen Lester Knutsen is President of Advanced DataTools Corporation, and has

More information

Teradata SQL Class Outline

Teradata SQL Class Outline Teradata SQL Class Outline CoffingDW education has been customized for every customer for the past 20 years. Our classes can be taught either on site or remotely via the internet. Education Contact: Thomas

More information

Introduction to SQL Server 2005/2008 and Transact SQL

Introduction to SQL Server 2005/2008 and Transact SQL Introduction to SQL Server 2005/2008 and Transact SQL Week 2 TRANSACT SQL CRUD Create, Read, Update, and Delete Steve Stedman - Instructor Steve@SteveStedman.com Homework Review Review of homework from

More information

SQL: Data Querying. B0B36DBS, BD6B36DBS: Database Systems. h p://www.ksi.m.cuni.cz/~svoboda/courses/172-b0b36dbs/ Lecture 4

SQL: Data Querying. B0B36DBS, BD6B36DBS: Database Systems. h p://www.ksi.m.cuni.cz/~svoboda/courses/172-b0b36dbs/ Lecture 4 B0B36DBS, BD6B36DBS: Database Systems h p://www.ksi.m.cuni.cz/~svoboda/courses/172-b0b36dbs/ Lecture 4 SQL: Data Querying Mar n Svoboda mar n.svoboda@fel.cvut.cz 20. 3. 2018 Czech Technical University

More information

Data Warehousing and Decision Support. Introduction. Three Complementary Trends. [R&G] Chapter 23, Part A

Data Warehousing and Decision Support. Introduction. Three Complementary Trends. [R&G] Chapter 23, Part A Data Warehousing and Decision Support [R&G] Chapter 23, Part A CS 432 1 Introduction Increasingly, organizations are analyzing current and historical data to identify useful patterns and support business

More information

SIT772 Database and Information Retrieval WEEK 6. RELATIONAL ALGEBRAS. The foundation of good database design

SIT772 Database and Information Retrieval WEEK 6. RELATIONAL ALGEBRAS. The foundation of good database design SIT772 Database and Information Retrieval WEEK 6. RELATIONAL ALGEBRAS The foundation of good database design Outline 1. Relational Algebra 2. Join 3. Updating/ Copy Table or Parts of Rows 4. Views (Virtual

More information