SlideShare a Scribd company logo
Enhancements in
DML and XML DML
4
New Features of SQL Server 2008 / Session 4 2
Introduction

Some enhancements to Transact-SQL in DML
statements are:

Table value constructors

Table-valued parameters

MERGE statement

Enhanced GROUP BY clause, ROLLUP, and
CUBE operations

Enhanced XML SQL data type and XML
schema
New Features of SQL Server 2008 / Session 4 3
Table Value Constructor 1-4
VALUES ( <row value expression list> ) [ ,...n ]
<row value expression list> ::=
{<row value expression> } [ ,...n ]
<row value expression> ::=
{ DEFAULT | NULL | expression }
Syntax
where,
VALUES: row value expression lists enclosed in
parentheses and separated by a comma
DEFAULT: inserts the default value defined for a column
if defined, otherwise, NULL
expression: can be a constant, a variable, or an
expression

Are also called row constructors

Allows to add multiple rows to a table using a
single INSERT statement
New Features of SQL Server 2008 / Session 4 4
Table Value Constructor 2-4
Example
--Inserting multiple rows using table value constructor
INSERT INTO Customer (CustomerId, Name, Grade, Rank) VALUES
(1 , 'Timothy Brown','A', 1),
(2 , 'Ambrose Pears' ,'B', 1),
(3 , 'Betty Scott', 'A', 2)
Here, using only a single INSERT statement, three rows have been
inserted. This is because of table value constructors.
Output
New Features of SQL Server 2008 / Session 4 5
Table Value Constructor 3-4

Features:

Table value constructor allows to insert
maximum 1000 rows

To insert more than 1000 rows, use:

multiple INSERT statements

bcp utility

BULK INSERT statement

Can also be used to insert multiple rows
having DEFAULT and NULL columns
New Features of SQL Server 2008 / Session 4 6
Table Value Constructor 3-4
Example
INSERT INTO Customer VALUES
(14, 'Weng Lee', NULL, 12),
(15, 'Rose Sanders', 'B', NULL),
(16, 'Mark Preston', NULL, NULL),
(17, 'Rob Mallory', 'A', 11)
For the first customer, the grade is optional, for the
second, the rank is optional, for the third both are
optional and for the last, both are specified.
Output
New Features of SQL Server 2008 / Session 4 7
Table-Valued Parameters 1-3

Enables multiple rows of data to be sent to a
stored procedure

Need not use several parameters, XML, or
temporary tables to pass multiple rows of data

Very tedious in earlier versions of SQL Server
New Features of SQL Server 2008 / Session 4 8
Table-Valued Parameters 2-3

Is newly introduced in SQL Server 2008

Minimizes the additional server-side processing

Allows to create a variable of type table and pass
it to a stored procedure

Must be declared with READONLY attribute

Are actually temporary tables that are stored on
the server

Support both joins and queries
where,
schema_name: is the schema name
type_name: is the user-defined type name or alias type
<column_definition>: defines the columns for a
user-defined table type
<table_constraint>: can be PRIMARY KEY, UNIQUE, or
CHECK
CREATE TYPE [ schema_name. ] type_name
{
AS TABLE ( { <column_definition> }
[ <table_constraint> ] [ ,...n ] )
} [ ; ]
SyntaxThe following example creates a table type, called
EmployeeType.
Example
--Creating a TABLE type named EmployeeType
CREATE TYPE EmployeeType
AS TABLE
(EmployeeId int, Name varchar(50), Salary int,
DepartmentId int);
New Features of SQL Server 2008 / Session 4 9
Table-Valued Parameters 3-3
--Creating stored procedure with table valued parameter of type
--EmployeeType
CREATE PROCEDURE AddEmployee (@EmployeeList EmployeeType READONLY)
AS
SELECT * FROM @EmployeeList
GO
--Creating variable of type EmployeeType and populating it with
--values
DECLARE @EmployeeTable EmployeeType;
INSERT INTO @EmployeeTable VALUES
(4, 'Ethel George', 75000, 2);
INSERT INTO @EmployeeTable VALUES
(5, 'Robert Bernstein', 50000, 2);
--Passing the variable as an argument to the stored procedure
EXEC AddEmployee @EmployeeTable
OutputA stored procedure, AddEmployee, is created and a
variable, EmployeeList, of type EmployeeType is
passed to it.
EmployeeList is a table-valued parameter.
New Features of SQL Server 2008 / Session 4 10
MERGE Statement 1-3

Allows to maintain a target table based on join
conditions on a source table using a single
statement

Enables to perform following in one MERGE
statement:

Insert a new row from the source if the row is missing
in the target

Update a target row if a record already exists in the
source table

