SKILL 2.2: QUERY DATA BY USING TABLE EXPRESSIONS Flashcards

1
Q

Name T-SQL Table Expressions

A
  1. Derived Tables
  2. common table expressions (CTE)
  3. Views
  4. Inline table variables
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Table expressions that are visible only to the statement that defines them?

A
  1. Derived Tables

2. Common table Expressiosn (CTE)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Which Table expressions are reusable and preserved in the database as an object

A
  1. Views

2. Inline table-valued functions

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Table expressions- Which operation is not allowed and how can it be circumvented?

A

Their inner query can’t have an ORDER BY clause, Except when you use OFFSET-FETCH

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

(Table expressions)- Columns returned by the inner query must have:

A

names or use aliases, and they need to be unique

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Derived Tables - Format

A

SELECT

*

FROM

(

SELECT

FilmName

,FilmRunTimeMinutes

FROM

tblFilm

) AS MyDerivedTable

WHERE

FilmRunTimeMinutes < 100

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Derived tables - drawbacks

A

When nested they are too complicated,
If you want to join multiple instances of the same derived table you can’t. You have to duplicate code - and that generates errors

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Common table Expression - Visibility

A

It is not visible to the outer query

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Common table Expression and Derived table parts

A
  1. Inner query
  2. Name assigned to the query and its columns
  3. Outer query
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Common table expression - Format

A

WITH

AS

(

)

;

Example:
WITH C AS

(

SELECT

ROW_NUMBER() OVER(PARTITION BY categoryid

                  ORDER BY unitprice, productid) AS rownum,

categoryid, productid, productname, unitprice

FROM Production.Products

)

SELECT categoryid, productid, productname, unitprice

FROM C

WHERE rownum <= 2;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Defining multiple CTEs

A

You don’t nest CTEs, if you need multiple CTEs you simply separate them by commas.
Each can refer to the previously defined CTEs and the outer query can refer to all of them

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Defining multiple CTEs - Format

A

WITH C1 AS

(

SELECT …

FROM T1

WHERE …

),

C2 AS

(

SELECT

FROM C1

WHERE …

)

SELECT …

FROM C2

WHERE …;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Recursive CTE - Format

A

WITH EmpsCTE AS

(

SELECT empid, mgrid, firstname, lastname, 0 AS distance

FROM HR.Employees

WHERE empid = 9

UNION ALL

SELECT M.empid, M.mgrid, M.firstname, M.lastname, S.distance + 1 AS distance

FROM EmpsCTE AS S

JOIN HR.Employees AS M

  ON S.mgrid = M.empid

)

SELECT empid, mgrid, firstname, lastname, distance

FROM EmpsCTE;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Which table expressions are reusable?

A

Views and Inlined table-valued functions. They are created as objects in the database and thus can be reused.
You can also control access by assigning permissions

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Difference between Views and inline table-valued functions?

A

Views don’t accept input parameters while inline table-valued functions do

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

View - format

A

CREATE VIEW Sales.RankedProducts

AS

SELECT

ROW_NUMBER() OVER(PARTITION BY categoryid

                ORDER BY unitprice, productid) AS rownum,

categoryid, productid, productname, unitprice

FROM Production.Products;

GO

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Inline table-valued function - Format

A

CREATE FUNCTION HR.GetManagers(@empid AS INT) RETURNS TABLE

AS

RETURN

WITH EmpsCTE AS

(

SELECT empid, mgrid, firstname, lastname, 0 AS distance

FROM HR.Employees

WHERE empid = @empid

UNION ALL

SELECT M.empid, M.mgrid, M.firstname, M.lastname, S.distance + 1 AS distance

FROM EmpsCTE AS S

  JOIN HR.Employees AS M

    ON S.mgrid = M.empid

)

SELECT empid, mgrid, firstname, lastname, distance

FROM EmpsCTE;

GO

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

With GROUPING SETS clause you can…

A

list all grouping sets that you want to define in the query

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

GROUPING SETS - Format

A

SELECT shipperid, YEAR(shippeddate) AS shipyear, COUNT(*) AS numorders

FROM Sales.Orders

WHERE shippeddate IS NOT NULL – exclude unshipped orders

GROUP BY GROUPING SETS

(

( shipperid, YEAR(shippeddate) ),

( shipperid ),

( YEAR(shippeddate) ),

( )

);

20
Q

CUBE

A

Same as GROUP BY GROUPING SETS with all the combinations

21
Q

ROLLUP

A

You use it when there is a natural hierarchy. Used when other combinations are not interesting
and to avoid unnecessary computation

22
Q

ROLLUP - format

A

SELECT shipcountry, shipregion, shipcity, COUNT(*) AS numorders

FROM Sales.Orders

GROUP BY ROLLUP( shipcountry, shipregion, shipcity );

–Same as:
GROUPING SETS
( shipcountry, shipregion, shipcity )

