Showing posts with label SQL 2014. Show all posts
Showing posts with label SQL 2014. Show all posts

Saturday, 14 March 2015

In Memory OLT P (Memory Optimizer Table) In SQL 2014

Introduction

In SQL 2014 comes with some amazing feature that we must discuss in my blog post. One of the interesting features is In Memory OLTP (Memory Optimizer Table).
In this article we are trying to learn about it. Hope it will be interesting and informative.

What is it?
Microsoft is releasing SQL Server 2014 with a new set of In-Memory OLTP features to significantly improve the OLTP performance and reduce the processing time for servers with a large amount of memory and multi-core processors.

In Memory OLTP is a new technology introduced by Microsoft to reduce the work load of OLTP and provide the high improvement of processing. The performance gains also depends on the hardware we have and how we writing our query. By this technology we are taking the full advantage of modern hardware trends and modern application requirement.
SQL Server is generally designed for saving data in the disk and loading the data into the memory to serve the request made by the Query. This done for resource management as it is quite expensive.

Nowadays the cost of the hardware is quite low and we can manage a server with huge REM and multi core and the new feature of Microsoft called In Memory OLTP works on it.
The In-memory OLTP features are a new database engine component, which is fully integrated into SQL Server and runs side by side with the traditional database engine. It allows us to declare a table to be stored in main memory so that your OLTP workload can access this memory resident data faster.

In the memory optimized table all the data is stored in the memory not in Disk.
Type of Memory Optimize table

There are two types of memory optimize table

1.    SCHEMA_AND_DATA
2.    SCHEMA_ONLY

SCHEMA_AND_DATA :
The SCHEMA_AND_DATA Memory-Optimized table is a table that resides in memory where the data is available after a server crash, a shutdown or a restart of SQL Server

Usages: A point of sales transaction data might be a good fit for a SCHEMA_AND_DATA type table.  We might want our point of sales transactions to run as fast as possible so the memory-optimize type table would provide this, but we wouldn’t want to lose those transactions should our server be restarted.

SCHEMA_ONLY
 SCHEMA_ONLY Memory-Optimized table is a table that does not persist data should SQL Server crash, or the instance is stopped or restarted.  The SCHEMA_ONLY Memory-Optimized tables do retain their table structure should the server crash, or be shutdown.

Usages: SCHEMA_ONLY table would be useful for a staging table in a data warehouse application.   Typically it is fairly easily to reload a data warehouse staging table from its data source. This is why making these type of tables a SCHEMA_ONLY type table is relatively safe.

Maintaining Version in Rows
Rows in memory-optimized tables are versioned. This means that each row in the table potentially has multiple versions. All row versions are maintained in the same table data structure. Row versioning is used to allow concurrent reads and writes on the same row.



.
How we Crate it?
To create Memory-Optimized table we are just following our step by step process to Understand it clearly.

Step-1 [ Create Database to Support Memory Optimize Table ]

First we have to create a database to support Memory-Optimized Table. If needed, we can alter our existing database also.

 IF EXISTS (SELECT *
           FROM   sys.databases
           WHERE name = N'InMemoryExample'
)
  DROP DATABASE InMemoryExample;
GO

CREATE DATABASE InMemoryExample
ON PRIMARY
  (NAME = InMemory_Data,
   FILENAME = N'C:\data\InMemoryExample_Data.mdf',
   SIZE = 100MB,
   FILEGROWTH = 10MB),
FILEGROUP InMemoryExample_InMemory CONTAINS MEMORY_OPTIMIZED_DATA
  ( NAME = InMemory_InMemory,
    FILENAME = N'C:\data\InMemoryExample_InMemory.mdf')

LOG ON
  ( NAME = InMemoryExample_Log,
    FILENAME = N'C:\data\InMemoryExample_Log.ldf',
    SIZE = 100MB,
    FILEGROWTH = 10MB)

GO

The script look likes same. Please review the script carefully, the only differences that we find is

FILEGROUP InMemoryExample_InMemory CONTAINS MEMORY_OPTIMIZED_DATA
  ( NAME = InMemory_InMemory,
    FILENAME = N'C:\data\InMemoryExample_InMemory.mdf')