Delete a target row if the row is missing in the source
table
New Features of SQL Server 2008 / Session 4 11
MERGE Statement 2-3
MERGE target_table USING source_table
ON match_condition WHEN MATCHED THEN UPDATE SET Col1 =
val1 [, Col2 = val2...]
WHEN [TARGET] NOT MATCHED THEN INSERT (Col1 [,Col2...]
VALUES (Val1 [,Val2...])
WHEN NOT MATCHED BY SOURCE THEN DELETE [OUTPUT $action,
Inserted.Col1, Deleted.Col1,...] ;
Syntax
where,
target_table: is the table where changes are being made
source_table: is the table from which rows will be inserted, updated,
or deleted into target table
match_conditions: are the JOIN conditions and any other
comparison operators
MATCHED: true if a row in the target_table and source_table matches
the match_condition
NOT MATCHED: true if a row from the source_table does not exist in the
target_table
SOURCE NOT MATCHED: true if a row exists in the target_table but not in
the source_table
OUTPUT: An optional clause that allows to view those records that have
been inserted/deleted/updated in target_table
MERGE statements are terminated with a semi-colon (;)
New Features of SQL Server 2008 / Session 4 12
MERGE Statement 3-3
Example
--Create a MERGE statement with CustomerMaster as
target table and CustomerTemp as source table
MERGE INTO CustomerMaster AS T USING CustomerTemp AS
S ON T.CustomerId = S.CustomerId
WHEN MATCHED THEN UPDATE SET T.Name = S.Name,
T.ContactNumber = S.ContactNumber WHEN NOT MATCHED
THEN INSERT (CustomerId, Name, ContactNumber) VALUES
(S.CustomerId, S.Name, S.ContactNumber)
WHEN NOT MATCHED BY SOURCE THEN DELETE
--Display the results
OUTPUT $action, Inserted.CustomerId, Inserted.Name,
Deleted.CustomerId, Deleted.Name;
In this code, CustomerTemp and CustomerMaster table are the
source and target tables respectively. The match condition is the column,
CustomerId, of both tables. If the match condition evaluates to false
(NOT MATCHED), then new records are inserted in the target table.
If match condition evaluates to true (MATCHED), then records are updated
into the target table from the source table.
If records present in the target table do not match with those of source
table (NOT MATCHED BY SOURCE), then these are deleted from the target
table.
The last statement displays a report consisting of rows that were inserted/
updated/ deleted as shown in the output.
Output
New Features of SQL Server 2008 / Session 4 13
“GROUPING SETS” 1-2

Supports aggregation of multiple column
groupings and an optional grand total

More efficient to use GROUPING SETS
operators than multiple GROUP BY with
UNION clauses
where,
grouping set list: consists of one or more
columns, separated by commas
A pair of parentheses, (), without any column name
denotes grand total.
GROUP BY
GROUPING SETS ( <grouping set list> )
Syntax
New Features of SQL Server 2008 / Session 4 14
“GROUPING SETS” 2-2
The example uses GROUPING SETS to display average marks
for every student. NULL values in Name indicate average marks
for every student. NULL value in both Id and Name columns
indicate grand total.
Example
SELECT Id, Name, AVG(Marks) Marks FROM Students
GROUP BY GROUPING SETS
(
(Id, Name, Marks),
(Id),
()
)
Output
New Features of SQL Server 2008 / Session 4 15
"ROLLUP()", "CUBE()", and "GROUPING_ID()” 1-6

ROLLUP()

Is used with GROUP BY clause and can generate
aggregate rows, super-aggregate rows, or
cumulative rows, and a grand total row

Returns n + 1 groupings including a grand total
row, where n denotes number of grouping
elements

Changing of column order changes the output of
ROLLUP()
SELECT a, b, c, function ( <expression> )
FROM <object>
GROUP BY ROLLUP (a,b,c)
Syntax
where,
a, b, c: are elements in composite column list
function: is an SQL function, such as avg(), sum()
<expression>: is an SQL expression

GROUPING_ID() function – newly
introduced

Existing ROLLUP() and CUBE()
operators - enhanced
New Features of SQL Server 2008 / Session 4 16
"ROLLUP()", "CUBE()", and "GROUPING_ID()” 2-6
Example
SELECT DepartmentId, EmployeeId, Avg(Salary) AS
Average_Salary FROM Employee
GROUP BY ROLLUP (DepartmentId, EmployeeId);
Output
New Features of SQL Server 2008 / Session 4 17
"ROLLUP()", "CUBE()", and "GROUPING_ID()” 3-6

CUBE()

Is used with GROUP BY clause

Can generate a grouping of all permutations of
elements in the <composite element list>
present in GROUP BY clause

Number of groupings after performing CUBE
operation equals 2n, where n is the number of
elements in the <composite element list>

Column order does not change the output of
CUBE()
SELECT a, b, c, function ( <expression> )
FROM <object>
GROUP BY ROLLUP (a,b,c)
Syntax
It generates one row for each unique combination of values of
(a, b, c), (a, b), (a, c), (b, c), (a), (b), and (c).
It also calculates a subtotal for each row and a grand total row.
New Features of SQL Server 2008 / Session 4 18
"ROLLUP()", "CUBE()", and "GROUPING_ID()” 4-6
Example
Output
SELECT EmployeeId, DepartmentId, Avg(Salary) AS
Average_Salary FROM Employee GROUP BY CUBE
(EmployeeId, DepartmentId);
New Features of SQL Server 2008 / Session 4 19
"ROLLUP()", "CUBE()", and "GROUPING_ID()” 5-6

GROUPING ID()

Is a function used to find out the grouping set
responsible for producing a particular result row

One can provide all those elements as input to
the function that were used in a grouping set
after a ROLLUP or CUBE operation

Returns a unique integer for each grouping set
that can be used to filter out all unrelated rows
and display only relevant rows
GROUPING_ID()
GROUPING_ID ( <column_expression> [ ,...n ] )
Syntax
where,
<column_expression>: A column expression used in
a GROUP BY clause
New Features of SQL Server 2008 / Session 4 20
"ROLLUP()", "CUBE()", and "GROUPING_ID()” 6-6
Example
SELECT GROUPING_ID(EmployeeId, DepartmentId) AS
GROUP_ID, EmployeeId,
DepartmentId, Avg(Salary) as Average_Salary
FROM Employee
GROUP BY CUBE (EmployeeId, DepartmentId)
HAVING GROUPING_ID(EmployeeId, DepartmentId) > 0;
Output
New Features of SQL Server 2008 / Session 4 21
GROUPING SETS Algebra 1-2
The example contains a combination of two
GROUPING SETS in the GROUP BY clause.
Example
SELECT Id, Name, AVG(Marks) AverageMarks FROM Students
GROUP BY
GROUPING SETS
(
(Id, Marks),
()
),
GROUPING SETS
(
(Name)
);
Output
 A query can have multiple GROUPING
SETS with a GROUP BY clause
 Separate GROUPING SETS clauses by
commas
 A comma represents a Cartesian product
between two GROUPING SETS clauses
New Features of SQL Server 2008 / Session 4 22
GROUPING SETS Algebra 2-2
Example
SELECT Id, Name, AVG(Marks) AverageMarks FROM Students
GROUP BY
GROUPING SETS
(
(Id, Marks, Name),
(Name)
);
The query in the example is equivalent to the Cartesian product of
two GROUPING SETS clauses.
Name is combined with each of the other groups:
Output

More Related Content

What's hot

SQL
SQLSQL
Sql wksht-3
Sql wksht-3Sql wksht-3
Sql wksht-3
Mukesh Tekwani
 
DDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsDDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and Joins
Ashwin Dinoriya
 
Sql DML
Sql DMLSql DML
Sql DML
Vikas Gupta
 
Sql ch 5
Sql ch 5Sql ch 5
Sql ch 5
Mukesh Tekwani
 
Sql dml & tcl 2
Sql   dml & tcl 2Sql   dml & tcl 2
Sql dml & tcl 2
Dr. C.V. Suresh Babu
 
1. dml select statement reterive data
1. dml select statement reterive data1. dml select statement reterive data
1. dml select statement reterive data
Amrit Kaur
 
Sql commands
Sql commandsSql commands
Sql wksht-6
Sql wksht-6Sql wksht-6
Sql wksht-6
Mukesh Tekwani
 
Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)
Achmad Solichin
 
