Wednesday, September 23, 2015

Ranking Functions

Sample Example of RANKING Functions – ROW_NUMBER, RANK, DENSE_RANK, NTILE

I have not written about this subject for long time, as I strongly believe that Book On Line explains this concept very well. SQL Server 2005 has total of 4 ranking function. Ranking functions return a ranking value for each row in a partition. All the ranking functions are non-deterministic.
ROW_NUMBER () OVER ([] )
Returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.
RANK () OVER ([] )
Returns the rank of each row within the partition of a result set.
DENSE_RANK () OVER ([] )
Returns the rank of rows within the partition of a result set, without any gaps in the ranking.
NTILE (integer_expression) OVER ([] )
Distributes the rows in an ordered partition into a specified number of groups.
All the above definition and syntax are taken from BOL. It is difficult to explain above function anything else than what they are explained in BOL. Following example is excellent example from BOL again. This function explains usage of all the four function together in one query.
USE AdventureWorks;
GO
SELECT c.FirstName, c.LastName
,ROW_NUMBER() OVER (
ORDER BY a.PostalCode) AS 'Row Number'
,RANK() OVER (
ORDER BY a.PostalCode) AS 'Rank'
,DENSE_RANK() OVER (
ORDER BY a.PostalCode) AS 'Dense Rank'
,NTILE(4) OVER (
ORDER BY a.PostalCode) AS 'Quartile'
,s.SalesYTD, a.PostalCode
FROM Sales.SalesPerson s
INNER JOIN Person.Contact c
ON s.SalesPersonID = c.ContactID
INNER JOIN Person.Address a
ON a.AddressID = c.ContactID
WHERE TerritoryID IS NOT NULL
AND 
SalesYTD <> 0;
Resultset:

http://www.pinaldave.com/bimg/ranking.gif

Monday, January 18, 2010

Date Functions



/*General Syntax */

SELECT DATENAME(datepart,'2007-10-30 12:15:32.1234567 +05:10')

/*Example */

SELECT DATENAME(yyyy,'2007-10-30 12:15:32.1234567 +05:10')



/*

Here is the result set.

datepart                     Return value



year, yyyy, yy                2007

quarter, qq, q                4

month, mm, m                October

dayofyear, dy, y            303

day, dd, d                    30

week, wk, ww                44

weekday, dw                    Tuesday

hour, hh                    12

minute, n                    15

second, ss, s                32

millisecond, ms                123

microsecond, mcs            123456

nanosecond, ns                123456700

TZoffset, tz                310



*/



/*General Syntax */

SELECT DATEPart(datepart,'2007-10-30 12:15:32.1234567 +05:10')

/*Example */

SELECT DATEpart(yyyy,'2007-10-30 12:15:32.1234567 +05:10')



/*

Here is the result set.

datepart                     Return value



year, yyyy, yy                2007

quarter, qq, q                4

month, mm, m                October

dayofyear, dy, y            303

day, dd, d                    30

week, wk, ww                44

weekday, dw                    Tuesday

hour, hh                    12

minute, n                    15

second, ss, s                32

millisecond, ms                123

microsecond, mcs            123456

nanosecond, ns                123456700

TZoffset, tz                310



Key difference between datepart and datename is,

    -    datepart will return numeric value

    -    datename will return both nuermic / text value

*/



/*

DateDiff - it will find and return the differences between two dates.



    First parameter - what difference you want to find ? - year / month /date

    second parameter - comparision date 1

    third parameter - comparision date 2

*/





