Difference between NEWID() and NEWSEQUENTIALID() in SQL Server

udayarumilli_uniqueDifference between NEWID() and NEWSEQUENTIALID() in SQL Server

Both NEWID() and NEWSEQUENTIALID() are used to generate GUID of data type UNIQUEIDENTIFIER in SQL Server.

The Basic difference between them is NEWID() generates GUID’s in random order whereas NEWSEQUENTIALID()  generates GUID’s in a sequential order.

We can generate a GUID just by calling NEWID() but we can’t directly use NEWSEQUENTIALID() for generating GUID’s from select statement.

Since NEWID() generates random GUID’s it leads to have more page splits in indexes compare to NEWSEQUENTIALID().

Examples:

  1. Now let’s see how both of them generates GUID’s    

To understand them properly lets create a table insert data and create cluster indexes.

/****** Drop the table if exists ******/
IF EXISTS (SELECT 1 FROM sysobjects WHERE TYPE = 'U' and NAME = 'Product_NewID')
BEGIN
    DROP TABLE Product_NewID;
END
GO
/****Create table with NEWID() ***/
CREATE TABLE Product_NewID(
    ProductID    UNIQUEIDENTIFIER DEFAULT(NEWID()),
    ProductName    VARCHAR(100) NOT NULL,
    ProductPrice    DECIMAL(10,3) NOT NULL DEFAULT(0.000),
    UpdatedDate    DATETIME NOT NULL DEFAULT(SYSDATETIME())
);
GO
IF EXISTS (SELECT 1 FROM sysobjects WHERE TYPE = 'U' and NAME = 'Product_NewSEQID')
BEGIN
    DROP TABLE Product_NewSEQID;
END
GO

/****Create table with NEWSEQUENTIALID() ***/
CREATE TABLE Product_NewSEQID(
    ProductID    UNIQUEIDENTIFIER DEFAULT(NEWSEQUENTIALID()),
    ProductName    VARCHAR(100) NOT NULL,
    ProductPrice    DECIMAL(10,3) NOT NULL DEFAULT(0.000),
    UpdatedDate    DATETIME NOT NULL DEFAULT(SYSDATETIME())
);
GO

/**** Create clustered indexes as below ****/
CREATE CLUSTERED INDEX ix_Product_NewID_ID ON Product_NewID(ProductID);
GO
CREATE CLUSTERED INDEX Product_NewSEQID_ID ON Product_NewSEQID(ProductID);
GO

/*** Now insert data into these two tables ****/
INSERT INTO Product_NewID (ProductName,ProductPrice)
VALUES ('Product_11109',233.56);
GO 20000

INSERT INTO Product_NewSEQID (ProductName,ProductPrice)
VALUES ('Product_11109',233.56);
GO 20000

Now we’ll see just by selecting data from them

You can see all “ProductID” column values are randomly generated.

Now we’ll look into the other table where we have used NEWSEQUENTIALID().

From the above picture we can see the “ProductID” values are sequentially generated.

  1. Now we‘ll see how these differentiate with the select statement.

SELECT NEWID();
GO
SELECT NEWSEQUENTIALID();
GO

NEWID() is generating a GUID. We’ll try with NEWSEQUENTIALID()

It results into an error message:

Msg 302, Level 16, State 0, Line 1

The newsequentialid() built-in function can only be used in a DEFAULT expression for a column of type ‘uniqueidentifier’ in a CREATE TABLE or ALTER TABLE statement. It cannot be combined with other operators to form a complex scalar expression.

  1. Difference between NEWID() and NEWSEQUENTIALID() in page allocation

 We have already inserted 20000 rows into two tables.

Product_NewID: Used NEWID()

Product_NewSEQID: Used NEWSEQUENTIALID()

DBCC SHOWCONTIG('Product_NewID');

 

DBCC SHOWCONTIG('Product_NewSEQID');

 

For the same 20000 rows inserted in these tables we can check observe how pages are allocated for each of these tables.

For the table Product_NewID

Pages Scanned: 218

Avg. Bytes free per page: 2499.7

For the table Product_NewSEQID

Pages Scanned: 152

Avg. Bytes free per page: 69.2