Oracle SQL DML Statements
Oracle SQL DML StatementsOracle SQL DML Statements
Oracle SQL DML Statements
A Data Guru
 
Sql
SqlSql
Merging data (1)
Merging data (1)Merging data (1)
Merging data (1)
Ris Fernandez
 
The Database Environment Chapter 8
The Database Environment Chapter 8The Database Environment Chapter 8
The Database Environment Chapter 8
Jeanie Arnoco
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functions
Vikas Gupta
 
SQL Fundamentals
SQL FundamentalsSQL Fundamentals
SQL Fundamentals
Brian Foote
 
Module 3
Module 3Module 3
Module 3
cs19club
 
Chap 7
Chap 7Chap 7
Chap 7
Karan Patil
 
Ch04
Ch04Ch04
Ch04
cs19club
 
Ch05
Ch05Ch05
Ch05
cs19club
 

What's hot (20)

SQL
SQLSQL
SQL
 
Sql wksht-3
Sql wksht-3Sql wksht-3
Sql wksht-3
 
DDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsDDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and Joins
 
Sql DML
Sql DMLSql DML
Sql DML
 
Sql ch 5
Sql ch 5Sql ch 5
Sql ch 5
 
Sql dml & tcl 2
Sql   dml & tcl 2Sql   dml & tcl 2
Sql dml & tcl 2
 
1. dml select statement reterive data
1. dml select statement reterive data1. dml select statement reterive data
1. dml select statement reterive data
 
Sql commands
Sql commandsSql commands
Sql commands
 
Sql wksht-6
Sql wksht-6Sql wksht-6
Sql wksht-6
 
Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)
 
Oracle SQL DML Statements
Oracle SQL DML StatementsOracle SQL DML Statements
Oracle SQL DML Statements
 
Sql
SqlSql
Sql
 
Merging data (1)
Merging data (1)Merging data (1)
Merging data (1)
 
