Using Table Expressions

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 18
At a glance
Powered by AI
The key takeaways from the module are that it covers using views, inline TVFs, derived tables, and common table expressions (CTEs) to write queries that return data from these table expressions.

The module covers using views, inline TVFs, derived tables, and CTEs. Views are saved queries with a single SELECT statement. Inline TVFs are like parameterized views with a single SELECT. Derived tables are subqueries defined with SELECT and given an alias. CTEs are named table expressions that can be referenced multiple times in a query.

Views are saved queries that can be used in the FROM clause like a table, while inline TVFs support input parameters. Views cannot have an ORDER BY clause by default but TVFs can. TVFs return a virtual table to the calling query.

Module 11

Using Table Expressions


Module Overview

Using Views
Using Inline TVFs
Using Derived Tables
Using CTEs
Lesson 1: Using Views

Writing Queries That Return Results from Views


Creating Simple Views
Demonstration: Using Views
Writing Queries That Return Results from Views

Views may be referenced in a SELECT


statement just like a table
Views are named table expressions with
definitions stored in a database
Like derived tables and CTEs, queries that use
views can provide encapsulation and
simplification
From an administrative perspective, views can
provide a security layer to a database
SELECT <select_list>
FROM <view_name>
ORDER BY <sort_list>;
Creating Simple Views

Views are saved queries created in a database by


administrators and developers
Views are defined with a single SELECT statement
ORDER BY is not permitted in a view definition without
the use of TOP, OFFSET/FETCH, or FOR XML
To sort the output, use ORDER BY in the outer query
View creation supports additional options beyond the
scope of this class
CREATE VIEW HR.EmpPhoneList
AS
SELECT empid, lastname, firstname, phone
FROM HR.Employees;
Lesson 2: Using Inline TVFs

Writing Queries That Use Inline TVFs


Creating Simple Inline TVFs
Retrieving from Inline TVFs
Demonstration: Inline TVFs
Writing Queries That Use Inline TVFs

TVFs are named table expressions with


definitions stored in a database
TVFs return a virtual table to the calling query
SQL Server provides two types of TVFs
Inline, based on a single SELECT statement
Multi-statement, which creates and loads a table
variable
Unlike views, TVFs support input parameters
Inline TVFs may be thought of as
parameterized views
Creating Simple Inline TVFs

TVFs are created by administrators and developers


Create and name function and optional parameters with
CREATE FUNCTION
Declare return type as TABLE
Define inline SELECT statement following RETURN

CREATE FUNCTION Sales.fn_LineTotal (@orderid INT)


RETURNS TABLE
AS
RETURN
SELECT orderid,
CAST((qty * unitprice * (1 - discount)) AS
DECIMAL(8, 2)) AS line_total
FROM Sales.OrderDetails
WHERE orderid = @orderid ;
Retrieving from Inline TVFs

SELECT from function


Use two-part name
Pass in parameters
SELECT orderid, productid, unitprice,
qty, discount, line_total
FROM Sales.fn_LineTotal(10252) AS LT;

orderid productid unitprice qty discount line_total


10252 20 64.80 40 0.05 2462.40
10252 33 2.00 25 0.05 47.50
10252 60 27.20 40 0.00 1088.00
Lesson 3: Using Derived Tables

Writing Queries with Derived Tables


Guidelines for Derived Tables
Using Aliases for Column Names in Derived Tables
Passing Arguments to Derived Tables
Nesting and Reusing Derived Tables
Demonstration: Using Derived Tables
Writing Queries with Derived Tables

Derived tables are named query expressions created


within an outer SELECT statement
Not stored in database represents a virtual relational
table
When processed, unpacked into query against
underlying referenced objects
Allow you to write more modular queries

SELECT <column_list>
FROM (
<derived_table_definition>
) AS <derived_table_alias>;

Scope of a derived table is the query in which it is


defined
Guidelines for Derived Tables

Derived Tables Must Derived Tables May

Have an alias Use internal or external


Have names for all aliases for columns
columns Refer to parameters
Have unique names for all and/or variables
columns Be nested within other
Not use an ORDER BY derived tables
clause (without TOP or
OFFSET/FETCH)
Not be referred to
multiple times in the
same query
Using Aliases for Column Names in Derived Tables

Column aliases may be defined inline:


SELECT orderyear, COUNT(DISTINCT custid) AS cust_count
FROM (
SELECT YEAR(orderdate) AS orderyear, custid
FROM Sales.Orders) AS derived_year
GROUP BY orderyear;

Column aliases may be defined externally:


SELECT orderyear, COUNT(DISTINCT custid) AS cust_count
FROM (
SELECT YEAR(orderdate), custid
FROM Sales.Orders) AS
derived_year(orderyear, custid)
GROUP BY orderyear;
Passing Arguments to Derived Tables

Derived tables may refer to arguments


Arguments may be:
Variables declared in the same batch as the SELECT
statement
Parameters passed into a table-valued function or
stored procedure
DECLARE @emp_id INT = 9;
SELECT orderyear, COUNT(DISTINCT custid) AS cust_count
FROM (
SELECT YEAR(orderdate) AS orderyear, custid
FROM Sales.Orders
WHERE empid=@emp_id
) AS derived_year
GROUP BY orderyear;
Nesting and Reusing Derived Tables

Derived tables may be nested, though not


recommended:

SELECT orderyear, cust_count


FROM ( SELECT orderyear,
COUNT(DISTINCT custid) AS cust_count
FROM ( SELECT YEAR(orderdate) AS orderyear
,custid
FROM Sales.Orders) AS derived_table_1
GROUP BY orderyear) AS derived_table_2
WHERE cust_count > 80;

Derived tables may not be referred to multiple


times in the same query
Each reference must be separately defined
Lesson 4: Using CTEs

Writing Queries with CTEs


Creating Queries with Common Table Expressions
Demonstration: Using CTEs
Writing Queries with CTEs

CTEs are named table expressions defined in a


query
CTEs are similar to derived tables in scope and
naming requirements
Unlike derived tables, CTEs support multiple
definitions, multiple references, and recursion
WITH <CTE_name>
AS (
<CTE_definition>
)
<outer query referencing CTE>;
Creating Queries with Common Table Expressions

To create a CTE:
Define the table expression in a WITH clause
Assign column aliases (inline or external)
Pass arguments if desired
Reference the CTE in the outer query

WITH CTE_year AS
(
SELECT YEAR(orderdate) AS orderyear, custid
FROM Sales.Orders
)
SELECT orderyear, COUNT(DISTINCT custid) AS cust_count
FROM CTE_year
GROUP BY orderyear;

You might also like