From the above values we can say that there is higher fragmentation for the table which is using NEWID() when comparing with the table which is using NEWSEQUENTIALID().

Posted in SQL Development | Tagged , , , , , , , , , , , , , | Leave a comment

How to find highest salary in sql

 

udayarumilli_highest

How to find highest salary in sql

We had a situation where we have to find out all the details of a product with the Nth highest price Note: Some of the products are in the same price range.

Here I am demonstrating with employee table. Create the table “Employee” from the below script.

USE [udayarumilli];
GO
CREATE TABLE [dbo].[Employee](
    [empid]     [int] IDENTITY(1,1) NOT NULL,
    [name]      [nvarchar](20) NOT NULL,
    [birthdate] [datetime] NOT NULL,
    [Salary]    [int] NOT NULL
) ON [PRIMARY];
GO
INSERT INTO [Employee] ( name,birthdate,Salary)
VALUES ('Sara Davis',1958-12-08,120000),
('Don Funk',1962-02-19,98000),
('Judy Lew',1973-08-30,76000),
('Yael Peled',1947-09-19,76000),
('Sven Buck',1965-03-04,102000),
('Paul Suurs',1973-07-02,110000),
('Russell King',1970-05-29,69000),
('Maria Cameron',1968-01-09,72000),
('Zoya Dolgopyatova',1976-01-27,89000)
GO

Now let’s check the employee salaries using the below query.

SELECT      Salary
FROM         Employee
ORDER BY  salary DESC;
GO

From the table we can say that highest salary is: 120000 and lowest salary is: 69000

Now we‘ll see the different options how can get the employee details for Nth highest salary.

There are mainly two ways we can accomplish this as below. We’ll find the 3rd highest salary.

-- Traditional way to find the 3rd highest salaried employee details

SELECT TOP 1 name,salary
FROM (
        SELECT DISTINCT TOP 3 name,salary
        FROM        employee
        ORDER BY    salary DESC) e
ORDER BY salary
 

-- Using ROW_NUMBER() to find the 3rd highest salaried employee details

SELECT    name,salary
FROM(
        SELECT name,Salary,
               row_number() over(order by salary desc) as place
        FROM   employee) e
WHERE e.place=3

From the data yes we can confirm these are giving the 3rd highest salaried employee details.

 From the above queries if you want to find the 4th highest just replace 3 with 4 and if Nth highest required replace 3 with N.

 Now we’ll try to find out the 6th highest salary using the same queries.

 -- Traditional way to find the 6th highest salaried employee details

SELECT TOP 1 name,salary
FROM (
        SELECT DISTINCT TOP 6 name,salary
        FROM        employee
        ORDER BY    salary DESC) e
ORDER BY salary

-- Using ROW_NUMBER() to find the 6th highest salaried employee details
SELECT    name,salary
FROM(
        SELECT    name,Salary,row_number() over(order by salary desc) as place
        FROM    employee) e
WHERE e.place=6

Here is the problem. If you can observe there are two employees with the same salary

But these queries are retrieving only one record that is 6th row: Judy Lew. But there are two employees with the same salary which is 6th highest in the group.

If we try to capture the 7th highest it gives us the wrong result. It might be 6th row or 7th row depends on the ORDER BY clause.  To avoid this we have to change the query to use DENSE_RANK() instead of ROW_NUMBER().

-- Using DENSE_RANK() to find the 6th highest salaried employee details

SELECT  name,salary as '6th_Highest'
FROM(
        SELECT  name,Salary,
                DENSE_RANK() over(order by salary desc) as place
        FROM    employee) e
WHERE e.place=6

-- Using DENSE_RANK() to find the 3rd highest salaried employee details
SELECT    name,salary AS '3rd_Highest'
FROM(
        SELECT  name,Salary,
                DENSE_RANK() over(order by salary desc) as place
        FROM    employee) e
WHERE e.place=3

Now we can see all the employees who are at the 6th highest salary are included in the result set.

Posted in SQL Development | Tagged , , , , , , , , | 2 Comments

Microsoft Windows 8.1 Preview

Windows8_1udayarumilliwindows81Microsoft Windows 8.1 Preview

Posted in Miscellaneous | Tagged , , | Leave a comment