The Database Environment Chapter 8
The Database Environment Chapter 8The Database Environment Chapter 8
The Database Environment Chapter 8
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functions
 
SQL Fundamentals
SQL FundamentalsSQL Fundamentals
SQL Fundamentals
 
Module 3
Module 3Module 3
Module 3
 
Chap 7
Chap 7Chap 7
Chap 7
 
Ch04
Ch04Ch04
Ch04
 
Ch05
Ch05Ch05
Ch05
 

Viewers also liked

Physical Tharapist
Physical Tharapist Physical Tharapist
Physical Tharapist
ABUENO52
 
111214 hospital la-fe-spain-mind_byte_presentation
111214 hospital la-fe-spain-mind_byte_presentation111214 hospital la-fe-spain-mind_byte_presentation
111214 hospital la-fe-spain-mind_byte_presentation
Serafin Arroyo
 
Cancer drug could help fight parkinson's
Cancer drug could help fight parkinson'sCancer drug could help fight parkinson's
Cancer drug could help fight parkinson's
Other Mother
 
Schizophrenia
SchizophreniaSchizophrenia
Schizophrenia
Schizophrenia 101
 
Lynching in america
Lynching in americaLynching in america
Lynching in america
Mohamed Taleb
 
PALEA
PALEAPALEA
Printcatalog229594
Printcatalog229594Printcatalog229594
Printcatalog229594
ozwashroom
 
School of social work faith based community collaborative visual
School of social work faith based community collaborative visualSchool of social work faith based community collaborative visual
School of social work faith based community collaborative visual
juanbtoribio
 
Courses
CoursesCourses
Courses
Paige Hannah
 
Robert koch
Robert kochRobert koch
Robert koch
shibushabeeb
 

Viewers also liked (10)

Physical Tharapist
Physical Tharapist Physical Tharapist
Physical Tharapist
 
111214 hospital la-fe-spain-mind_byte_presentation
111214 hospital la-fe-spain-mind_byte_presentation111214 hospital la-fe-spain-mind_byte_presentation
111214 hospital la-fe-spain-mind_byte_presentation
 
Cancer drug could help fight parkinson's
Cancer drug could help fight parkinson'sCancer drug could help fight parkinson's
Cancer drug could help fight parkinson's
 
Schizophrenia
SchizophreniaSchizophrenia
Schizophrenia
 
Lynching in america
Lynching in americaLynching in america
Lynching in america
 
PALEA
PALEAPALEA
PALEA
 
Printcatalog229594
Printcatalog229594Printcatalog229594
Printcatalog229594
 
School of social work faith based community collaborative visual
School of social work faith based community collaborative visualSchool of social work faith based community collaborative visual
School of social work faith based community collaborative visual
 
Courses
CoursesCourses
Courses
 
Robert koch
Robert kochRobert koch
Robert koch
 

Similar to Sql server ___________session 3(sql 2008)

DML Commands
DML CommandsDML Commands
Sql (DBMS)
Sql (DBMS)Sql (DBMS)
Sql (DBMS)
Saransh Vijay
 
Ch 9 S Q L
Ch 9  S Q LCh 9  S Q L
Ch 9 S Q L
guest8fdbdd
 
Review of SQL
Review of SQLReview of SQL
Review of SQL
Information Technology
 
SQL Query
SQL QuerySQL Query
SQL Query
Imam340267
 
2. DBMS Experiment - Lab 2 Made in SQL Used
2. DBMS Experiment - Lab 2 Made in SQL Used2. DBMS Experiment - Lab 2 Made in SQL Used
2. DBMS Experiment - Lab 2 Made in SQL Used
TheVerse1
 
Exploring collections with example
Exploring collections with exampleExploring collections with example
Exploring collections with example
pranav kumar verma
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commands
Belle Wx
 
chapter 8 SQL.ppt
chapter 8 SQL.pptchapter 8 SQL.ppt
chapter 8 SQL.ppt
YitbarekMurche
 
Query
QueryQuery
SQL
SQLSQL
SQL Overview
SQL OverviewSQL Overview
SQL Overview
Stewart Rogers
 
Lab
LabLab
Adbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queriesAdbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queries
Vaibhav Khanna
 
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
SakkaravarthiS1
 
Database Architecture and Basic Concepts
Database Architecture and Basic ConceptsDatabase Architecture and Basic Concepts
Database Architecture and Basic Concepts
Tony Wong
 
Intro to tsql unit 9
Intro to tsql   unit 9Intro to tsql   unit 9
Intro to tsql unit 9
Syed Asrarali
 
Oraclesql
OraclesqlOraclesql
Oraclesql
Priya Goyal
 
Sql commands
Sql commandsSql commands
Sql commands
Pooja Dixit
 
chap 7.ppt(sql).ppt
chap 7.ppt(sql).pptchap 7.ppt(sql).ppt
chap 7.ppt(sql).ppt
arjun431527
 

Similar to Sql server ___________session 3(sql 2008) (20)

DML Commands
DML CommandsDML Commands
DML Commands
 
