Uploaded by Talysson Oliveira

TSQL Cheat Sheet

advertisement
Document to
accompany
TSQL CHEAT SHEET
Document includes example and tips for use of TSQL for delegates who
are using TSQL for Microsoft SQL Server 2005, 2008 and 2008R2.
 SQL 2000
(M2071)
 SQL 2005
(M50027)
 SQL 2008
(M2778)
TSQL Cheat Sheet
Version 1.0 Page 2
Table of Contents
Data Types........................................................................................................................................... 3
Strings ............................................................................................................................................. 3
Dates / Times .................................................................................................................................. 3
Numbers.......................................................................................................................................... 3
Others ............................................................................................................................................. 3
Order of clauses .................................................................................................................................. 4
Single Table Queries............................................................................................................................ 4
ANSI 92 JOINS...................................................................................................................................... 7
Multiple Tables Queries ...................................................................................................................... 8
Windowed Functions ........................................................................................................................ 11
Pivot and Unpivot ............................................................................................................................. 14
Index: ................................................................................................................................................ 16
New features added :
SQL Server 2005 are marked with □,05. SQL Server 2008 and 2008R2 are marked with ○,08.
TSQL Cheat Sheet
Version 1.0 Page 3
Data Types
Strings
Type
Varchar(x)
Char(x)
Nvarchar(x)
Nchar(x)
Dates / Times
Type
DateTime
○,08Date
○,08Time
○,08
DateTimeOffset
Numbers
Type
TinyInt
SmallInt
Int
BigInt
Decimal(x,y)
Float(x)
Others
Type
SQL_Variant
○,08Geography
○,08Geometry
□,05XML
Values
Variable length text string maximum length x
Fixed length text string maximum length x
Variable length text string maximum length x (extended character set – 2 bytes
per character)
Fixed length text string maximum length x (extended character set – 2 bytes per
character)
Values
01/01/1753 00:00:00.000 to 31/12/9999 23:59:59.997
01/01/0001 to 31/12/9999
00:00:00.0000000 to 23:59:59.9999999
01/01/0001 00:00:00.0000000 -14:00 to 31/12/9999 23:59:59.9999999 +14:00
Values
0 to 255 (1 byte)
-32768 to +32767 (2 bytes)
-2,147,483,648 to 2,147,483,647 (4 bytes)
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (8 bytes)
x is total number of figures, y is number of figures after decimal place
x is total number of figures (approximate number i.e. figures like 0.1 cannot be
represented exactly)
Values
The sql_variant data type column can contain any of the data types in SQL Server
except large objects.
Coordinates using global / world longitude and latitude. Can hold point,
linestring, polygon, multipoint, multilinestring, multipolygon and
GeomCollection.
Coordinates using euclidean coordinates (x,y). Can hold point, linestring,
polygon, multipoint, multilinestring, multipolygon and GeomCollection.
Can hold either an XML document or XML collection. Must be well-formed
before entry. It is possible to define an XML Schema to force correctness.
New features added :
SQL Server 2005 are marked with □,05. SQL Server 2008 and 2008R2 are marked with ○,08.
TSQL Cheat Sheet
Version 1.0 Page 4
Order of clauses
SELECT <TOP x <WITH TIES>><TOP x PERCENT><DISTINCT>….columns….
FROM ….table(s)….
WHERE …clauses to reduce number of rows….
GROUP BY ….columns to group by….
HAVING …where clause on aggregates….
ORDER BY ….columns to order by….
Single Table Queries
TSQL example
Simple select
Comparison
(=,<,<=,>,>=)
IN clause
(in the list)
LIKE
BETWEEN
YEAR
SQL Sample
SELECT *
FROM Production.Product
SELECT *
FROM Production.Product
WHERE ProductID = 925
SELECT *
FROM Production.Product
WHERE Color IN (‘Black’,’White’,’Silver’)
SELECT *
FROM Production.Product
WHERE ProductNumber LIKE (‘SR%’)
Notes:
_ (single underscore is any single character)
% (percent sign is any characters 0 or more length)
[A-Z] (any single character within range, in this case A to Z)
[A,B,C,…] (any single character from list)
SELECT *
FROM Production.Product
WHERE SellStartDate between '1/1/2005' and '12/31/2006'
SELECT *
FROM Production.Product
WHERE year(SellStartDate) = 2003
DATEPART
Functions also exist for month and day
SELECT ProductID, SellStartDate, datepart(??,SellStartDate)
FROM Production.Product
IS NULL
Change ?? to the section of the date required [yy=Year, mm=Month, dd=Day,
hh=Hour,mi=Minute,ss=Second,ms=Millisecond]
SELECT *
FROM Production.Product
WHERE Color IS NULL
DO NOT USE = NULL as shown below
SELECT *
FROM Production.Product
WHERE Color = NULL
New features added :
SQL Server 2005 are marked with □,05. SQL Server 2008 and 2008R2 are marked with ○,08.
TSQL Cheat Sheet
TSQL example
NOT IS NULL(1)
NOT IS NULL(2)
Calculations
ISNULL()
function
CONVERT
CONVERT –
Date formatting
Top 10 products
by price
Top 10 products
by price (with
ties)
Top 50% of
products by
price
Number of
products by
colour
Analyse sales by
product
Show products
with sales >
1000
Using datepart
to select hour
CASE statement
(1)
The WHEN
conditions have
independent
boolean results.
Version 1.0 Page 5
SQL Sample
SELECT *
FROM Production.Product
WHERE NOT Color IS NULL
SELECT *
FROM Production.Product
WHERE Color IS NOT NULL
SELECT Name,ListPrice,StandardCost,(ListPrice-StandardCost) as Profit
FROM Production.Product
SELECT FirstName,MiddleName,LastName,
FirstName+’ ‘+ISNULL(MiddleName+’ ‘,’’)+LastName as FullName
FROM Production.Product
SELECT Name + ‘ ( £‘ + CONVERT(varchar(30),ListPrice)+’)’
FROM Production.Product
SELECT Name + ‘ (‘ + CONVERT(varchar(10),SellStartDate,103)+’)’
FROM Production.Product
SELECT TOP 10 *
FROM Production.Product
ORDER BY ListPrice DESC
SELECT TOP 10 WITH TIES *
FROM Production.Product
ORDER BY ListPrice DESC
SELECT TOP 50 PERCENT *
FROM Production.Product
ORDER BY ListPrice DESC
SELECT Color, count(*) as NumberRows
FROM Production.Product
GROUP BY Color
SELECT ProductID, sum(OrderQty) as TotalSold, min(OrderQty) as MinSold,
max(OrderQty) as MaxSold, count(*) as NumberRows
FROM Production.Product
GROUP BY ProductID
SELECT ProductID, sum(OrderQty) as TotalSold, min(OrderQty) as MinSold,
max(OrderQty) as MaxSold, count(*) as NumberRows
FROM Production.Product
GROUP BY ProductID
HAVING sum(OrderQty) > 1000
SELECT StoreID,datepart(hh,SalesDT), sum(SalesValue) as TotalSales
FROM Sales
WHERE SalesDT between '12/21/2010 0:00' and '12/21/2010 23:59'
GROUP BY StoreID,datepart(hh,SalesDT)
SELECT
CASE
WHEN <condition1> THEN <result1>
WHEN <condition2> THEN <result2>
….
WHEN <conditionx> THEN <resultx>
ELSE <result_else>
END AS ColumnName
FROM Table1
New features added :
SQL Server 2005 are marked with □,05. SQL Server 2008 and 2008R2 are marked with ○,08.
TSQL Cheat Sheet
TSQL example
CASE statement
(2)
The WHEN
match the value
of the
columnname.
Version 1.0 Page 6
SQL Sample
SELECT
CASE ColumnName
WHEN <value1> THEN <result1>
WHEN <value2> THEN <result2>
….
WHEN <valuex> THEN <resultx>
ELSE <result_else>
END AS ColumnName
FROM Table1
New features added :
SQL Server 2005 are marked with □,05. SQL Server 2008 and 2008R2 are marked with ○,08.
TSQL Cheat Sheet
Version 1.0 Page 7
ANSI 92 JOINS
ANSI Type
ANSI 92
SQL Sample
 Uses ON clause between the tables
 ON clauses cannot be left out
