sql server 2012 notes - part i

54
SQL Server 2012 Notes Part I Madhura Oak Project Manager Intellect Design Arena Ltd.

Upload: madhura-oak

Post on 12-Apr-2017

363 views

Category:

Software


0 download

TRANSCRIPT

Page 1: Sql Server 2012 Notes - Part I

SQL Server 2012 Notes Part I

Madhura OakProject Manager

Intellect Design Arena Ltd.

Page 2: Sql Server 2012 Notes - Part I

T-SQL

• Transact SQL also called as T-SQL is the dialect of SQL Server

Page 3: Sql Server 2012 Notes - Part I

Order of SQL Query Execution

• FROM• WHERE• GROUP BY• HAVING• SELECT• ORDER BY

Page 4: Sql Server 2012 Notes - Part I

WHERE clause

SELECT EMPID, NAME FROM EMPLOYEES WHERE YEAR(HIREDATE) = 2015

Select all employees which joined in year 2015

Aliases defined in SELECT clause cannot be referred in WHERE clause since WHERE is evaluated before SELECT.

Page 5: Sql Server 2012 Notes - Part I

GROUP BY clause

SELECT CUSTID, COUNT(*) As ‘Order Count’FROM ORDERS GROUP BY CUSTIDORDER BY CUSTID

Get the number of orders placed by customers.

The element referred in GROUP BY clause should be present in SELECT clause.

Page 6: Sql Server 2012 Notes - Part I

HAVING clauseSELECT CUSTID, COUNT(*) AS ‘Order Count’ FROM ORDERS WHERE YEAR(ORDERDATE) = 2015GROUP BY CUSTID HAVING COUNT(*) > 5 ORDER BY CUSTID

Get customers who have placed more than 5 orders in year 2015

Page 7: Sql Server 2012 Notes - Part I

Difference between HAVING and WHERE clauses

WHERE is evaluated before GROUP BY and HAVING is applied after filtering.

Page 8: Sql Server 2012 Notes - Part I

DISTINCT clause

SELECT DISTINCT CUSTID FROM ORDERSWHERE MONTH(ORDERDATE) = 11 AND YEAR(ORDERDATE) = 2015

Get all distinct customers who have placed orders in November 2015.

Page 9: Sql Server 2012 Notes - Part I

DISTINCT clause

SELECT DISTINCT YEAR(ORDERDATE), MONTH(ORDERDATE), CUSTID FROM ORDERS

The resultset can contain multiple rows with same year and month but only one row having unique combination of year, month and custId

Page 10: Sql Server 2012 Notes - Part I

FROM clause

FROM <schemaname>.<tablename> If schema name is not given, then implicit

schema name is used.

<servername>.<databasename>.<schemaname>.<objectname>

Page 11: Sql Server 2012 Notes - Part I

Alias

• <expression> <alias>• <expression> AS <alias>• <alias> = <expression>

Page 12: Sql Server 2012 Notes - Part I

FROM is optional

SELECT 10

will return 10

Page 13: Sql Server 2012 Notes - Part I

SELECT * FROM

Use of * is considered as a bad practice instead of explicitly specifying column names since it could fetch unnecessary data and pass it across the network when the query is called.

SELECT * FROM ORDERS

Page 14: Sql Server 2012 Notes - Part I

Concatenating column values

SELECT FIRSTNAME + N‘ ' + LASTNAME FROM EMPLOYEE

The column name in the resultset will not be present. This is considered as a non relational result.

SELECT FIRSTNAME + N‘ ' + LASTNAME AS Name FROM EMPLOYEE

Page 15: Sql Server 2012 Notes - Part I

Concatenating NULLs

SELECT FIRSTNAME + N‘ ' + LASTNAME AS Name FROM EMPLOYEE

If any of FIRSTNAME or LASTNAME is NULL, it will return NULL. This is due to the option called CONCAT_NULL_YIELDS_NULL which is turned ON by default

