Lesson 3.2: Running a complex query
Use the SQL editor in Db2® Big SQL console to run a complex query.
About this task
This complex query has common table expressions, aggregate functions, and a ranking function to rank products based on quantity sold online and quantity sold in stores.
Procedure
Results
Learn more about this complex query:
- The query joins multiple tables. When choosing the order of tables in a query, remember to eliminate rows as early as possible.
- Tables that use predicates to filter out many rows, or tables with rows that are removed as a result of a join, should be located early in a query. Such tables are considered to be highly selective. Ordering the tables in this way reduces the number of rows that must be moved to the next step of the query.
- The INV_SHIPPED column is derived from the SUM aggregate function and a CAST function, as shown
in the following statement from the
query:
The original column, QUANTITY_SHIPPED, is defined as an integer column. The CAST function converts the output to another data type; in this case, BIGINT. The SUM function returns a single aggregate value for the column.SUM(CAST (inventory.quantity_shipped AS BIGINT)) AS inv_shipped
- The PROD_RANK column is derived from the RANK function, as shown in the following statement from
the
query:
The SALES.QUANTITY column is sorted in descending order. The RANK function generates a number that is based on the sorted order.RANK() OVER (ORDER BY SUM(CAST (sales.quantity AS BIGINT)) DESC) AS prod_rank