Sie sind auf Seite 1von 2
College MEYCAUAYAN Advance Database Systems

College MEYCAUAYAN

Advance Database Systems

COMMON TABLE EXPRESSION

(CTE) are temporary result set that are known only within the scope of a single SELECT, INSERT, UPDATE, DELETE or CREATE VIEW statement

Similar to derived table

It is not stored as an object and it last only for the duration of the query.

Generally useful in a query that involves multiple aggregate functions.

Used to produce summary of data such as SUM(), COUNT, MAX(), MIN(), etc.

Provide convenient means to temporarily store sets of values.

The CTE are defined using the WITH clause.

It precedes the SELECT keyword in a SELECT statement.

The content of the clause defines one or more temporary result set that may then be referenced elsewhere in the statement.

Example 1:

WITH CountEmployees(dept_id, n) AS

(

SELECT dept_id, COUNT(*) AS n

FROM Employee GROUP BY dept_id

)

SELECT dept_id, n FROM CountEmployees WHERE n = (SELECT MAX(n) FROM CountEmployees)

The above query is used to extract the department with the most employees. The SELECT statement in the CTE named CountEmployees return the dept_id and the count for each department. Then, the code

SELECT dept_id, n FROM CountEmployess WHERE n = ( SELECT MAX(n) FROM CountEmployees)

Invokes the CTE and iterates to the result set produced by the CTE. It then returns the department that has the most number of employees.

College MEYCAUAYAN Advance Database Systems

College MEYCAUAYAN

Advance Database Systems

Example 2:

WITH CountEmployees(dept_id, n) AS

(

SELECT dept_id, COUNT(*) AS n FROM employee GROUP BY dept_id

)

SELECT a.dept_id, a.n, b.dept_id, b.n FROM CountEmployees AS a JOIN CountEmployees as b ON a.n = b.n AND a.dept_id < b.dept_id

The code above shows an example of using different correlation names to multiple instances of a common table expression. The query above joins a common table expression to itself. The query produces pairs of departments that have the same number of employees.

Example 3:

WITH CountEmployees(dept_id, n) AS

(

SELECT dept_id, COUNT(*) AS n FROM employee GROUP BY dept_id ),DeptPayroll(dept_id, amt) AS

(

SELECT dept_id, sum(salary) AS amt FROM employee GROUP BY dept_id

)

SELECT count.dept_id, count.n, pay.amt FROM CountEmployees AS count JOIN DeptPayroll as pay ON count.dept_id = pay.dept_id WHERE count.n = ( SELECT MAX(n) FROM CountEmployees) OR pay.amt = (SELECT MIN(amt) FROM DeptPayroll)

The code above shows an example of using multiple table expression on a single WITH clause. Each table expression is separated by commas. The query lists the department that has the smallest payroll and the department that has the largest number of employees.