Page 16: Sql Server 2012 Notes - Part I

CONCAT_NULL_YIELDS_NULL

This option is set to ON by default and in further release after SQL Server 2016 this would always be ON. Hence use of this option is discouraged.

When this option is set to ON SELECT ‘abc’+NULL returns NULL

When this option is set to OFF, concatenating a NULL value is equivalent to concatenating empty strings.

SELECT ‘abc’+NULL returns ‘abc’

Page 17: Sql Server 2012 Notes - Part I

CONCAT_NULL_YIELDS_NULL

This option should be ON when indexes on computed columns or indexed views are created or modified. If set to OFF, CREATE, UPDATE, INSERT and DELETE statements on tables with indexes on computed columns or indexed views fail.

When this option is OFF, string concatenation across server boundaries cannot occur.

Page 18: Sql Server 2012 Notes - Part I

Adding values

+ operator adds values if used on numeric data types

SELECT ORDER_AMOUNT + DISCOUNT AS [Original Price] FROM ORDERS

Page 19: Sql Server 2012 Notes - Part I

Identifiers

• Regular– First character is a character in Unicode

Standard 3.2. It can be a-z, A-Z and other Unicode characters, _ (underscore), @, #

– Other characters include letters, decimal numbers, @, $, # or _

– Should not be a reserved keyword – Cannot contain spaces

Page 20: Sql Server 2012 Notes - Part I

Identifiers

• Delimited– Identifiers that are not regular are delimited.

For e.g. “Item Details” or [Item Details]– Reserved T-SQL keyword

Prefer use of Regular identifiers

Page 21: Sql Server 2012 Notes - Part I

Data Types• Numeric (TINYINT, SMALLINT, INT, BIGINT,

NUMERIC, DECIMAL)• Character string (CHAR, VARCHAR)• Unicode character string (NCHAR, NVARCHAR)• Approximate numeric (FLOAT, REAL)• Binary (BINARY, VARBINARY)• Time (DATE, TIME, DATETIME2,

SMALLDATETIME, DATETIME, DATETIMEOFFSET)

• Unique Identifier - UNIQUEIDENTIFIER

Page 22: Sql Server 2012 Notes - Part I

Data type size

• TINYINT - 1 byte• SMALLINT – 2 bytes• INT – 4 bytes• BIGINT – 8 bytes• FLOAT – 4 bytes• REAL – 8 bytes• UNIQUEIDENTIFIER – 16 bytes

Page 23: Sql Server 2012 Notes - Part I

Choosing Data types• Use data type which fits storage needs• Using data types with large storage will

unnecessarily occupy memory for e.g. using INT to store a 2 digit number

• Use fixed data types for frequent updates for e.g. use of CHAR(30) instead of VARCHAR(30) increases performance

• Starting with SQL Server 2008 R2, Unicode compression is used to store unicode data types.

Page 24: Sql Server 2012 Notes - Part I

Choosing Data types

• Explicitly specify data length where possible. for e.g. CHAR(2)

Page 25: Sql Server 2012 Notes - Part I

Literals with unicode characters

• Use N'ت‘ to represent unicode characters which are not English characters

Page 26: Sql Server 2012 Notes - Part I

NOT NULL constraint

• NOT NULL is enforced as a part of definition

CREATE TABLE ORDERS (ORDERID INT NOT NULL)

Page 27: Sql Server 2012 Notes - Part I

Data conversion functions

• CAST• TRY_CAST• CONVERT• TRY_CONVERT• PARSE• TRY_PARSE

Page 28: Sql Server 2012 Notes - Part I

TRY conversion functions

SELECT CAST(‘a’ AS INT) fails

SELECT TRY_CAST(‘a’ AS INT)returns NULL

Page 29: Sql Server 2012 Notes - Part I

Data conversion

• SQL Server converts value with lower data type precedence to higher one.

• 1 + ‘1’ will not result in ’11’ but 2 since INT preceds VARCHAR