We created a FILEGROUP named “InMemoryExample_InMemory” that will be used to support our Memory-Optimized tables.  This file group contains a single file.  Without this “MEMORY_OPTIMIZED_DATA” file group I wouldn’t be able to create a Memory-Optimized table in our new database.

Step-2 [ Creating Memory Optimized Table ]

Here we are going to create two types of memory optimized table.

SCHEMA_AND_DATA table:

IF  OBJECT_ID('MemoryOptimized_Schema_And_Data','U') IS NOT NULL
    DROP TABLE MemoryOptimized_Schema_And_Data
GO

CREATE TABLE MemoryOptimized_Schema_And_Data
(
       Id    INT        NOT NULL,
       Col1  CHAR(1000) NOT NULL,
       CONSTRAINT PK_MemoryOptimized_Schema_And_Data
        PRIMARY KEY NONCLUSTERED HASH (Id)
        WITH (BUCKET_COUNT = 1024)
) WITH (MEMORY_OPTIMIZED = ON,
        DURABILITY = SCHEMA_AND_DATA);

SCHEMA_ONLY Table:

IF  OBJECT_ID('MemoryOptimized_Schema_Only','U') IS NOT NULL
    DROP TABLE MemoryOptimized_Schema_Only
GO

CREATE TABLE MemoryOptimized_Schema_Only
(
       Id     INT        NOT NULL,
       Col1   CHAR(1000) NOT NULL,
       CONSTRAINT PK_MemoryOptimized_Schema_Only
        PRIMARY KEY NONCLUSTERED HASH (Id)
        WITH (BUCKET_COUNT = 1024)
) WITH (MEMORY_OPTIMIZED = ON,
        DURABILITY = SCHEMA_ONLY);

Now we have to understand it.
Please look at the part of the script carefully.

CONSTRAINT PK_MemoryOptimized_Schema_Only
        PRIMARY KEY NONCLUSTERED HASH (Id)
        WITH (BUCKET_COUNT = 1024)

Here we are creating NON CLAUSTERED HASH Index on columns ID. The memory optimized table needs the HASH index It cannot be more than the 8. With CTP1 only columns with Windows BIN2 collation types can be used for a HASH index.  Therefore on our table we are just create a HASH index on the INT column and not the char column.
Second thing is BUCKET_COUNT. The BUCKET_COUNT identifies the number of different buckets SQL Server will create in memory to store my Memory-Optimized table records.  Each bucket is identified by the value created when hashing the index column.  Each unique index key value that has the same hash value will be stored in the same bucket.  Therefore it is recommended that we create a bucket value that is equal to or greater than the number of unique key values we expect for your Memory-Optimized table.

Memory-Optimized tables only support the following data types: bit, tinyint, smallint, int, bigint, money, smallmoney, float, real, datetime, smalldatetime, datetime2, date, time, numberic, decimal, char(n),  varchar(n) ,nchar(n),  nvarchar(n), sysname, binary(n), varbinary(n), and Uniqueidentifier. Notice that none of the large Binary Object data types are allowed, even the variable character “max” data types.  Something worth also mentioning is the combined record length must not exceed 8060.  This record length limitation will be enforced at the time we create our table.

Step-3 [ Inserting data into Memory-Optimized Table ]

SET NOCOUNT ON;

USE InMemoryExample;
GO

DELETE FROM MemoryOptimized_Schema_And_Data;
DELETE FROM MemoryOptimized_Schema_Only;

SET STATISTICS IO Off;
SET STATISTICS TIME Off;

DECLARE @s datetime = getdate()

-- Load Normal Table
DECLARE @I int = 0;
WHILE @I < 1000
BEGIN
       SET @I+=1;
       INSERT INTO Normal(Id,C1)
       VALUES (@i,cast(@I as varchar(4)) + 'A');
END;

SELECT DATEDIFF(ms,@s,getdate()) as Normal;

-- Load SchemaAnadData table --
SET @s = getdate();
SET @I = 0;
WHILE @I < 1000
BEGIN
       SET @I+=1;
       INSERT INTO MemoryOptimized_Schema_And_Data
               (Id, Col1)
        VALUES (@i,cast(@I as varchar(4)) + 'A');
END;

SELECT DATEDIFF(ms,@s,getdate()) as SchemaAndData;