SELECT DATEDIFF(year, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');



SELECT DATEDIFF(quarter, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');



SELECT DATEDIFF(month, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');



SELECT DATEDIFF(dayofyear, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');



SELECT DATEDIFF(day, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');



SELECT DATEDIFF(week, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');



SELECT DATEDIFF(hour, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');



SELECT DATEDIFF(minute, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');



SELECT DATEDIFF(second, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');



SELECT DATEDIFF(millisecond, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');

Union vs Union All




SQL SERVER – Union vs. Union All – Which is better for performance?







This article is completely re-written with better example SQL SERVER – Difference Between Union vs. Union All – Optimal Performance Comparison. I suggest all of my readers to go here for update article.



UNION

The UNION command is used to select related information from two tables, much like the JOIN command. However, when using the UNION command all selected columns need to be of the same data type. With UNION, only distinct values are selected.



UNION ALL

The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values.



The difference between Union and Union all is that Union all will not eliminate duplicate rows, instead it just pulls all rows from all tables fitting your query specifics and combines them into a table.



A UNION statement effectively does a SELECT DISTINCT on the results set. If you know that all the records returned are unique from your union, use UNION ALL instead, it gives faster results.



Example:

Table 1 : First,Second,Third,Fourth,Fifth

Table 2 : First,Second,Fifth,Sixth



Result Set:

UNION: First,Second,Third,Fourth,Fifth,Sixth (This will remove duplicate values)

UNION ALL: First,First,Second,Second,Third,Fourth,Fifth,Fifth,Sixth,Sixth (This will repeat values)

Union & Operator


Like Operator


Aggregate Functions


Monday, January 11, 2010

String Functions

/* SQL Server String Functions */

/*
1. CHARINDEX string function takes 2 arguments. 1st argument specifies the character whose index is to be retrieved and 2nd argument takes as a string from which character index is carried out.
Example:
*/

Select CHARINDEX ('S','MICROSOFT SQL SERVER 2000') --Result: 6
Select CHARINDEX ('ROS','MICROSOFT SQL SERVER 2000') --Result: 4

/*
2. LEFT string function takes 2 arguments. 1st argument takes as a string value and 2nd argument as integer value as length parameter. It returns first characters of specified length starting from the left side of the string entered as 1st argument.
Example:
*/

Select LEFT ('MICROSOFT SQL SERVER 2000',4)
--Result: MICR

/*
3. RIGHT string function takes 2 arguments. 1st argument takes as a string value and 2nd argument as integer value as length parameter. It returns last characters of specified length starting from the right side of the string entered as 1st argument.
Example:
*/

Select RIGHT ('MICROSOFT SQL SERVER 2000',4)
--Result: 2000

/*
4. LEN string function takes 1 argument as string value and returns the length of entered string.
Example:
*/

Select LEN ('MICROSOFT SQL SERVER 2000')
--Result: 25

/*
5. REPLACE string function takes 3 arguments.
1st argument as string value.
2nd argument is a part of string entered as 1st argument which is to be replaced.
3rd argument as a new string value that is to be placed at the place of 2nd argument.
Example:
*/

Select REPLACE ('MICROSOFT SQL SERVER 2000','MICROSOFT','MS')
--Result: MS SQL SERVER 2000

/*
6. STUFF string function takes 4 arguments. It is used to replace specified length of characters with provided pattern.
1st argument as string value.
2nd argument as integer value specifying the starting point of characters to be replaced.
3rd arguments as integer value specifying the length of characters.
4th argument as string value specifying the new pattern of characters.
Example:
*/

Select STUFF ('MICROSOFT SQL SERVER 2000', 11, 3,'S.Q.L.')
--Result: MICROSFT S.Q.L. SERVER 2000

/*
7. SUBSTRING string function returns the sub string of specified length starting from the entered start position. It takes 3 arguments.
1st argument as string value.
2nd argument as integer specifying the start position.
3rd argument as integer specifying the length
Example:
*/

Select SUBSTRING ('MICROSOFT SQL SERVER 2000', 11, 3)
--Result: SQL

/*
8. LOWER string function returns the lower case string whether the entered string has upper case letters. It takes 1 argument as string value.
Example:
*/

select LOWER('MICROSOFT ASP NET WEB HOSTING')
--Result: microsoft asp .net web hosting

/*
9. UPPER string function returns the upper case string whether the entered string has lower case letters. It takes 1 argument as string value.
Example:
*/

select UPPER(‘MICROSOFT ASP .NET WEB HOSTING with SQL Database’)
--Result: MICROSOFT ASP .NET WEB HOSTING WITH SQL DATABASE

/*
10. REVERSE string function returns the string in reverse order. It takes 1 argument as string value.
Example:
*/

select REVERSE(‘ASP.NET’)
--Result: TEN.PSA

/*
11. LTRIM function returns the string by removing all the blank spaces at left side. It also takes 1 argument as string value.
Example:
*/

Select LTRIM('  ASP')
--Result: ASP-----blanks at the right side not removed.

/*
12. RTRIM function returns the string by removing all the blank spaces at left side. It also takes 1 argument as string value.
Example:
*/

select RTRIM (‘ ASP ’)
--Result: -----ASPblanks at the left side not removed.

/*
13. PATINDEX function returns the position of first occurrence of specified pattern in the provided string. It takes 2 arguments.
1st argument as string value specifying the pattern to match
2nd argument as string value specifying the string to compare.
Example:
*/

select PATINDEX('%RO%','MICROSOFT')
--Results: 4

/*
14. STR function returns character data converted from numeric data. It takes 3 arguments.
1st argument as float data
2nd argument as integer value specifying the length of the string including decimal that is to be retrieved.
3rd argument as integer specifying the number of places to the right of the decimal point.
Example:
*/

select STR(140.15, 6, 1)
--Result: 140.2

/*
15. ASCII function returns the ASCII code value from the leftmost character specified character expression. It takes 1 argument as string/character expression.
Example:
*/

select ASCII('A')
--Result: 65

/*
16. CHAR function that converts an int ASCII code to a character
Example:
*/

Select CHAR(78)
-- Result: N

/*
17. NCHAR - Returns the Unicode character with the given integer code, as defined by the Unicode standard.
Example:
*/

Select NCHAR(4)
--Result: J

/*
18. SOUNDEX - Returns a four-character (SOUNDEX) code to evaluate the similarity of two strings.
Syntax

SOUNDEX ( character_expression )
Examples

This example shows the SOUNDEX function and the related DIFFERENCE function. In the first example, the standard SOUNDEX values are returned for all consonants. Returning the SOUNDEX for Smith and Smythe returns the same SOUNDEX result because all vowels, the letter y, doubled letters, and the letter h, are not included.

-- Using SOUNDEX
*/
SELECT SOUNDEX ('Smith'), SOUNDEX ('Smythe')

/*
Here is the result set:
----- -----
S530  S530
*/


/*
19. QUOTENAME - Returns a Unicode string with the delimiters added to make the input string a valid Microsoft® SQL Server™ delimited identifier.
Syntax

QUOTENAME ( 'character_string' [ , 'quote_character' ] )
Example:
This example takes the character string abc[]def and uses the [ and ] characters to create a valid SQL Server quoted (delimited) identifier.
*/

SELECT QUOTENAME('abc[]def')
/* Here is the result set:
[abc[]]def]
*/

/*
20. UNICODE

Returns the integer value, as defined by the Unicode standard, for the first character of the input expression.
Syntax - UNICODE ( 'ncharacter_expression' )
Example:
*/

Select UNICODE(197)

--

/*
21. SPACE - Include space
Example:
*/

Select 'a' + SPACE(1)+ 'b'

--Result: 'a b'