INNER JOIN
SELECT *
FROM Table1
INNER JOIN Table2
ON Table1.Field = Table2.Field
OUTER JOINS
SELECT *
FROM Table1
<outer join type> JOIN Table2
ON Table1.Field = Table2.Field
<outer join type> = LEFT, RIGHT or FULL
Pre-ANSI 92
CROSS JOIN (CARTESIAN PRODUCT)
SELECT *
FROM Table1 CROSS JOIN Table2
 Uses WHERE clauses to join tables
 WHERE clauses can be left out (sometimes by mistake)
INNER JOIN
SELECT *
FROM Table1, Table2
WHERE Table1.Field = Table2.Field
OUTER JOINS
SELECT *
FROM Table1,Table2
WHERE Table1.Field <special characters – see below> Table2.Field
Special characters:
*=
Left outer join
=*
Right outer join
*=*
Full outer join
CROSS JOIN (CARTESIAN PRODUCT)
SELECT *
FROM Table1,Table2
In pre-ANSI 92 standard the cross join (cartesian) can result from forgetting to
add a WHERE clause. This causes every row from Table1 to match every row
from Table2. For example, given Table 1=100 rows, Table2 = 70000 rows then
result would be 7,000,000 rows in result set.
New features added :
SQL Server 2005 are marked with □,05. SQL Server 2008 and 2008R2 are marked with ○,08.
TSQL Cheat Sheet
Version 1.0 Page 8
Multiple Tables Queries
Join Type
Inner join
Show columns
from both tables
where certain
values match.
In this case
show all
products and
their related
subcategory.
Products
without
subcategories,
or subcategories
without
products are not
shown.
Left join
Show all rows
and columns
from table1 and
columns from
table2 where
certain values
match.
In this case
show all
products
whether they
are attached to
subcategories or
not.
SQL Sample
SELECT *
FROM Production.Product as PP
INNER JOIN Production.ProductSubCategory as PSC
ON PP.ProductSubcategoryID = PSC.ProductSubCategoryID
SELECT *
FROM Production.Product as PP
LEFT JOIN Production.ProductSubCategory as PSC
ON PP.ProductSubcategoryID = PSC.ProductSubCategoryID
New features added :
SQL Server 2005 are marked with □,05. SQL Server 2008 and 2008R2 are marked with ○,08.
TSQL Cheat Sheet
Version 1.0 Page 9
Join Type
Right join
Show all rows
and columns
from table2 and
columns from
table1 where
certain values
match.
SQL Sample
In this case
show all
subcategories
whether they
have products
or not.
Full join
Show columns
from both tables
where certain
values match or
not.
SELECT *
FROM Production.Product as PP
RIGHT JOIN Production.ProductSubCategory as PSC
ON PP.ProductSubcategoryID = PSC.ProductSubCategoryID
SELECT *
FROM Production.Product as PP
FULL JOIN Production.ProductSubCategory as PSC
ON PP.ProductSubcategoryID = PSC.ProductSubCategoryID
Union
Add the rows
from two result
sets together.
In this example,
the query
simplifies the
writing of the
where clause, by
splitting the
query into two
result sets.
Union All to
include
duplicate rows.
SELECT Name, ProductNumber
FROM Production.Product
WHERE StandardCost<1000 and ProductNumber LIKE (‘B%’)
UNION
SELECT Name, ProductNumber
FROM Production.Product
WHERE ListPrice > 2000 and ProductNumber LIKE (‘C%’)
New features added :
SQL Server 2005 are marked with □,05. SQL Server 2008 and 2008R2 are marked with ○,08.
TSQL Cheat Sheet
Join Type
□,05Except
Shows the rows
from that
appear in the
first result sets
that do not
appear in the
second.
In this example,
the query
simplifies the
writing of the
where clause, by
splitting the
query into two
result sets.
□,05Intersect
Shows the rows
from that
appear in both
sets.
In this example,
the query
simplifies the
writing of the
where clause, by
splitting the
query into two
result sets.
Version 1.0 Page 10
SQL Sample
SELECT Name
FROM Production.Product
WHERE ListPrice < 1000 and ProductNumber LIKE (‘SR%’)
EXCEPT
SELECT Name
FROM Production.Product
WHERE StandardCost > 5000 and ProductSubcategoryID IN (2,3,4)
SELECT Name
FROM Production.Product
WHERE ListPrice < 1000 and ProductNumber LIKE (‘SR%’)
INTERSECT
SELECT Name
FROM Production.Product
WHERE StandardCost > 5000 and ProductSubcategoryID IN (2,3,4)
New features added :
SQL Server 2005 are marked with □,05. SQL Server 2008 and 2008R2 are marked with ○,08.
TSQL Cheat Sheet
Version 1.0 Page 11
Windowed Functions
Examples based on this data:
TeamName
Team1
Team2
Team3
Team4
Team5
Team6
Team7
Team8
LeagueName
League 1
League 1
League 1
League 1
League 2
League 2
League 2
League 2
Points
50
35
35
32
65
48
47
17
Function
SQL Sample
Rank()
SELECT TeamName, LeagueName, Points,
Rows with the
Rank() over (order by Points DESC) as Position
same order by
FROM Teams
value are given
the same
TeamName
LeagueName
Points
Position
position.
Team5
League 2
65
1
Subsequent
Team1
League 1
50
2
rows may skip
Team6
League 2
48
3
number due to
Team7
League 2
47
4
ties, in this case
Team2
League 1
35
5
5,5,7 with two
Team3
League 1
35
5
5th places and no Team4
League 1
32
7
6th.
Team8
League 2
17
8
Rank() with
SELECT TeamName, LeagueName, Points,
partitioning
Rank() over (partition by LeagueName order by Points DESC) as Position
As with rank
FROM Teams
above but
numbering
TeamName
LeagueName
Points
Position
restarts for each
Team1
League 1
50
1
partition.
Team2
League 1
35
2
Team3
League 1
35
2
Team4
League 1
32
4
Team5
League 2
65
1
Team6
League 2
48
2
Team7
League 2
47
3
Team8
League 2
17
4
New features added :
SQL Server 2005 are marked with □,05. SQL Server 2008 and 2008R2 are marked with ○,08.
TSQL Cheat Sheet
Function
Dense_Rank()
Rows with the
same order by
value are given
the same
position.
Subsequent
rows do not skip
number s due to
ties, in this case
5,5,6 with two
5th places and a
6th.
Ntile()
Divides the
resultset into x
blocks. In this
case x is 2 so the
function is
Ntile(2).
Row_Number()
Rows with the
same order by
value are not
given the same
position but
given the next
value.
Version 1.0 Page 12
SQL Sample
SELECT TeamName, LeagueName, Points,
Rank() over (order by Points DESC) as Position
FROM Teams
TeamName
LeagueName
Points
Team5
League 2
65
Team1
League 1
50
Team6
League 2
48
Team7
League 2
47
Team2
League 1
35
Team3
League 1
35
Team4
League 1
32
Team8
League 2
17
SELECT TeamName, LeagueName, Points,
NTile(2) over (order by Points DESC) as Position
FROM Teams
TeamName
LeagueName
Points
Team5
League 2
65
Team1
League 1
50
Team6
League 2
48
Team7
League 2
47
Team2
League 1
35
Team3
League 1
35
Team4
League 1
32
Team8
League 2
17
SELECT TeamName, LeagueName, Points,
Row_Number() over (order by Points DESC) as Position
FROM Teams
TeamName
LeagueName
Points
Team5
League 2
65
Team1
League 1
50
Team6
League 2
48
Team7
League 2
47
Team2
League 1
35
Team3
League 1
35
Team4
League 1
32
Team8
League 2
17
Position
1
2
3
4
5
5
6
7
Block
1
1
1
1
2
2
2
2
Position
1
2
3
4
5
6
7
8
New features added :
SQL Server 2005 are marked with □,05. SQL Server 2008 and 2008R2 are marked with ○,08.
TSQL Cheat Sheet
Function
Aggregation
functions
Allows for the
aggregation of
rows without
group by.
Version 1.0 Page 13
SQL Sample
SELECT *,
SUM(points) OVER (PARTITION BY LeagueName) as TotalPointsInLeague,
SUM(points) OVER (PARTITION BY NULL) as TotalPoint
FROM Teams
TeamName LeagueName Points
TotalPointsInLeague TotalPoint
Team1
League 1
50
152
329
Team2
League 1
35
152
329
Team3
League 1
35
152
329
Team4
League 1
32
152
329
Team5
League 2
65
177
329
Team6
League 2
48
177
329
Team7
League 2
47
177
329
Team8
League 2
17
177
329
New features added :
SQL Server 2005 are marked with □,05. SQL Server 2008 and 2008R2 are marked with ○,08.
TSQL Cheat Sheet
Version 1.0 Page 14
Pivot and Unpivot
Query Type
Pivot
Pivot converts
rows of data
into columns.
SQL Sample
create table SalesByRegionByYear(
RegionName varchar(30),
SalesYear int,
SalesValue money
)
RegionName
South
West
North
South
West
North
East
SalesYear
2009
2009
2009
2010
2010
2010
2010
SalesValue
9000.00
4000.00
10000.00
8500.00
6000.00
9500.00
2000.00
select * from
(select * from SalesByRegionByYear) as Query
pivot
(sum(SalesValue) for SalesYear IN ([2009],[2010])) as Pvt
RegionName
East
North
South
West
2009
NULL
10000.00
9000.00
4000.00
2010
2000.00
9500.00
8500.00
6000.00
New features added :
SQL Server 2005 are marked with □,05. SQL Server 2008 and 2008R2 are marked with ○,08.
TSQL Cheat Sheet
Query Type
Unpivot
Unpivot
converts
columns of data
into rows.
Version 1.0 Page 15
SQL Sample
create table ImportedFromExcel(
GroupCode varchar(10),
Month1 money,
Month2 money,
Month3 money
)
GroupCode
ABC
DEF
GHJ
Month1
100.00
80.00
250.00
Month2
200.00
230.00
200.00
Month3
300.00
400.00
180.00
select * from
(select * from ImportedFromExcel) as Query
unpivot
(SalesValue for MonthNo IN (Month1,Month2,Month3)) as UnPvt
GroupCode
ABC
ABC
ABC
DEF
DEF
DEF
GHJ
GHJ
GHJ
SalesValue
100.00
200.00
300.00
80.00
230.00
400.00
250.00
200.00
180.00
MonthNumber
Month1
Month2
Month3
Month1
Month2
Month3
Month1
Month2
Month3
New features added :
SQL Server 2005 are marked with □,05. SQL Server 2008 and 2008R2 are marked with ○,08.
TSQL Cheat Sheet
Version 1.0 Page 16
Index
A
ANSI 92 JOINS ................................................................. 8
B
BETWEEN ........................................................................ 5
BigInt ............................................................................... 3
C
CASE ................................................................................ 6
Char................................................................................. 3
CONVERT ........................................................................ 6
Date formatting ......................................................... 6
D
Date ................................................................................ 3
DATEPART ....................................................................... 5
DateTime ........................................................................ 3
DateTimeOffset............................................................... 3
Decimal ........................................................................... 3
DISTINCT ......................................................................... 5
F
IS NULL ............................................................................ 5
ISNULL()........................................................................... 6
L
LIKE ................................................................................. 5
N
Nchar............................................................................... 3
Nvarchar ......................................................................... 3
S
SELECT ............................................................................. 5
SmallInt ........................................................................... 3
SQL_Variant .................................................................... 3
T
Time ................................................................................ 3
TinyInt ............................................................................. 3
Top .................................................................................. 6
TOP.................................................................................. 5
PERCENT..................................................................... 5
WITH TIES ................................................................... 5
V
Float ................................................................................ 3
Varchar............................................................................ 3
G
Geography ...................................................................... 4
Geometry ........................................................................ 4
GROUP BY ....................................................................... 6
H
X
XML ................................................................................. 4
Y
YEAR ................................................................................ 5
HAVING ........................................................................... 6
I
IN clause ......................................................................... 5
Int 3
New features added :
SQL Server 2005 are marked with □,05. SQL Server 2008 and 2008R2 are marked with ○,08.
Download