Sql (DBMS)
Sql (DBMS)Sql (DBMS)
Sql (DBMS)
 
Ch 9 S Q L
Ch 9  S Q LCh 9  S Q L
Ch 9 S Q L
 
Review of SQL
Review of SQLReview of SQL
Review of SQL
 
SQL Query
SQL QuerySQL Query
SQL Query
 
2. DBMS Experiment - Lab 2 Made in SQL Used
2. DBMS Experiment - Lab 2 Made in SQL Used2. DBMS Experiment - Lab 2 Made in SQL Used
2. DBMS Experiment - Lab 2 Made in SQL Used
 
Exploring collections with example
Exploring collections with exampleExploring collections with example
Exploring collections with example
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commands
 
chapter 8 SQL.ppt
chapter 8 SQL.pptchapter 8 SQL.ppt
chapter 8 SQL.ppt
 
Query
QueryQuery
Query
 
SQL
SQLSQL
SQL
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
Lab
LabLab
Lab
 
Adbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queriesAdbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queries
 
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
 
Database Architecture and Basic Concepts
Database Architecture and Basic ConceptsDatabase Architecture and Basic Concepts
Database Architecture and Basic Concepts
 
Intro to tsql unit 9
Intro to tsql   unit 9Intro to tsql   unit 9
Intro to tsql unit 9
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
Sql commands
Sql commandsSql commands
Sql commands
 
chap 7.ppt(sql).ppt
chap 7.ppt(sql).pptchap 7.ppt(sql).ppt
chap 7.ppt(sql).ppt
 

More from Ehtisham Ali

Android tutorial
Android tutorialAndroid tutorial
Android tutorial
Ehtisham Ali
 
Sql server ___________session_20(ddl triggers)
Sql server  ___________session_20(ddl triggers)Sql server  ___________session_20(ddl triggers)
Sql server ___________session_20(ddl triggers)
Ehtisham Ali
 
Sql server ___________session3-normailzation
Sql server  ___________session3-normailzationSql server  ___________session3-normailzation
Sql server ___________session3-normailzation
Ehtisham Ali
 
Sql server ___________session2-data_modeling
Sql server  ___________session2-data_modelingSql server  ___________session2-data_modeling
Sql server ___________session2-data_modeling
Ehtisham Ali
 
Sql server ___________session_19(triggers)
Sql server  ___________session_19(triggers)Sql server  ___________session_19(triggers)
Sql server ___________session_19(triggers)
Ehtisham Ali
 
Sql server ___________session_18(stored procedures)
Sql server  ___________session_18(stored procedures)Sql server  ___________session_18(stored procedures)
Sql server ___________session_18(stored procedures)
Ehtisham Ali
 
Sql server ___________session_17(indexes)
Sql server  ___________session_17(indexes)Sql server  ___________session_17(indexes)
Sql server ___________session_17(indexes)
Ehtisham Ali
 
Sql server ___________session_16(views)
Sql server  ___________session_16(views)Sql server  ___________session_16(views)
Sql server ___________session_16(views)
Ehtisham Ali
 
Sql server ___________session_15(data integrity)
Sql server  ___________session_15(data integrity)Sql server  ___________session_15(data integrity)
Sql server ___________session_15(data integrity)
Ehtisham Ali
 
Sql server ___________session_11-12(joins)
Sql server  ___________session_11-12(joins)Sql server  ___________session_11-12(joins)
Sql server ___________session_11-12(joins)
Ehtisham Ali
 
Sql server ___________session_10(group by clause)
Sql server  ___________session_10(group by clause)Sql server  ___________session_10(group by clause)
Sql server ___________session_10(group by clause)
Ehtisham Ali
 
Sql server ___________session_1-intro
Sql server  ___________session_1-introSql server  ___________session_1-intro
Sql server ___________session_1-intro
Ehtisham Ali
 
Sql server ___________session 2(sql 2008)
Sql server  ___________session 2(sql 2008)Sql server  ___________session 2(sql 2008)
Sql server ___________session 2(sql 2008)
Ehtisham Ali
 
Sql server ___________session 1(sql 2008)
Sql server  ___________session 1(sql 2008)Sql server  ___________session 1(sql 2008)
Sql server ___________session 1(sql 2008)
Ehtisham Ali
 
Sql server ___________data type of sql server
Sql server  ___________data type of sql serverSql server  ___________data type of sql server
Sql server ___________data type of sql server
Ehtisham Ali
 
Sql server ___________data control language
Sql server  ___________data control languageSql server  ___________data control language
Sql server ___________data control language
Ehtisham Ali
 
Sql server ___________ (advance sql)
Sql server  ___________  (advance sql)Sql server  ___________  (advance sql)
Sql server ___________ (advance sql)
Ehtisham Ali
 

More from Ehtisham Ali (17)

Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
Sql server ___________session_20(ddl triggers)
Sql server  ___________session_20(ddl triggers)Sql server  ___________session_20(ddl triggers)
Sql server ___________session_20(ddl triggers)
 