-- Load SchemaOnly table
SET @s = getdate();
SET @I = 0;
WHILE @I < 1000
BEGIN
       SET @I+=1;
       INSERT INTO MemoryOptimized_Schema_Only
               (Id, Col1)
        VALUES (@i,cast(@I as varchar(4)) + 'A');
END;
SELECT DATEDIFF(ms,@s,getdate()) As SchemaOnly;
GO

Some limitation
  • NO TRUNCATE TABLE statement against my Memory-Optimized tables.
  • NO ALTER TABLE statement against my Memory-Optimized tables.
  • NO UPDATE of primary key columns of my Memory-Optimized tables.
  • NO FOREIGN KEY or CHECK constraints.
  • NO UNIQUE constraints other than the PRIMARY KEY.




Hope you like it.


Posted by: MR. JOYDEEP DAS

Saturday, 22 March 2014

Delayed Transaction Durability in MS SQL 2014(CTP2)

Introduction

When we first learn the Database we all know about the ACID property of database. We are not going to review it again. Just going to the D means the Durability.

Durability means that when a transaction is committed then changes made by the transaction are permanently stored on disk.

Before MS SQL Server 2014 the TRANSACTION of the SQL Server is Fully Durable. That means TRANSACTION commits are synchronous and report a COMMIT as successful and return control to the client only after the log records for the transaction are written to disk.
If the log records are written to disk successfully then the COMMIT process is successful and the control returns to client. In the other words, we can say that if the transaction log entry fails then the entire transaction is ROLLBACK.

MS SQL Server 2014 (CTP2) introduced Delayed Durability.
It helps reduce the IO contention for writing to the transaction log. Transaction commits are asynchronous. In this case, transactions are logged to the transaction log buffer and then control is returned to the application. The log buffers are written to disk later. This feature is also known as Lazy Commit. 

Both Full and Delayed Transaction durability have their own advantage and disadvantage.

When to Use Full Transaction Durability
·         We must use it when our system not tolerates any data loss.
·         The bottleneck is not due to transaction log write latency.


When to Use Delayed Transaction Durability

We can tolerate some data loss

Where the individual records are not critical as long as we have most of the data.

We are experiencing a bottleneck on transaction log writes

If our performance issues are due to latency in transaction log writes, our application will likely benefit from using delayed transaction durability.

We  workloads have a high contention rate
If our system has workloads with a high contention level much time is lost waiting for locks to be released. Delayed transaction durability reduces commit time and thus releases locks faster which results in higher throughput.

Option of the Transaction Durability
We have the following three options to set the value of Delayed Durability:
  • Disabled: The Delayed Durability feature cannot be used by the current database. This is the default setting. This is the same as a fully durable transaction.

  • Allowed: With this option, each transaction's durability is determined by the transaction level (DELAYED_DURABILITY = {OFF | ON}).

  • Forced: With this option, every transaction must follow Delayed Durability. This is very useful when transaction durability is more important for the database.
Syantax

ALTER DATABASE [DatabaseName]
SET DELAYED_DURABILITY = {DISABLED | ALLOWED | FORCED}

Please note that MS SQL Server 2014 also allows us to use various durability levels at the transaction level.

The COMMIT syntax is extended to support force delayed transaction durability. This COMMIT option is ignored when DELAYED_DURABILITY is DISABLED or FORCED at the database level.

COMMIT TRAN
[ transaction name | @transaction name variable ]
[ WITH ( DELAYED_DURABILITY = { OFF | ON })]

Example

BEGIN TRAN
   INSERT INTO tbl_JODT
          (JOINDT)
   SELECT GETDATE()
COMMIT WITH (DELAYED_DURABILITY = ON)

With Procedure Example

CREATE PROCEDURE TESTPROC
WITH NATIVE_COMPILATION, SCHEMABINDING,
EXECUTE AS OWNER
AS
BEGIN
     ATOMIC WITH
     (
          DELAYED_DURABILITY = ON,
          TRANSACTION ISOLATION LEVEL = SNAPSHOT
     )
     <.... Body ...>
END

Forced a transaction log flush

MS SQL Server 2014 has the system Stored Procedure named sp_flush_log that forces a flush of the log records of all preceding committed (in memory).

References


Hope you like it.

Posted By: MR. JOYDEEP DAS