• 5/2 results in 2 and not 2.5 since both operands are integers

Page 30: Sql Server 2012 Notes - Part I

Generating surrogate keys

• IDENTITY – integer type (INT, SMALLINT, INT, BIGINT) or NUMERIC/DEMICAL with a scale of 0

• SEQUENCE• Non sequential GUIDs - unique identifier

of UNIQUEIDENTIFIER type. NEWID function is used to generate it.

• Sequential GUIDs – NEWSEQUENTIALID function is used to generate it.

Page 31: Sql Server 2012 Notes - Part I

When should you use sequential keys?

• All rows go into right end of index. SQL server allocates a new page when a page is full. This results in less fragmentation in index. Improves read performance

• Insertions are faster if single session is loading data or data resides in a single or small number of drives.

• When data is being loaded in multiple sessions, page latch contention is possible. This prevents use of full throughput of high-end storage subsystems

Page 32: Sql Server 2012 Notes - Part I

Nonsequential keys performance

• When a page is full when NEWID is used, SQL Server performs page split by moving half rows from original page to new one. A page split results in index fragmentation which has negative impact on performance of reads.

• Index fragmentation can be dealt by rebuilding index as part of regular maintenance activity.

Page 33: Sql Server 2012 Notes - Part I

DATE and TIME functions

• GETDATE – returns DATETIME datatype• CURRENT_TIMESTAMP – returns DATETIME

datatype• GETUTCDATE – returns DATETIME datatype• SYSDATETIME – returns DATETIME2 data type• SYSUTCDATETIME – returns DATETIME2 data

type• SYSDATETIMEOFFSET – returns

DATETIMEOFFSET data type

Page 34: Sql Server 2012 Notes - Part I

Date and time functions

• DATEPART• YEAR• MONTH • DAY• DATENAME• EOMONTH

Page 35: Sql Server 2012 Notes - Part I

Date and time functions

• DATEPART(year, ‘20151129’) returns 2015

• DATENAME(month, ‘20151129’) returns ‘November’

• EOMONTH(GETDATE()) returns ‘2015-11-30’ since the current month is November.

• EOMONTH(GETDATE(),2) returns ‘2016-01-31’) if current month is November

Page 36: Sql Server 2012 Notes - Part I

Date conversion

• CAST(CURRENT_TIMESTAMP AS DATE)

Page 37: Sql Server 2012 Notes - Part I

Functions to construct date and time

• DATEFROMPARTS• DATETIME2FROMPARTS• DATETIMEFROMPARTS• DATETIMEOFFSETFROMPARTS• SMALLDATETIMEFROMPARTS• TIMEFROMPARTS

Page 38: Sql Server 2012 Notes - Part I

Constructing date and time

DECLARE @today AS DATESELECT @today =

DATEFROMPARTS(2015,11,29)

Page 39: Sql Server 2012 Notes - Part I

Functions to Add and subtract dates

• DATEADD– DATEADD(month, 2, ‘20151129’) adds 2

months• DATEDIFF

– DATEDIFF(month, ‘20151129’,’20160129’) returns 2

Page 40: Sql Server 2012 Notes - Part I

Functions for Date OFFSET

• SWITCHOFFSET– SWITCHOFFSET(SYSDATETIMEOFFSET(),

‘-1:00’). If the system offset is +05:30, this returns the value after subtracting 06:30 hours.

• TODATETIMEOFFSET– TODATETIMEOFFSET(‘20151129

10:15:00’,’-05:30’) returns ‘20151129 10:15:00 -05:30’

Page 41: Sql Server 2012 Notes - Part I

Substitute NULL values

• COALESCE– COALESCE(VALUE,SUBSTITUTE)

• CONCAT – Substitutes NULL with empty string

SELECT COALESCE(FIRSTNAME + N' ' + LASTNAME,' ') FROM EMPLOYEE

SELECT CONCAT(FIRSTNAME,' ',LASTNAME) FROM EMPLOYEE