Sql server ___________session3-normailzation
Sql server  ___________session3-normailzationSql server  ___________session3-normailzation
Sql server ___________session3-normailzation
 
Sql server ___________session2-data_modeling
Sql server  ___________session2-data_modelingSql server  ___________session2-data_modeling
Sql server ___________session2-data_modeling
 
Sql server ___________session_19(triggers)
Sql server  ___________session_19(triggers)Sql server  ___________session_19(triggers)
Sql server ___________session_19(triggers)
 
Sql server ___________session_18(stored procedures)
Sql server  ___________session_18(stored procedures)Sql server  ___________session_18(stored procedures)
Sql server ___________session_18(stored procedures)
 
Sql server ___________session_17(indexes)
Sql server  ___________session_17(indexes)Sql server  ___________session_17(indexes)
Sql server ___________session_17(indexes)
 
Sql server ___________session_16(views)
Sql server  ___________session_16(views)Sql server  ___________session_16(views)
Sql server ___________session_16(views)
 
Sql server ___________session_15(data integrity)
Sql server  ___________session_15(data integrity)Sql server  ___________session_15(data integrity)
Sql server ___________session_15(data integrity)
 
Sql server ___________session_11-12(joins)
Sql server  ___________session_11-12(joins)Sql server  ___________session_11-12(joins)
Sql server ___________session_11-12(joins)
 
Sql server ___________session_10(group by clause)
Sql server  ___________session_10(group by clause)Sql server  ___________session_10(group by clause)
Sql server ___________session_10(group by clause)
 
Sql server ___________session_1-intro
Sql server  ___________session_1-introSql server  ___________session_1-intro
Sql server ___________session_1-intro
 
Sql server ___________session 2(sql 2008)
Sql server  ___________session 2(sql 2008)Sql server  ___________session 2(sql 2008)
Sql server ___________session 2(sql 2008)
 
Sql server ___________session 1(sql 2008)
Sql server  ___________session 1(sql 2008)Sql server  ___________session 1(sql 2008)
Sql server ___________session 1(sql 2008)
 
Sql server ___________data type of sql server
Sql server  ___________data type of sql serverSql server  ___________data type of sql server
Sql server ___________data type of sql server
 
Sql server ___________data control language
Sql server  ___________data control languageSql server  ___________data control language
Sql server ___________data control language
 
Sql server ___________ (advance sql)
Sql server  ___________  (advance sql)Sql server  ___________  (advance sql)
Sql server ___________ (advance sql)
 

Recently uploaded

Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
Katrina Pritchard
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
imrankhan141184
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
TechSoup
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
HajraNaeem15
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
iammrhaywood
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
Temple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation resultsTemple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation results
Krassimira Luka
 
Constructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective CommunicationConstructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective Communication
Chevonnese Chevers Whyte, MBA, B.Sc.
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
ZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptxZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptx
dot55audits
 
B. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdfB. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdf
BoudhayanBhattachari
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
S. Raj Kumar
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 

Recently uploaded (20)

Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
Temple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation resultsTemple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation results
 
Constructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective CommunicationConstructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective Communication
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
ZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptxZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptx
 
B. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdfB. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdf
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 

