SQL SQL Overview 1. SELECT-FROM-WHERE Blocks

Total Page:16

File Type:pdf, Size:1020Kb

SQL SQL Overview 1. SELECT-FROM-WHERE Blocks 229 SQL • After completing this chapter, you should be able to . write advanced SQL queries including, e.g., multiple tuple variables over different/the same relation, . use aggregation, grouping, UNION, . be comfortable with the various join variants, . evaluate the correctness and equivalence of SQL queries, This includes the sometimes tricky issues of (deciding the presence) duplicate result tuples. judge the portability of certain SQL constructs. 230 SQL Overview 1. SELECT-FROM-WHERE Blocks, Tuple Variables 2. Subqueries, Non-Monotonic Constructs 3. Aggregations I: Aggregation Functions 4. Aggregations II: GROUP BY, HAVING 5. UNION, Conditional Expressions 6. ORDER BY 7. SQL-92 Joins, Outer Join 231 Basic SQL Query Syntax Basic SQL query (extensions follow) SELECT A1, ... ,An FROM R1, ... ,Rm WHERE C • The FROM clause declares which table(s) are accessed in the query. • The WHERE clause specifies a condition for rows (or row combinations) in these tables that are considered in this query (absence of C is equivalent to C TRUE). ≡ • The SELECT clause specifies the attributes of the result tuples (* output all attributes occurring in R ,...,R ). ≡ 1 m 232 Example Database (again) STUDENTS RESULTS SID FIRST LAST EMAIL SID CAT ENO POINTS 101 Ann Smith ... 101 H 1 10 102 Michael Jones (null) 101 H 2 8 103 Richard Turner ... 101 M 1 12 104 Maria Brown ... 102 H 1 9 102 H 2 9 EXERCISES 102 M 1 10 CAT ENO TOPIC MAXPT 103 H 1 5 103 M 1 7 H 1 Rel.Alg. 10 H 2 SQL 10 M 1 SQL 14 233 Tuple Variables (1) • The FROM clause can be understood as declaring variables that range over tuples of a relation: SELECT E.ENO, E.TOPIC FROM EXERCISES E WHERE E.CAT = ’H’ . This may be executed as foreach E EXERCISES do ∈ if E.CAT = ’H’ then print E.ENO, E.TOPIC fi od . Tuple variable E represents a single row of table EXERCISES (the loop assigns each row in succession). 234 Tuple Variables (2) • For each table in the FROM clause, a tuple variable is automatically created: if not given explicitly, the variable will have the name of the relation: SELECT EXERCISES.ENO, EXERCISES.TOPIC FROM EXERCISES WHERE EXERCISES.CAT = ’H’ . In other words, stating FROM EXERCISES only is understood as FROM EXERCISES EXERCISES (the tuple variable EXERCISES ranges over the rows of the table EXERCISES). 235 Tuple Variables (3) • If a tuple variable is explicitly declared, e.g., FROM EXERCISES E then the implicit tuple variable EXERCISES is not declared, i.e., EXERCISES.ENO will yield an error. • A reference to an attribute A of a tuple variable R may be simply written as A (instead of R.A) if R is the only variable which is bound to tuples having an attribute named A. 236 Attribute References (1) • In general, attributes are referenced in the form R.A • If an attribute may be associated to a tuple variable in an unambiguous manner, the variable may be omitted, e.g.: SELECT CAT, ENO, POINTS FROM STUDENTS S, RESULTS R WHERE S.SID = R.SID AND FIRST = ’Ann’ AND LAST = ’Smith’ FIRST, LAST can only refer to S. CAT, ENO, POINTS can only refer to R. SID on its own is ambiguous (may refer to S or R). 237 Attribute References (2) • Consider this query: SELECT ENO, SID, POINTS, MAXPT FROM RESULTS R, EXERCISES E WHERE R.ENO = E.ENO AND R.CAT = ’H’ AND E.CAT = ’H’ . Although forced to be equal by the join condition, SQL requires the user to specify unambiguously which of the ENO attributes (bound to R or E) is meant in the SELECT clause. The unambiguity rule thus is purely syntactic and does not depend on the query semantics. 238 Joins (1) • Consider a query with two tuple variables: SELECT A1, ... ,An FROM STUDENTS S, RESULTS R WHERE C . S will range over 4 tuples in STUDENTS, R will range over 8 tuples in RESULTS. In principle, all 4 8 = 32 combinations × will be considered in condition C: foreach S STUDENTS do foreach∈ R RESULTS do if C then∈ print A1,...,An fi od od 239 Joins (2) • A good DBMS will use a better evaluation algorithm (depending on the condition C). This is the task of the query optimizer. For example, if C contains the join condition S.SID = R.SID, the DBMS might loop over the tuples in RESULTS and find the corresponding STUDENTS tuple by using an index over STUDENT.SID (many DBMS automatically create an index over the key attributes). • In order to understand the semantics of a query, however, the simple nested foreach algorithm suffices. The query optimizer may use any algorithm that produces the exact same output, although possibly in different tuple order. 240 Joins (3) • A join needs to be explicitly specified in the WHERE clause: SELECT R.CAT, R.ENO, R.POINTS FROM STUDENTS S, RESULTS R WHERE S.SID = R.SID -- Join Condition AND S.FIRST = ’Ann’ AND S.LAST = ’Smith’ Output of this query? SELECT S.FIRST, S.LAST FROM STUDENTS S, RESULTS R WHERE R.CAT = ’H’ AND R.ENO = 1 Notes 241 Joins (4) • Guideline: it is almost always an error if there are two tuples variables which are not linked (directly or indirectly) via join conditions. In this query, all three tuple variables are connected: SELECT E.CAT, E.ENO, R.POINTS, E.MAXPT FROM STUDENTS S, RESULTS R, EXERCISES E WHERE S.SID = R.SID AND R.CAT = E.CAT AND R.ENO = E.ENO AND S.FIRST = ’Ann’ AND S.LAST = ’Smith’ 242 Joins (5) • The tuple variable connection works as follows: S R E '&%$ !"# S.SID = R.SID '&%$ !"# R.CAT = E.CAT '&%$ !"# AND R.ENO = E.ENO • The conditions correspond to the foreign key relationships between the tables. • The omission of a join condition will usually lead to numerous duplicates in the query result. Usage of DISTINCT to get rid of duplicate does not fix the error in such a case, of course. 243 Query Formulation (1) Formulate the following query in SQL “Which are the topics of all exercises solved by Ann Smith?” • To formulate this query, . consider that Ann Smith is a student, requiring a tuple variable, S say, over STUDENTS and the identifying condition S.FIRST = ’Ann’ AND S.LAST = ’Smith’. Exercise topics are of interest, so a tuple variable E over EXERCISES is needed, and the following piece of SQL can already be generated: SELECT DISTINCT E.TOPIC Several exercises may have the same topic. 244 Query Formulation (2) • Note: S and E are still unconnected. • The connection graph of the tables in a database schema (edges correspond to foreign key relationships) helps in understanding the connection requirements: STUDENTS RESULTS EXERCISES . We see that the S–E connection is indirect and needs to be established via a tuple variable R over RESULTS: S.SID = R.SID AND R.CAT = E.CAT AND R.ENO = E.ENO 245 Query Formulation (3) • It is not always that trivial. The connection graph may contain cycles, which makes the selection of the “right path” more difficult (and error-prone). • Consider a course registration database that also contains TA (“Hiwi”) assignments: TA eee YYYY eeeeeee YYYYYY STUDENTS e Y COURSES YYYY eee YYYYY eeeeee ENROLLMENTS 246 Unnecessary Joins (1) • Do not join more tables than needed. Query will run slowly if the optimizer overlooks the redundancy. Results for homework 1 SELECT R.SID, R.POINTS FROM RESULTS R, EXERCISES E WHERE R.CAT = E.CAT AND R.ENO = E.ENO AND E.CAT = ’H’ AND E.ENO = 1 Will the following query produce the same results? SELECT SID, POINTS FROM RESULTS R WHERE R.CAT = ’H’ AND R.ENO = 1 247 Unnecessary Joins (2) What will be the result of this query? SELECT R.SID, R.POINTS FROM RESULTS R, EXERCISES E WHERE R.CAT = ’H’ AND R.ENO = 1 Is there any difference between these two queries? SELECT S.FIRST, S.LAST FROM STUDENTS S SELECT DISTINCT S.FIRST, S.LAST FROM STUDENTS S, RESULTS R WHERE S.SID = R.SID Notes 248 Self Joins (1) • In some query scenarios, we might have to consider more than tuple of the same relation in order to generate a result tuple. Is there a student who got 9 points for both, homework 1 and homework 2? SELECT S.FIRST, S.LAST FROM STUDENTS S, RESULTS H1, RESULTS H2 WHERE S.SID = H1.SID AND S.SID = H2.SID AND H1.CAT = ’H’ AND H1.ENO = 1 AND H2.CAT = ’H’ AND H2.ENO = 2 AND H1.POINTS = 9 AND H2.POINTS = 9 249 Self Joins (2) Find students who solved at least two exercises.a aThis may also be solved using aggregations (later). SELECT S.FIRST, S.LAST FROM STUDENTS S, RESULTS E1, RESULTS E2 WHERE S.SID = E1.SID AND S.SID = E2.SID “Unexpected” result What is going wrong here? We need to make explicit that E1 and E2 refer to distinct exercises: . AND (E1.CAT <> E2.CAT OR E1.ENO <> E2.ENO) 250 Duplicate Elimination (1) • A core difference between SQL and relational algebra is that duplicates have to explicitly eliminated in SQL. Which exercises have already been solved by at least one student? CAT ENO H 1 H 2 SELECT CAT, ENO M 1 FROM RESULTS H 1 H 2 M 1 H 1 M 1 251 Duplicate Elimination (2) • If a query might yield unwanted duplicate tuples, the DISTINCT modifier may be applied to the SELECT clause to request explicit duplicate row elimination: CAT ENO SELECT DISTINCT CAT, ENO H 1 FROM RESULTS H 2 M 1 • To emphasize that there will be duplicate rows (and that these are wanted in the result), SQL provides the ALL modifier.4 4SELECT ALL is the default.
Recommended publications
  • Database Concepts 7Th Edition
    Database Concepts 7th Edition David M. Kroenke • David J. Auer Online Appendix E SQL Views, SQL/PSM and Importing Data Database Concepts SQL Views, SQL/PSM and Importing Data Appendix E All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. Printed in the United States of America. Appendix E — 10 9 8 7 6 5 4 3 2 1 E-2 Database Concepts SQL Views, SQL/PSM and Importing Data Appendix E Appendix Objectives • To understand the reasons for using SQL views • To use SQL statements to create and query SQL views • To understand SQL/Persistent Stored Modules (SQL/PSM) • To create and use SQL user-defined functions • To import Microsoft Excel worksheet data into a database What is the Purpose of this Appendix? In Chapter 3, we discussed SQL in depth. We discussed two basic categories of SQL statements: data definition language (DDL) statements, which are used for creating tables, relationships, and other structures, and data manipulation language (DML) statements, which are used for querying and modifying data. In this appendix, which should be studied immediately after Chapter 3, we: • Describe and illustrate SQL views, which extend the DML capabilities of SQL. • Describe and illustrate SQL Persistent Stored Modules (SQL/PSM), and create user-defined functions. • Describe and use DBMS data import techniques to import Microsoft Excel worksheet data into a database. E-3 Database Concepts SQL Views, SQL/PSM and Importing Data Appendix E Creating SQL Views An SQL view is a virtual table that is constructed from other tables or views.
    [Show full text]
  • Self-Organizing Tuple Reconstruction in Column-Stores
    Self-organizing Tuple Reconstruction in Column-stores Stratos Idreos Martin L. Kersten Stefan Manegold CWI Amsterdam CWI Amsterdam CWI Amsterdam The Netherlands The Netherlands The Netherlands [email protected] [email protected] [email protected] ABSTRACT 1. INTRODUCTION Column-stores gained popularity as a promising physical de- A prime feature of column-stores is to provide improved sign alternative. Each attribute of a relation is physically performance over row-stores in the case that workloads re- stored as a separate column allowing queries to load only quire only a few attributes of wide tables at a time. Each the required attributes. The overhead incurred is on-the-fly relation R is physically stored as a set of columns; one col- tuple reconstruction for multi-attribute queries. Each tu- umn for each attribute of R. This way, a query needs to load ple reconstruction is a join of two columns based on tuple only the required attributes from each relevant relation. IDs, making it a significant cost component. The ultimate This happens at the expense of requiring explicit (partial) physical design is to have multiple presorted copies of each tuple reconstruction in case multiple attributes are required. base table such that tuples are already appropriately orga- Each tuple reconstruction is a join between two columns nized in multiple different orders across the various columns. based on tuple IDs/positions and becomes a significant cost This requires the ability to predict the workload, idle time component in column-stores especially for multi-attribute to prepare, and infrequent updates. queries [2, 6, 10].
    [Show full text]
  • Support Aggregate Analytic Window Function Over Large Data by Spilling
    Support Aggregate Analytic Window Function over Large Data by Spilling Xing Shi and Chao Wang Guangdong University of Technology, Guangzhou, Guangdong 510006, China North China University of Technology, Beijing 100144, China Abstract. ​Analytic function, also called window function, is to query the aggregation of data over a sliding window. For example, a simple query over the online stock platform is to return the average price of a stock of the last three days. These functions are commonly used features in SQL databases. They are supported in most of the commercial databases. With the increasing usage of cloud data infra and machine learning technology, the frequency of queries with analytic window functions rises. Some analytic functions only require const space in memory to store the state, such as SUM, AVG, while others require linear space, such as MIN, MAX. When the window is extremely large, the memory space to store the state may be too large. In this case, we need to spill the state to disk, which is a heavy operation. In this paper, we proposed an algorithm to manipulate the state data in the disk to reduce the disk I/O to make spill available and efficiency. We analyze the complexity of the algorithm with different data distribution. 1. Introducion In this paper, we develop novel spill techniques for analytic window function in SQL databases. And discuss different various types of aggregate queries, e.g., COUNT, AVG, SUM, MAX, MIN, etc., over a relational table. Aggregate ​analytic function, also called aggregate window function, is to query the aggregation of data over a sliding window.
    [Show full text]
  • On Free Products of N-Tuple Semigroups
    n-tuple semigroups Anatolii Zhuchok Luhansk Taras Shevchenko National University Starobilsk, Ukraine E-mail: [email protected] Anatolii Zhuchok Plan 1. Introduction 2. Examples of n-tuple semigroups and the independence of axioms 3. Free n-tuple semigroups 4. Free products of n-tuple semigroups 5. References Anatolii Zhuchok 1. Introduction The notion of an n-tuple algebra of associative type was introduced in [1] in connection with an attempt to obtain an analogue of the Chevalley construction for modular Lie algebras of Cartan type. This notion is based on the notion of an n-tuple semigroup. Recall that a nonempty set G is called an n-tuple semigroup [1], if it is endowed with n binary operations, denoted by 1 ; 2 ; :::; n , which satisfy the following axioms: (x r y) s z = x r (y s z) for any x; y; z 2 G and r; s 2 f1; 2; :::; ng. The class of all n-tuple semigroups is rather wide and contains, in particular, the class of all semigroups, the class of all commutative trioids (see, for example, [2, 3]) and the class of all commutative dimonoids (see, for example, [4, 5]). Anatolii Zhuchok 2-tuple semigroups, causing the greatest interest from the point of view of applications, occupy a special place among n-tuple semigroups. So, 2-tuple semigroups are closely connected with the notion of an interassociative semigroup (see, for example, [6, 7]). Moreover, 2-tuple semigroups, satisfying some additional identities, form so-called restrictive bisemigroups, considered earlier in the works of B. M. Schein (see, for example, [8, 9]).
    [Show full text]
  • Multiple Condition Where Clause Sql
    Multiple Condition Where Clause Sql Superlunar or departed, Fazeel never trichinised any interferon! Vegetative and Czechoslovak Hendrick instructs tearfully and bellyings his tupelo dispensatorily and unrecognizably. Diachronic Gaston tote her endgame so vaporously that Benny rejuvenize very dauntingly. Codeigniter provide set class function for each mysql function like where clause, join etc. The condition into some tests to write multiple conditions that clause to combine two conditions how would you occasionally, you separate privacy: as many times. Sometimes, you may not remember exactly the data that you want to search. OR conditions allow you to test multiple conditions. All conditions where condition is considered a row. Issue date vary each bottle of drawing numbers. How sql multiple conditions in clause condition for column for your needs work now query you take on clauses within a static list. The challenge join combination for joining the tables is found herself trying all possibilities. TOP function, if that gives you no idea. New replies are writing longer allowed. Thank you for your feedback! Then try the examples in your own database! Here, we have to provide filters or conditions. The conditions like clause to make more content is used then will identify problems, model and arrangement of operators. Thanks for your help. Thanks for war help. Multiple conditions on the friendly column up the discount clause. This sql where clause, you have to define multiple values you, we have to basic syntax. But your suggestion is more readable and straight each way out implement. Use parenthesis to set of explicit groups of contents open source code.
    [Show full text]
  • SQL DELETE Table in SQL, DELETE Statement Is Used to Delete Rows from a Table
    SQL is a standard language for storing, manipulating and retrieving data in databases. What is SQL? SQL stands for Structured Query Language SQL lets you access and manipulate databases SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the International Organization for Standardization (ISO) in 1987 What Can SQL do? SQL can execute queries against a database SQL can retrieve data from a database SQL can insert records in a database SQL can update records in a database SQL can delete records from a database SQL can create new databases SQL can create new tables in a database SQL can create stored procedures in a database SQL can create views in a database SQL can set permissions on tables, procedures, and views Using SQL in Your Web Site To build a web site that shows data from a database, you will need: An RDBMS database program (i.e. MS Access, SQL Server, MySQL) To use a server-side scripting language, like PHP or ASP To use SQL to get the data you want To use HTML / CSS to style the page RDBMS RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access. The data in RDBMS is stored in database objects called tables. A table is a collection of related data entries and it consists of columns and rows. SQL Table SQL Table is a collection of data which is organized in terms of rows and columns.
    [Show full text]
  • How to Get Data from Oracle to Postgresql and Vice Versa Who We Are
    How to get data from Oracle to PostgreSQL and vice versa Who we are The Company > Founded in 2010 > More than 70 specialists > Specialized in the Middleware Infrastructure > The invisible part of IT > Customers in Switzerland and all over Europe Our Offer > Consulting > Service Level Agreements (SLA) > Trainings > License Management How to get data from Oracle to PostgreSQL and vice versa 19.06.2020 Page 2 About me Daniel Westermann Principal Consultant Open Infrastructure Technology Leader +41 79 927 24 46 daniel.westermann[at]dbi-services.com @westermanndanie Daniel Westermann How to get data from Oracle to PostgreSQL and vice versa 19.06.2020 Page 3 How to get data from Oracle to PostgreSQL and vice versa Before we start We have a PostgreSQL user group in Switzerland! > https://www.swisspug.org Consider supporting us! How to get data from Oracle to PostgreSQL and vice versa 19.06.2020 Page 4 How to get data from Oracle to PostgreSQL and vice versa Before we start We have a PostgreSQL meetup group in Switzerland! > https://www.meetup.com/Switzerland-PostgreSQL-User-Group/ Consider joining us! How to get data from Oracle to PostgreSQL and vice versa 19.06.2020 Page 5 Agenda 1.Past, present and future 2.SQL/MED 3.Foreign data wrappers 4.Demo 5.Conclusion How to get data from Oracle to PostgreSQL and vice versa 19.06.2020 Page 6 Disclaimer This session is not about logical replication! If you are looking for this: > Data Replicator from DBPLUS > https://blog.dbi-services.com/real-time-replication-from-oracle-to-postgresql-using-data-replicator-from-dbplus/
    [Show full text]
  • Handling Missing Values in the SQL Procedure
    Handling Missing Values in the SQL Procedure Danbo Yi, Abt Associates Inc., Cambridge, MA Lei Zhang, Domain Solutions Corp., Cambridge, MA non-missing numeric values. A missing ABSTRACT character value is expressed and treated as a string of blanks. Missing character values PROC SQL as a powerful database are always same no matter whether it is management tool provides many features expressed as one blank, or more than one available in the DATA steps and the blanks. Obviously, missing character values MEANS, TRANSPOSE, PRINT and SORT are not the smallest strings. procedures. If properly used, PROC SQL often results in concise solutions to data In SAS system, the way missing Date and manipulations and queries. PROC SQL DateTime values are expressed and treated follows most of the guidelines set by the is similar to missing numeric values. American National Standards Institute (ANSI) in its implementation of SQL. This paper will cover following topics. However, it is not fully compliant with the 1. Missing Values and Expression current ANSI Standard for SQL, especially · Logic Expression for the missing values. PROC SQL uses · Arithmetic Expression SAS System convention to express and · String Expression handle the missing values, which is 2. Missing Values and Predicates significantly different from many ANSI- · IS NULL /IS MISSING compatible SQL databases such as Oracle, · [NOT] LIKE Sybase. In this paper, we summarize the · ALL, ANY, and SOME ways the PROC SQL handles the missing · [NOT] EXISTS values in a variety of situations. Topics 3. Missing Values and JOINs include missing values in the logic, · Inner Join arithmetic and string expression, missing · Left/Right Join values in the SQL predicates such as LIKE, · Full Join ANY, ALL, JOINs, missing values in the 4.
    [Show full text]
  • Chapter 11 Querying
    Oracle TIGHT / Oracle Database 11g & MySQL 5.6 Developer Handbook / Michael McLaughlin / 885-8 Blind folio: 273 CHAPTER 11 Querying 273 11-ch11.indd 273 9/5/11 4:23:56 PM Oracle TIGHT / Oracle Database 11g & MySQL 5.6 Developer Handbook / Michael McLaughlin / 885-8 Oracle TIGHT / Oracle Database 11g & MySQL 5.6 Developer Handbook / Michael McLaughlin / 885-8 274 Oracle Database 11g & MySQL 5.6 Developer Handbook Chapter 11: Querying 275 he SQL SELECT statement lets you query data from the database. In many of the previous chapters, you’ve seen examples of queries. Queries support several different types of subqueries, such as nested queries that run independently or T correlated nested queries. Correlated nested queries run with a dependency on the outer or containing query. This chapter shows you how to work with column returns from queries and how to join tables into multiple table result sets. Result sets are like tables because they’re two-dimensional data sets. The data sets can be a subset of one table or a set of values from two or more tables. The SELECT list determines what’s returned from a query into a result set. The SELECT list is the set of columns and expressions returned by a SELECT statement. The SELECT list defines the record structure of the result set, which is the result set’s first dimension. The number of rows returned from the query defines the elements of a record structure list, which is the result set’s second dimension. You filter single tables to get subsets of a table, and you join tables into a larger result set to get a superset of any one table by returning a result set of the join between two or more tables.
    [Show full text]
  • SQL Stored Procedures
    Agenda Key:31MA Session Number:409094 DB2 for IBM i: SQL Stored Procedures Tom McKinley ([email protected]) DB2 for IBM i consultant IBM Lab Services 8 Copyright IBM Corporation, 2009. All Rights Reserved. This publication may refer to products that are not currently available in your country. IBM makes no commitment to make available any products referred to herein. What is a Stored Procedure? • Just a called program – Called from SQL-based interfaces via SQL CALL statement • Supports input and output parameters – Result sets on some interfaces • Follows security model of iSeries – Enables you to secure your data – iSeries adopted authority model can be leveraged • Useful for moving host-centric applications to distributed applications 2 © 2009 IBM Corporation What is a Stored Procedure? • Performance savings in distributed computing environments by dramatically reducing the number of flows (requests) to the database engine – One request initiates multiple transactions and processes R R e e q q u u DB2 for i5/OS DB2DB2 for for i5/OS e e AS/400 s s t t SP o o r r • Performance improvements further enhanced by the option of providing result sets back to ODBC, JDBC, .NET & CLI clients 3 © 2009 IBM Corporation Recipe for a Stored Procedure... 1 Create it CREATE PROCEDURE total_val (IN Member# CHAR(6), OUT total DECIMAL(12,2)) LANGUAGE SQL BEGIN SELECT SUM(curr_balance) INTO total FROM accounts WHERE account_owner=Member# AND account_type IN ('C','S','M') END 2 Call it (from an SQL interface) over and over CALL total_val(‘123456’, :balance) 4 © 2009 IBM Corporation Stored Procedures • DB2 for i5/OS supports two types of stored procedures 1.
    [Show full text]
  • Firebird 3 Windowing Functions
    Firebird 3 Windowing Functions Firebird 3 Windowing Functions Author: Philippe Makowski IBPhoenix Email: pmakowski@ibphoenix Licence: Public Documentation License Date: 2011-11-22 Philippe Makowski - IBPhoenix - 2011-11-22 Firebird 3 Windowing Functions What are Windowing Functions? • Similar to classical aggregates but does more! • Provides access to set of rows from the current row • Introduced SQL:2003 and more detail in SQL:2008 • Supported by PostgreSQL, Oracle, SQL Server, Sybase and DB2 • Used in OLAP mainly but also useful in OLTP • Analysis and reporting by rankings, cumulative aggregates Philippe Makowski - IBPhoenix - 2011-11-22 Firebird 3 Windowing Functions Windowed Table Functions • Windowed table function • operates on a window of a table • returns a value for every row in that window • the value is calculated by taking into consideration values from the set of rows in that window • 8 new windowed table functions • In addition, old aggregate functions can also be used as windowed table functions • Allows calculation of moving and cumulative aggregate values. Philippe Makowski - IBPhoenix - 2011-11-22 Firebird 3 Windowing Functions A Window • Represents set of rows that is used to compute additionnal attributes • Based on three main concepts • partition • specified by PARTITION BY clause in OVER() • Allows to subdivide the table, much like GROUP BY clause • Without a PARTITION BY clause, the whole table is in a single partition • order • defines an order with a partition • may contain multiple order items • Each item includes
    [Show full text]
  • Using the Set Operators Questions
    UUSSIINNGG TTHHEE SSEETT OOPPEERRAATTOORRSS QQUUEESSTTIIOONNSS http://www.tutorialspoint.com/sql_certificate/using_the_set_operators_questions.htm Copyright © tutorialspoint.com 1.Which SET operator does the following figure indicate? A. UNION B. UNION ALL C. INTERSECT D. MINUS Answer: A. Set operators are used to combine the results of two ormore SELECT statements.Valid set operators in Oracle 11g are UNION, UNION ALL, INTERSECT, and MINUS. When used with two SELECT statements, the UNION set operator returns the results of both queries.However,if there are any duplicates, they are removed, and the duplicated record is listed only once.To include duplicates in the results,use the UNION ALL set operator.INTERSECT lists only records that are returned by both queries; the MINUS set operator removes the second query's results from the output if they are also found in the first query's results. INTERSECT and MINUS set operations produce unduplicated results. 2.Which SET operator does the following figure indicate? A. UNION B. UNION ALL C. INTERSECT D. MINUS Answer: B. UNION ALL Returns the combined rows from two queries without sorting or removing duplicates. sql_certificate 3.Which SET operator does the following figure indicate? A. UNION B. UNION ALL C. INTERSECT D. MINUS Answer: C. INTERSECT Returns only the rows that occur in both queries' result sets, sorting them and removing duplicates. 4.Which SET operator does the following figure indicate? A. UNION B. UNION ALL C. INTERSECT D. MINUS Answer: D. MINUS Returns only the rows in the first result set that do not appear in the second result set, sorting them and removing duplicates.
    [Show full text]