SlideShare a Scribd company logo
1 of 22
SQL Basics - II
Non-correlated Sub query
USE AdventureWorks
SELECT SalesPersonID,
SalesQuota CurrentSalesQuota
FROM Sales.SalesPerson
WHERE SalesQuota IN
(SELECT MAX(SalesQuota)
FROM Sales.SalesPerson)
UNION
USE AdventureWorks
SELECT SalesPersonID, GETDATE() QuotaDate,
SalesQuota FROM Sales.SalesPerson
WHERE SalesQuota > 0
UNION
SELECT SalesPersonID, QuotaDate, SalesQuota
FROM Sales.SalesPersonQuotaHistory
WHERE SalesQuota > 0
ORDER BY SalesPersonID DESC, QuotaDate DESC
Combining Result Sets
with UNION
•The UNION operator is used to append the results of two or
more SELECT statements into a single result set
•Each SELECT statement being merged must have the same
number of columns, with the same or compatible data types
in the same order
Table Valued Function
USE AdventureWorks
GO
CREATE FUNCTION dbo.fn_WorkOrderRouting
(@WorkOrderID int) RETURNS TABLE
AS
RETURN
SELECT WorkOrderID,ProductID,OperationSequence,LocationID
FROM Production.WorkOrderRouting
WHERE WorkOrderID = @WorkOrderID
GO
Using CROSS APPLY
USE AdventureWorks
GO
SELECT
w.WorkOrderID,w.OrderQty,r.ProductID,r.OperationSequence
FROM Production.WorkOrder w
CROSS APPLY dbo.fn_WorkOrderRouting
(w.WorkOrderID) AS r
ORDER BY w.WorkOrderID,w.OrderQty,r.ProductID
APPLY
•APPLY is used to invoke a table-valued function for each row
of an outer query
•CROSS APPLY works like an INNER JOIN in that unmatched
rows between the left table and the table-valued function
don’t appear in the result set
•OUTER APPLY is like an OUTER JOIN, in that mismatched
rows are still returned in the result set with NULL values in
the function results.
EXCEPT and INTERCEPT
-- First two new tables based on ProductionProduct will be created
USE AdventureWorks
GO
SELECT prod.ProductID,
prod.Name
INTO dbo.TableA
FROM
(SELECT ProductID,
Name,
ROW_NUMBER() OVER (ORDER BY ProductID) RowNum
FROM Production.Product) prod
Create second table
USE AdventureWorks
GO
-- Create TableB
SELECT prod.ProductID,
prod.Name
INTO dbo.TableB
FROM
(SELECT ProductID,
Name,
ROW_NUMBER() OVER (ORDER BY ProductID) RowNum
FROM Production.Product) prod
WHERE RowNum BETWEEN 10 and 29
EXCEPT
USE AdventureWorks
GO
SELECT ProductID,
Name
FROM TableA
EXCEPT
SELECT ProductID,
Name
FROM TableB
INTERSECT
USE AdventureWorks
GO
SELECT ProductID,Name
FROM TableA
INTERSECT
SELECT ProductID,Name
FROM TableB
CUBE
USE AdventureWorks
GO
SELECT i.Shelf,
SUM(i.Quantity) Total
FROM Production.ProductInventory i
GROUP BY i.Shelf
WITH CUBE
What is CUBE ?
•WITH CUBE is used to aggregate values for each
grouping combination
•WITH CUBE is often used for reporting purposes,
providing an easy method of reporting totals by
grouped column
GROUPING with CUBE
USE AdventureWorks
GO
SELECT i.Shelf,
GROUPING(i.Shelf) Source,
SUM(i.Quantity) Total
FROM Production.ProductInventory i
GROUP BY i.Shelf
WITH CUBE
ROLLUP
USE AdventureWorks
GO
SELECT i.Shelf, p.Name,
SUM(i.Quantity) Total FROM Production.ProductInventory i
INNER JOIN Production.Product p ON
i.ProductID = p.ProductID
GROUP BY i.Shelf, p.Name
WITH ROLLUP
What is ROLLUP ?
WITH ROLLUP is used in conjunction with GROUP BY to add
hierarchical data summaries based on the ordering of
columns in the GROUP BY clause
HINTS
•SQL Server’s query optimization process is
responsible for producing a query execution plan when
a SELECT query is executed
•Under rare circumstances SQL Server may choose an
inefficient plan over a more efficient one
•After researching the query performance, you may
decide to override the decision making process of the
SQL Server query optimizer by using hints
JOINT Hints
A join hint will force the query optimizer to join the
tables in the way you command
JOIN without hint
USE AdventureWorks
GO
SET SHOWPLAN_TEXT ON
GO
SELECT p.Name,r.ReviewerName,r.Rating
FROM Production.Product p
INNER JOIN Production.ProductReview r ON
r.ProductID = p.ProductID
GO
SET SHOWPLAN_TEXT OFF
GO
JOIN with hint
USE AdventureWorks
GO
SET SHOWPLAN_TEXT ON
GO
SELECT p.Name,r.ReviewerName,
r.Rating
FROM Production.Product p
INNER HASH JOIN Production.ProductReview r ON
r.ProductID = p.ProductID
GO
SET SHOWPLAN_TEXT OFF
GO
Query with hint
USE AdventureWorks
GO
SELECT SalesOrderID,
ProductID,
UnitPrice,
OrderQty
FROM Sales.SalesOrderDetail
WHERE CarrierTrackingNumber = '5CE9-4D75-8F'
ORDER BY SalesOrderID,
ProductID
OPTION (RECOMPILE)
Table hint
USE AdventureWorks
GO
SELECT DocumentID,
Title
FROM Production.Document
WITH (NOLOCK)
WHERE Status = 1