Sql server ___________session 3(sql 2008)

  • 2. New Features of SQL Server 2008 / Session 4 2 Introduction  Some enhancements to Transact-SQL in DML statements are:  Table value constructors  Table-valued parameters  MERGE statement  Enhanced GROUP BY clause, ROLLUP, and CUBE operations  Enhanced XML SQL data type and XML schema
  • 3. New Features of SQL Server 2008 / Session 4 3 Table Value Constructor 1-4 VALUES ( <row value expression list> ) [ ,...n ] <row value expression list> ::= {<row value expression> } [ ,...n ] <row value expression> ::= { DEFAULT | NULL | expression } Syntax where, VALUES: row value expression lists enclosed in parentheses and separated by a comma DEFAULT: inserts the default value defined for a column if defined, otherwise, NULL expression: can be a constant, a variable, or an expression  Are also called row constructors  Allows to add multiple rows to a table using a single INSERT statement
  • 4. New Features of SQL Server 2008 / Session 4 4 Table Value Constructor 2-4 Example --Inserting multiple rows using table value constructor INSERT INTO Customer (CustomerId, Name, Grade, Rank) VALUES (1 , 'Timothy Brown','A', 1), (2 , 'Ambrose Pears' ,'B', 1), (3 , 'Betty Scott', 'A', 2) Here, using only a single INSERT statement, three rows have been inserted. This is because of table value constructors. Output
  • 5. New Features of SQL Server 2008 / Session 4 5 Table Value Constructor 3-4  Features:  Table value constructor allows to insert maximum 1000 rows  To insert more than 1000 rows, use:  multiple INSERT statements  bcp utility  BULK INSERT statement  Can also be used to insert multiple rows having DEFAULT and NULL columns
  • 6. New Features of SQL Server 2008 / Session 4 6 Table Value Constructor 3-4 Example INSERT INTO Customer VALUES (14, 'Weng Lee', NULL, 12), (15, 'Rose Sanders', 'B', NULL), (16, 'Mark Preston', NULL, NULL), (17, 'Rob Mallory', 'A', 11) For the first customer, the grade is optional, for the second, the rank is optional, for the third both are optional and for the last, both are specified. Output
  • 7. New Features of SQL Server 2008 / Session 4 7 Table-Valued Parameters 1-3  Enables multiple rows of data to be sent to a stored procedure  Need not use several parameters, XML, or temporary tables to pass multiple rows of data  Very tedious in earlier versions of SQL Server
  • 8. New Features of SQL Server 2008 / Session 4 8 Table-Valued Parameters 2-3  Is newly introduced in SQL Server 2008  Minimizes the additional server-side processing  Allows to create a variable of type table and pass it to a stored procedure  Must be declared with READONLY attribute  Are actually temporary tables that are stored on the server  Support both joins and queries where, schema_name: is the schema name type_name: is the user-defined type name or alias type <column_definition>: defines the columns for a user-defined table type <table_constraint>: can be PRIMARY KEY, UNIQUE, or CHECK CREATE TYPE [ schema_name. ] type_name { AS TABLE ( { <column_definition> } [ <table_constraint> ] [ ,...n ] ) } [ ; ] SyntaxThe following example creates a table type, called EmployeeType. Example --Creating a TABLE type named EmployeeType CREATE TYPE EmployeeType AS TABLE (EmployeeId int, Name varchar(50), Salary int, DepartmentId int);
  • 9. New Features of SQL Server 2008 / Session 4 9 Table-Valued Parameters 3-3 --Creating stored procedure with table valued parameter of type --EmployeeType CREATE PROCEDURE AddEmployee (@EmployeeList EmployeeType READONLY) AS SELECT * FROM @EmployeeList GO --Creating variable of type EmployeeType and populating it with --values DECLARE @EmployeeTable EmployeeType; INSERT INTO @EmployeeTable VALUES (4, 'Ethel George', 75000, 2); INSERT INTO @EmployeeTable VALUES (5, 'Robert Bernstein', 50000, 2); --Passing the variable as an argument to the stored procedure EXEC AddEmployee @EmployeeTable OutputA stored procedure, AddEmployee, is created and a variable, EmployeeList, of type EmployeeType is passed to it. EmployeeList is a table-valued parameter.
  • 10. New Features of SQL Server 2008 / Session 4 10 MERGE Statement 1-3  Allows to maintain a target table based on join conditions on a source table using a single statement  Enables to perform following in one MERGE statement:  Insert a new row from the source if the row is missing in the target  Update a target row if a record already exists in the source table  Delete a target row if the row is missing in the source table
  • 11. New Features of SQL Server 2008 / Session 4 11 MERGE Statement 2-3 MERGE target_table USING source_table ON match_condition WHEN MATCHED THEN UPDATE SET Col1 = val1 [, Col2 = val2...] WHEN [TARGET] NOT MATCHED THEN INSERT (Col1 [,Col2...] VALUES (Val1 [,Val2...]) WHEN NOT MATCHED BY SOURCE THEN DELETE [OUTPUT $action, Inserted.Col1, Deleted.Col1,...] ; Syntax where, target_table: is the table where changes are being made source_table: is the table from which rows will be inserted, updated, or deleted into target table match_conditions: are the JOIN conditions and any other comparison operators MATCHED: true if a row in the target_table and source_table matches the match_condition NOT MATCHED: true if a row from the source_table does not exist in the target_table SOURCE NOT MATCHED: true if a row exists in the target_table but not in the source_table OUTPUT: An optional clause that allows to view those records that have been inserted/deleted/updated in target_table MERGE statements are terminated with a semi-colon (;)
  • 12. New Features of SQL Server 2008 / Session 4 12 MERGE Statement 3-3 Example --Create a MERGE statement with CustomerMaster as target table and CustomerTemp as source table MERGE INTO CustomerMaster AS T USING CustomerTemp AS S ON T.CustomerId = S.CustomerId WHEN MATCHED THEN UPDATE SET T.Name = S.Name, T.ContactNumber = S.ContactNumber WHEN NOT MATCHED THEN INSERT (CustomerId, Name, ContactNumber) VALUES (S.CustomerId, S.Name, S.ContactNumber) WHEN NOT MATCHED BY SOURCE THEN DELETE --Display the results OUTPUT $action, Inserted.CustomerId, Inserted.Name, Deleted.CustomerId, Deleted.Name; In this code, CustomerTemp and CustomerMaster table are the source and target tables respectively. The match condition is the column, CustomerId, of both tables. If the match condition evaluates to false (NOT MATCHED), then new records are inserted in the target table. If match condition evaluates to true (MATCHED), then records are updated into the target table from the source table. If records present in the target table do not match with those of source table (NOT MATCHED BY SOURCE), then these are deleted from the target table. The last statement displays a report consisting of rows that were inserted/ updated/ deleted as shown in the output. Output
  • 13. New Features of SQL Server 2008 / Session 4 13 “GROUPING SETS” 1-2  Supports aggregation of multiple column groupings and an optional grand total  More efficient to use GROUPING SETS operators than multiple GROUP BY with UNION clauses where, grouping set list: consists of one or more columns, separated by commas A pair of parentheses, (), without any column name denotes grand total. GROUP BY GROUPING SETS ( <grouping set list> ) Syntax
  • 14. New Features of SQL Server 2008 / Session 4 14 “GROUPING SETS” 2-2 The example uses GROUPING SETS to display average marks for every student. NULL values in Name indicate average marks for every student. NULL value in both Id and Name columns indicate grand total. Example SELECT Id, Name, AVG(Marks) Marks FROM Students GROUP BY GROUPING SETS ( (Id, Name, Marks), (Id), () ) Output
  • 15. New Features of SQL Server 2008 / Session 4 15 "ROLLUP()", "CUBE()", and "GROUPING_ID()” 1-6  ROLLUP()  Is used with GROUP BY clause and can generate aggregate rows, super-aggregate rows, or cumulative rows, and a grand total row  Returns n + 1 groupings including a grand total row, where n denotes number of grouping elements  Changing of column order changes the output of ROLLUP() SELECT a, b, c, function ( <expression> ) FROM <object> GROUP BY ROLLUP (a,b,c) Syntax where, a, b, c: are elements in composite column list function: is an SQL function, such as avg(), sum() <expression>: is an SQL expression  GROUPING_ID() function – newly introduced  Existing ROLLUP() and CUBE() operators - enhanced
  • 16. New Features of SQL Server 2008 / Session 4 16 "ROLLUP()", "CUBE()", and "GROUPING_ID()” 2-6 Example SELECT DepartmentId, EmployeeId, Avg(Salary) AS Average_Salary FROM Employee GROUP BY ROLLUP (DepartmentId, EmployeeId); Output
  • 17. New Features of SQL Server 2008 / Session 4 17 "ROLLUP()", "CUBE()", and "GROUPING_ID()” 3-6  CUBE()  Is used with GROUP BY clause  Can generate a grouping of all permutations of elements in the <composite element list> present in GROUP BY clause  Number of groupings after performing CUBE operation equals 2n, where n is the number of elements in the <composite element list>  Column order does not change the output of CUBE() SELECT a, b, c, function ( <expression> ) FROM <object> GROUP BY ROLLUP (a,b,c) Syntax It generates one row for each unique combination of values of (a, b, c), (a, b), (a, c), (b, c), (a), (b), and (c). It also calculates a subtotal for each row and a grand total row.
  • 18. New Features of SQL Server 2008 / Session 4 18 "ROLLUP()", "CUBE()", and "GROUPING_ID()” 4-6 Example Output SELECT EmployeeId, DepartmentId, Avg(Salary) AS Average_Salary FROM Employee GROUP BY CUBE (EmployeeId, DepartmentId);
  • 19. New Features of SQL Server 2008 / Session 4 19 "ROLLUP()", "CUBE()", and "GROUPING_ID()” 5-6  GROUPING ID()  Is a function used to find out the grouping set responsible for producing a particular result row  One can provide all those elements as input to the function that were used in a grouping set after a ROLLUP or CUBE operation  Returns a unique integer for each grouping set that can be used to filter out all unrelated rows and display only relevant rows GROUPING_ID() GROUPING_ID ( <column_expression> [ ,...n ] ) Syntax where, <column_expression>: A column expression used in a GROUP BY clause
  • 20. New Features of SQL Server 2008 / Session 4 20 "ROLLUP()", "CUBE()", and "GROUPING_ID()” 6-6 Example SELECT GROUPING_ID(EmployeeId, DepartmentId) AS GROUP_ID, EmployeeId, DepartmentId, Avg(Salary) as Average_Salary FROM Employee GROUP BY CUBE (EmployeeId, DepartmentId) HAVING GROUPING_ID(EmployeeId, DepartmentId) > 0; Output
  • 21. New Features of SQL Server 2008 / Session 4 21 GROUPING SETS Algebra 1-2 The example contains a combination of two GROUPING SETS in the GROUP BY clause. Example SELECT Id, Name, AVG(Marks) AverageMarks FROM Students GROUP BY GROUPING SETS ( (Id, Marks), () ), GROUPING SETS ( (Name) ); Output  A query can have multiple GROUPING SETS with a GROUP BY clause  Separate GROUPING SETS clauses by commas  A comma represents a Cartesian product between two GROUPING SETS clauses
  • 22. New Features of SQL Server 2008 / Session 4 22 GROUPING SETS Algebra 2-2 Example SELECT Id, Name, AVG(Marks) AverageMarks FROM Students GROUP BY GROUPING SETS ( (Id, Marks, Name), (Name) ); The query in the example is equivalent to the Cartesian product of two GROUPING SETS clauses. Name is combined with each of the other groups: Output