Page 42: Sql Server 2012 Notes - Part I

Extracting substring

• SUBSTRING(string,startIndex,length)• LEFT(string,length)• RIGHT(string,length)

SELECT SUBSTRING(‘ABC’,1,1) returns ‘A’SELECT LEFT(‘ABC’,2) returns ‘AB’SELECT RIGHT(‘ABC’,1) returns ‘C’

Page 43: Sql Server 2012 Notes - Part I

Locating characters• CHARINDEX(string to be found,string to be

searched)• PATINDEX(pattern,string to be searched)

SELECT CHARINDEX(‘B’,’ABCDE’) returns 2

SELECT PATINDEX(‘%[0-9]{3}%’, ‘X12Y345’) returns 5

Page 44: Sql Server 2012 Notes - Part I

Length functions

• LEN – returns count of characters. If there are trailing spaces, LEN removes them– SELECT LEN(N’abc ’) returns 3

• DATALENGTH – returns count of bytes. Doesn’t remove trailing spaces.– SELECT DATALENGTH(N’abc ‘) returns 8

Page 45: Sql Server 2012 Notes - Part I

String alteration functions

• REPLACE– REPLACE(‘abcac’,’a’,’A’) returns ‘AbcAc’

• REPLICATE– REPLICATE(‘A’,3) returns ‘AAA’

• STUFF– STUFF(‘abc’,2,1,’de’) returns ‘adec’

Page 46: Sql Server 2012 Notes - Part I

String formatting functions

• UPPER• LOWER• LTRIM• RTRIM• FORMAT

– FORMAT(11,’#0.00’) returns ‘11.00’

Page 47: Sql Server 2012 Notes - Part I

CASE expression

• Simple formSELECT ORDERID, ORDER_AMT,

CASE DISCOUNT_RATE WHEN 0 THEN ‘No’ELSE ‘Yes’END AS [Discount Provided]

FROM ORDERS

If ELSE clause is not specified default is ELSE NULL.

Page 48: Sql Server 2012 Notes - Part I

CASE Expression• Searched formSELECT ORDERID, ORDER_AMT,CASE DISCOUNT_RATEWHEN = 0 THEN ‘No discount’WHEN <= 50 THEN ‘Upto 50%’WHEN <= 75 THEN ‘Upto 75%’ELSE ‘More than 75% discount’END AS DiscountFROM ORDERS

Page 49: Sql Server 2012 Notes - Part I

COALESCE function

COALESCE(<exp1>,<exp2>,…,<expr>)is equivalient to CASE WHEN <exp1> IS NOT NULL THEN <exp1>WHEN <exp2> IS NOT NULL THEN <exp2>…ELSE <expn> IS NOT NULL THEN <expn>END

Page 50: Sql Server 2012 Notes - Part I

ISNULL function

ISNULL(<exp1>,<exp2>)

If <exp1> is NULL then <exp2> is returned else <exp1> is returned.

This is not a standard function. Hence use of standard function COALESCE is preferred.

Page 51: Sql Server 2012 Notes - Part I

NULLIF function

NULLIF(<exp1>,<exp2>)If exp1 is equal to exp2 then NULL is

returned of the data type of exp1. If they are not equal exp1 is returned.

Time dependent functions such as RAND() should be avoided within NULLIF, since they would be evaluated twice and their result would be different.

Page 52: Sql Server 2012 Notes - Part I

IIF function• Not a standard T-SQL function. Exists for migration from

Access to SQL Server

IIF(<exp>,<true_value>,<false_value>)

The use of CASE is recommended instead.

Equivalent to CASE WHEN <exp> THEN <true_value> ELSE <false_value>END

Page 53: Sql Server 2012 Notes - Part I

CHOOSE function

CHOOSE(<pos>,<exp1>,<exp2>,…,<expn>)

This is also a non-standard T-SQL function which exists for simplifying Access to SQL Server migration.

Page 54: Sql Server 2012 Notes - Part I

Thank You!