More Related Content

Viewers also liked

Database Management Systems (DBMS)
Database Management Systems (DBMS)Database Management Systems (DBMS)
Database Management Systems (DBMS)
Dimara Hakim
 
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
SlideShare
 

Viewers also liked (20)

MS Sql Server: Creating A Database
MS Sql Server: Creating A DatabaseMS Sql Server: Creating A Database
MS Sql Server: Creating A Database
 
Sql Server 2012
Sql Server 2012Sql Server 2012
Sql Server 2012
 
Sql server basics
Sql server basicsSql server basics
Sql server basics
 
Sql Server Basics
Sql Server BasicsSql Server Basics
Sql Server Basics
 
MS Sql Server: Introduction To Database Concepts
MS Sql Server: Introduction To Database ConceptsMS Sql Server: Introduction To Database Concepts
MS Sql Server: Introduction To Database Concepts
 
SQL : introduction
SQL : introductionSQL : introduction
SQL : introduction
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands
 
Database Management Systems (DBMS)
Database Management Systems (DBMS)Database Management Systems (DBMS)
Database Management Systems (DBMS)
 
Sql ppt
Sql pptSql ppt
Sql ppt
 
Data Base Management System
Data Base Management SystemData Base Management System
Data Base Management System
 
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
 
Basic DBMS ppt
Basic DBMS pptBasic DBMS ppt
Basic DBMS ppt
 
A must Sql notes for beginners
A must Sql notes for beginnersA must Sql notes for beginners
A must Sql notes for beginners
 
Dbms slides
Dbms slidesDbms slides
Dbms slides
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
 
What Makes Great Infographics
What Makes Great InfographicsWhat Makes Great Infographics
What Makes Great Infographics
 
You Suck At PowerPoint!
You Suck At PowerPoint!You Suck At PowerPoint!
You Suck At PowerPoint!
 
STOP! VIEW THIS! 10-Step Checklist When Uploading to Slideshare
STOP! VIEW THIS! 10-Step Checklist When Uploading to SlideshareSTOP! VIEW THIS! 10-Step Checklist When Uploading to Slideshare
STOP! VIEW THIS! 10-Step Checklist When Uploading to Slideshare
 
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
 

Similar to Sql basics 2

e computer notes - Enhancements to the group by clause
e computer notes - Enhancements to the group by clausee computer notes - Enhancements to the group by clause
e computer notes - Enhancements to the group by clause
ecomputernotes
 
In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engine
WO Community
 
How to Sharpen Your Investigative Analysis with PowerPivot
How to Sharpen Your Investigative Analysis with PowerPivotHow to Sharpen Your Investigative Analysis with PowerPivot
How to Sharpen Your Investigative Analysis with PowerPivot
Carmen Mardiros
 
e computer notes - Aggregating data using group functions
e computer notes -  Aggregating data using group functionse computer notes -  Aggregating data using group functions
e computer notes - Aggregating data using group functions
ecomputernotes
 

Similar to Sql basics 2 (20)

e computer notes - Enhancements to the group by clause
e computer notes - Enhancements to the group by clausee computer notes - Enhancements to the group by clause
e computer notes - Enhancements to the group by clause
 
Les17
Les17Les17
Les17
 
Oracle Database Advanced Querying
Oracle Database Advanced QueryingOracle Database Advanced Querying
Oracle Database Advanced Querying
 
Les04
Les04Les04
Les04
 
Oracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic FunctionsOracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic Functions
 
In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engine
 
Oracle Database Advanced Querying (2016)
Oracle Database Advanced Querying (2016)Oracle Database Advanced Querying (2016)
Oracle Database Advanced Querying (2016)
 
Business Intelligence Portfolio
Business Intelligence PortfolioBusiness Intelligence Portfolio
Business Intelligence Portfolio
 
How to Sharpen Your Investigative Analysis with PowerPivot
How to Sharpen Your Investigative Analysis with PowerPivotHow to Sharpen Your Investigative Analysis with PowerPivot
How to Sharpen Your Investigative Analysis with PowerPivot
 
Oracle: Functions
Oracle: FunctionsOracle: Functions
Oracle: Functions
 
Oracle: Functions
Oracle: FunctionsOracle: Functions
Oracle: Functions
 
Monoids, Store, and Dependency Injection - Abstractions for Spark Streaming Jobs
Monoids, Store, and Dependency Injection - Abstractions for Spark Streaming JobsMonoids, Store, and Dependency Injection - Abstractions for Spark Streaming Jobs
Monoids, Store, and Dependency Injection - Abstractions for Spark Streaming Jobs
 
The art of querying – newest and advanced SQL techniques
The art of querying – newest and advanced SQL techniquesThe art of querying – newest and advanced SQL techniques
The art of querying – newest and advanced SQL techniques
 
Simplifying SQL with CTE's and windowing functions
Simplifying SQL with CTE's and windowing functionsSimplifying SQL with CTE's and windowing functions
Simplifying SQL with CTE's and windowing functions
 
e computer notes - Aggregating data using group functions
e computer notes -  Aggregating data using group functionse computer notes -  Aggregating data using group functions
e computer notes - Aggregating data using group functions
 
RxSwift to Combine
RxSwift to CombineRxSwift to Combine
RxSwift to Combine
 
How to work with Subquery in Data Mining?
How to work with Subquery in Data Mining?How to work with Subquery in Data Mining?
How to work with Subquery in Data Mining?
 
RxSwift to Combine
RxSwift to CombineRxSwift to Combine
RxSwift to Combine
 
Explaining the explain_plan
Explaining the explain_planExplaining the explain_plan
Explaining the explain_plan
 
CodingSerbia2014-JavaVSPig
CodingSerbia2014-JavaVSPigCodingSerbia2014-JavaVSPig
CodingSerbia2014-JavaVSPig
 

More from rchakra (12)

Requirement management presentation to a software team
Requirement management presentation to a software teamRequirement management presentation to a software team
Requirement management presentation to a software team
 
Subversion client
Subversion clientSubversion client
Subversion client
 
Subversion
SubversionSubversion
Subversion
 
Sql 2005 the ranking functions
Sql 2005   the ranking functionsSql 2005   the ranking functions
Sql 2005 the ranking functions
 
T-Sql basics
T-Sql basicsT-Sql basics
T-Sql basics
 
Sql architecture
Sql architectureSql architecture
Sql architecture
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NET
 
Intro to Microsoft.NET
Intro to Microsoft.NET Intro to Microsoft.NET
Intro to Microsoft.NET
 
Object oriented programming systems
Object oriented programming systemsObject oriented programming systems
Object oriented programming systems
 
Subversion Admin
Subversion AdminSubversion Admin
Subversion Admin
 
Intro to UML 2
Intro to UML 2Intro to UML 2
Intro to UML 2
 
Intro To .Net Threads
Intro To .Net ThreadsIntro To .Net Threads
Intro To .Net Threads
 