( shipcountry, shipregion )

( shipcountry )

( )

23
Q

GROUPING -function in GROUP BY

A

returns 0 when the element is a part of the grouping set and 1 when it’s not

24
Q

GROUPING_ID

A

Accepts the list of grouped columns as inputs and returns an integer representing a bitmap:
grp_id shipcountry shipregion shipcity numorders

0 Argentina NULL Buenos Aires 16

1 Argentina NULL NULL 16

3 Argentina NULL NULL 16

0 USA AK Anchorage 10

1 USA AK NULL 10

0 USA CA San Francisco 4

1 USA CA NULL 4

0 USA ID Boise 31

1 USA ID NULL 31

3 USA NULL NULL 122

7 NULL NULL NULL 830

25
Q

Pivoting data

A

Specialized case of grouping and aggregating data. It transitions it from a state of rows to a state of columns

26
Q

3 elements necessary for PIVOT queries

A
  1. What do you want to see on rows? - the “on rows” or grouping element
  2. What do you want to see on columns? - the “on cols” or spreading element
  3. What do you want to see in the intersection of each distinct row and column value - the “data” or aggregation element
27
Q

PIVOT- Form

A

WITH PivotData AS

(

SELECT

< grouping column >,

< spreading column >,

< aggregation column >

FROM < source table >

)

SELECT < select list >

FROM PivotData

PIVOT( < aggregate function >(< aggregation column >)

FOR < spreading column > IN (< distinct spreading values >) ) AS P;
28
Q

PIVOT limitations

A
  1. the COUNT(*) isn’t allowed, however COUNT(colname) is allowed
  2. PIVOT operator is limited to using only one aggregate function
  3. The IN clause of the PIVOT operator accepts only a static list of spreading values. It doesn’t support a subquery as input
29
Q

UNPIVOT

A

Always takes a set of source columns and rotates those to multiple rows, generating two target columns, one to hold source column values and one to hold the source column names

30
Q

UNPIVOT - Format

A

SELECT < column list >, < names column >, < values column >

FROM < source table >

UNPIVOT( < values column > FOR < names column > IN( ) ) AS U;

SELECT custid, shipperid, freight

FROM Sales.FreightTotals

UNPIVOT( freight FOR shipperid IN([1],[2],[3]) ) AS U;

31
Q

Window aggregate functions

A

are applied to a window of rows defiend by the OVER clause

32
Q

Window aggregate functions - use case when they are faster than joins

A

They better perform computations such as running totals

33
Q

Window aggregate functions - format

A

SELECT custid, orderid, val,

SUM(val) OVER(PARTITION BY custid) AS custtotal,

SUM(val) OVER() AS grandtotal

FROM Sales.OrderValues;

34
Q

Window aggregate functions - running totals - format

A

SELECT custid, orderid, orderdate, val,

SUM(val) OVER(PARTITION BY custid

            ORDER BY orderdate, orderid

            ROWS BETWEEN UNBOUNDED PRECEDING

                     AND CURRENT ROW) AS runningtotal

FROM Sales.OrderValues;

35
Q

UNBOUNDED PRECEDING and FOLLOWING

A

UNBOUNDED PRECEDING - start of the partition FOLLOWING - end of the partition

36
Q

ROWS PRECEDING or FOLLOWING

A

meaning n rows before or after the current, respectively.

37
Q

ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW can be changed for a less verbose form

A

ROWS UNBOUNDED PRECEDING

38
Q

Window functions are only allowed in which query clauses (the last evaluated clauses)

A

SELECT and ORDER BY. If you need to refer to the result of a window function in any clause that is before the SELECT statement you need to use a Table Expression

39
Q

How to include only the last three rows in a window function?

A

ROWS BETWEEN 2 PRECEDING AND CURRENT ROW

40
Q

Window Ranking Functions

A

rank rows within a partition base on a specified ordering

41
Q

What is mandatory in a Window ranking function

A

The ORDER BY clause is mandatory

42
Q

TSQL Window ranking functions

A

ROW_NUMBER, RANK, DENSE_RANK, NTILE

43
Q

ROW_NUMBER

A

unique incrementing integers starting with 1 within the partition based on the window ordering.
When there are ties the ordering is non-deterministic, so use unique ORDER BY

44
Q

Difference between RANK and DENSE_RANK

A

RANK increments the numbers but the values which are equal have the same rank but the following ranks “skip” the numbers.(1,2,2,4)
DENSE_RANK has the same behavior but without skipping ranks (1,2,2,3)

45
Q

Are Window ranking functions deterministic or non-deterministic?

A

With all window ranking functions, two different rows can get two different rank values, and therefore are considered nondeterministic.

46
Q

NTILE function

A

Arranges rows within the partition in a requested number of equally sized tiles, based on specific ordering

47
Q

Window Offset Functions - list

A

LAG, LEAD, FIRST_VALUE, LAST_VALUE