Sql basics 2

  • 2. Non-correlated Sub query USE AdventureWorks SELECT SalesPersonID, SalesQuota CurrentSalesQuota FROM Sales.SalesPerson WHERE SalesQuota IN (SELECT MAX(SalesQuota) FROM Sales.SalesPerson)
  • 3. UNION USE AdventureWorks SELECT SalesPersonID, GETDATE() QuotaDate, SalesQuota FROM Sales.SalesPerson WHERE SalesQuota > 0 UNION SELECT SalesPersonID, QuotaDate, SalesQuota FROM Sales.SalesPersonQuotaHistory WHERE SalesQuota > 0 ORDER BY SalesPersonID DESC, QuotaDate DESC
  • 4. Combining Result Sets with UNION •The UNION operator is used to append the results of two or more SELECT statements into a single result set •Each SELECT statement being merged must have the same number of columns, with the same or compatible data types in the same order
  • 5. Table Valued Function USE AdventureWorks GO CREATE FUNCTION dbo.fn_WorkOrderRouting (@WorkOrderID int) RETURNS TABLE AS RETURN SELECT WorkOrderID,ProductID,OperationSequence,LocationID FROM Production.WorkOrderRouting WHERE WorkOrderID = @WorkOrderID GO
  • 6. Using CROSS APPLY USE AdventureWorks GO SELECT w.WorkOrderID,w.OrderQty,r.ProductID,r.OperationSequence FROM Production.WorkOrder w CROSS APPLY dbo.fn_WorkOrderRouting (w.WorkOrderID) AS r ORDER BY w.WorkOrderID,w.OrderQty,r.ProductID
  • 7. APPLY •APPLY is used to invoke a table-valued function for each row of an outer query •CROSS APPLY works like an INNER JOIN in that unmatched rows between the left table and the table-valued function don’t appear in the result set •OUTER APPLY is like an OUTER JOIN, in that mismatched rows are still returned in the result set with NULL values in the function results.
  • 8. EXCEPT and INTERCEPT -- First two new tables based on ProductionProduct will be created USE AdventureWorks GO SELECT prod.ProductID, prod.Name INTO dbo.TableA FROM (SELECT ProductID, Name, ROW_NUMBER() OVER (ORDER BY ProductID) RowNum FROM Production.Product) prod
  • 9. Create second table USE AdventureWorks GO -- Create TableB SELECT prod.ProductID, prod.Name INTO dbo.TableB FROM (SELECT ProductID, Name, ROW_NUMBER() OVER (ORDER BY ProductID) RowNum FROM Production.Product) prod WHERE RowNum BETWEEN 10 and 29
  • 10. EXCEPT USE AdventureWorks GO SELECT ProductID, Name FROM TableA EXCEPT SELECT ProductID, Name FROM TableB
  • 11. INTERSECT USE AdventureWorks GO SELECT ProductID,Name FROM TableA INTERSECT SELECT ProductID,Name FROM TableB
  • 12. CUBE USE AdventureWorks GO SELECT i.Shelf, SUM(i.Quantity) Total FROM Production.ProductInventory i GROUP BY i.Shelf WITH CUBE
  • 13. What is CUBE ? •WITH CUBE is used to aggregate values for each grouping combination •WITH CUBE is often used for reporting purposes, providing an easy method of reporting totals by grouped column
  • 14. GROUPING with CUBE USE AdventureWorks GO SELECT i.Shelf, GROUPING(i.Shelf) Source, SUM(i.Quantity) Total FROM Production.ProductInventory i GROUP BY i.Shelf WITH CUBE
  • 15. ROLLUP USE AdventureWorks GO SELECT i.Shelf, p.Name, SUM(i.Quantity) Total FROM Production.ProductInventory i INNER JOIN Production.Product p ON i.ProductID = p.ProductID GROUP BY i.Shelf, p.Name WITH ROLLUP
  • 16. What is ROLLUP ? WITH ROLLUP is used in conjunction with GROUP BY to add hierarchical data summaries based on the ordering of columns in the GROUP BY clause
  • 17. HINTS •SQL Server’s query optimization process is responsible for producing a query execution plan when a SELECT query is executed •Under rare circumstances SQL Server may choose an inefficient plan over a more efficient one •After researching the query performance, you may decide to override the decision making process of the SQL Server query optimizer by using hints
  • 18. JOINT Hints A join hint will force the query optimizer to join the tables in the way you command
  • 19. JOIN without hint USE AdventureWorks GO SET SHOWPLAN_TEXT ON GO SELECT p.Name,r.ReviewerName,r.Rating FROM Production.Product p INNER JOIN Production.ProductReview r ON r.ProductID = p.ProductID GO SET SHOWPLAN_TEXT OFF GO
  • 20. JOIN with hint USE AdventureWorks GO SET SHOWPLAN_TEXT ON GO SELECT p.Name,r.ReviewerName, r.Rating FROM Production.Product p INNER HASH JOIN Production.ProductReview r ON r.ProductID = p.ProductID GO SET SHOWPLAN_TEXT OFF GO
  • 21. Query with hint USE AdventureWorks GO SELECT SalesOrderID, ProductID, UnitPrice, OrderQty FROM Sales.SalesOrderDetail WHERE CarrierTrackingNumber = '5CE9-4D75-8F' ORDER BY SalesOrderID, ProductID OPTION (RECOMPILE)
  • 22. Table hint USE AdventureWorks GO SELECT DocumentID, Title FROM Production.Document WITH (NOLOCK) WHERE Status = 1