top of page
Search

What's New in SQL Server for the Developer: SQL Server 2016

12m
10 min read
What's New in SQL Server for the Developer: SQL Server 2016

What's your plan when someone runs an UPDATE without a WHERE clause at 4:55 on a Friday afternoon?


If your answer is "restore last night's backup and transaction logs just to restore that one table," SQL Server 2016 has something for you. Actually, it has a lot. This is part 2 of my "What's New in SQL Server for the Developer" series, built from my session. Part 1 covered SQL Server 2012. This one is about SQL Server 2016.


A Little Background


For background, 2016 is the release where SQL Server started meeting developers where they already were. JSON came in. Security moved closer to the data with Always Encrypted, Dynamic Data Masking, and Row-Level Security. And for the first time, we got a built-in flight recorder for query performance with Query Store.


There's a lot here, so let's get started.


STRING_SPLIT


How many custom split functions have you seen in one database? Usually it's a WHILE loop or an XML trick someone copied years ago. STRING_SPLIT replaces all of them.

DECLARE @emails VARCHAR(400) = 'test@test.com,testing@mywebsite.com,demo@test.com';

SELECT value FROM STRING_SPLIT(@emails, ',');

SELECT value FROM STRING_SPLIT('My random sentence for this demo.', ' ');

Here's where it really shines. When a UI sends over a multi-select list as a comma-separated string, you can join right to it:

SELECT
    i.IndustryID,
    i.IndustryName
FROM
    dbo.Industries AS i
    INNER JOIN STRING_SPLIT('1,3,5,7,9,10,14,27,74,86', ',') AS s
        ON s.value = i.IndustryID;

Keep in mind that STRING_SPLIT needs database compatibility level 130 or higher, and in 2016 the output order isn't guaranteed.


DATEDIFF_BIG


DATEDIFF returns an INT, so it overflows faster than you'd think. In milliseconds, it runs out after about 24 days. DATEDIFF_BIG returns a BIGINT instead.

DECLARE @StartDate DATETIME2(0) = '1/1/2016', @EndDate DATETIME2(0) = GETDATE();

SELECT
    DATEDIFF_BIG(YEAR, @StartDate, @EndDate) AS [Year],
    DATEDIFF_BIG(QUARTER, @StartDate, @EndDate) AS [Quarter],
    DATEDIFF_BIG(MONTH, @StartDate, @EndDate) AS [Month],
    DATEDIFF_BIG(DAY, @StartDate, @EndDate) AS [Day],
    DATEDIFF_BIG(HOUR, @StartDate, @EndDate) AS [Hour],
    DATEDIFF_BIG(MINUTE, @StartDate, @EndDate) AS [Minute],
    DATEDIFF_BIG(SECOND, @StartDate, @EndDate) AS [Second],
    DATEDIFF_BIG(MILLISECOND, @StartDate, @EndDate) AS [Millisecond];

Run that with plain DATEDIFF, and the millisecond column throws an overflow error.


DROP IF EXISTS


No more wrapping every drop in an OBJECT_ID check first. It works inline, right in your scripts.

DROP PROCEDURE IF EXISTS dbo.MySP;
DROP INDEX IF EXISTS IX_MyTestTable_Index ON dbo.MyTestTable;
DROP TABLE IF EXISTS dbo.MyTestTable;
DROP SYNONYM IF EXISTS dbo.MySynonym;
DROP TRIGGER IF EXISTS dbo.MyTrigger;
DROP USER IF EXISTS [user_name];
DROP VIEW IF EXISTS dbo.MyView;
DROP TYPE IF EXISTS dbo.MyType;
DROP SCHEMA IF EXISTS Demo;
DROP FUNCTION IF EXISTS dbo.MyFunction;

ALTER TABLE dbo.MyTestTable DROP COLUMN IF EXISTS MyTestColumn;
ALTER TABLE dbo.MyTestTable DROP CONSTRAINT IF EXISTS PK_MyTestTable;

JSON Support


This next one is pretty cool. Starting in 2016, you can select directly from SQL Server and get a JSON document back. FOR JSON AUTO takes your column names and builds the elements for you:

SELECT TOP 10
    AccountId, DisplayName, Age, Location, CreationDate, LastAccessDate, Reputation
FROM
    dbo.Users
ORDER BY
    LastAccessDate DESC
FOR JSON AUTO;
[
  {
    "AccountId": 5638794,
    "DisplayName": "RiaDess",
    "CreationDate": "2015-01-17T13:34:58",
    "LastAccessDate": "2015-03-07T23:51:32.930",
    "Reputation": 1
  },
  {
    "AccountId": 2348349,
    "DisplayName": "Ed Cottrell",
    "Age": 36,
    "Location": "Houston, TX",
    "CreationDate": "2013-10-30T05:47:17",
    "LastAccessDate": "2015-03-07T16:02:03.720",
    "Reputation": 103
  }
]

Notice that the first user has no Age or Location in the output. FOR JSON leaves out NULL columns by default. If your application expects every property every time, add INCLUDE_NULL_VALUES.


FOR JSON PATH lets you control the element names, and dotted aliases build nested objects:

SELECT TOP 10
    AccountId AS AccountNumber,
    DisplayName AS [Profile.DisplayName],
    Location AS [Profile.Location],
    Reputation
FROM
    dbo.Users
ORDER BY
    LastAccessDate DESC
FOR JSON PATH, INCLUDE_NULL_VALUES;

Join two tables with FOR JSON AUTO, and SQL Server nests the child rows for you. Each user comes back with an array of their posts:

SELECT
    Users.AccountId,
    Posts.Id,
    Posts.PostTypeId,
    ISNULL(Posts.Title, LEFT(CAST(Posts.Body AS VARCHAR(MAX)), 50)) AS Title
FROM
    dbo.Users AS Users
    INNER JOIN dbo.Posts AS Posts
        ON Users.Id = Posts.OwnerUserId
WHERE
    Users.Id IN (SELECT TOP 10 u.Id FROM dbo.Users AS u ORDER BY u.LastAccessDate DESC)
ORDER BY
    Users.Id
FOR JSON AUTO;

And JSON_MODIFY lets you update a value inside a JSON document without pulling it out to the application layer:

DECLARE @info NVARCHAR(100) = N'{"name":"John","skills":["C#","SQL"]}';

SET @info = JSON_MODIFY(@info, '$.name', 'Mike');             -- update a value
SET @info = JSON_MODIFY(@info, '$.surname', 'Smith');         -- add a property
SET @info = JSON_MODIFY(@info, 'append $.skills', 'Azure');   -- append to an array
PRINT @info;
-- {"name":"Mike","skills":["C#","SQL","Azure"],"surname":"Smith"}

DECLARE @stats NVARCHAR(100) = N'{"click_count": 173}';
SET @stats = JSON_MODIFY(@stats, '$.click_count', CAST(JSON_VALUE(@stats, '$.click_count') AS INT) + 1);
PRINT @stats;
-- {"click_count": 174}

Setting a property to NULL with JSON_MODIFY removes it completely, which is how you delete or rename a property.


However, there is a catch: 2016 has no JSON data type. Your JSON lives in an NVARCHAR column, and SQL Server parses it every time you read it. Unfortunately, a real native JSON type doesn't show up until SQL Server 2025.


COMPRESS and DECOMPRESS


COMPRESS uses the GZIP algorithm to shrink a value into VARBINARY(MAX), right inside SQL Server. If you have a large table full of logs or JSON payloads you rarely read, this saves a lot of space.

DECLARE @jsontext VARCHAR(MAX) = '[{"name": "Albania", "code": "AL"},{"name": "Algeria", "code": "DZ"}]';
-- In my demo this was the full list of every country, 9,208 bytes

DECLARE @TestTable TABLE
(
    Id INT PRIMARY KEY IDENTITY,
    CompressedData VARBINARY(MAX),
    UnCompressedData VARCHAR(MAX),
    JSONData AS CAST(DECOMPRESS(CompressedData) AS VARCHAR(MAX))
);

INSERT INTO @TestTable (CompressedData, UnCompressedData)
VALUES (COMPRESS(@jsontext), @jsontext);

SELECT
    DATALENGTH(UnCompressedData) AS UncompressedSize,
    DATALENGTH(CompressedData) AS CompressedSize
FROM
    @TestTable;

With the full country list, 9,208 bytes went down to 2,300 bytes. That's about a 75% reduction.

Keep in mind that DECOMPRESS returns VARBINARY, so you have to CAST it back to the original type, and it must match the type you compressed (VARCHAR vs. NVARCHAR matters). You also can't index or search inside a compressed value.


Live Query Statistics


Before 2016, you only got the actual execution plan after the query finished. With Live Query Statistics in SQL Server Management Studio (SSMS), you watch the plan run in real time: row counts, elapsed time, operator progress, and live warnings. For a query that runs for 40 minutes, seeing which operator is stuck is a game changer.


Turn it on with 'Include Live Query Statistics' on the toolbar before you execute. Keep in mind that collecting live stats adds overhead, so be careful running it on a busy production server.


Always Encrypted


Always Encrypted encrypts sensitive columns on the client side. SQL Server only ever sees ciphertext, so even a sysadmin can't read the values. Banks have been all over this one.


There are two kinds of encryption:

  • Randomized: encrypt the same value twice, and you get two different results. It's the most secure, but you can't join, filter, or group on it.

  • Deterministic: the same value always encrypts the same way. It's less secure, but it supports equality in a WHERE clause, joins, DISTINCT, and GROUP BY.


You start with a column master key, which points to a certificate, then a column encryption key, then the table:

CREATE COLUMN MASTER KEY [CMK]
WITH
(
    KEY_STORE_PROVIDER_NAME = N'MSSQL_CERTIFICATE_STORE',
    KEY_PATH = N'CurrentUser/My/32714BF3CD4EBD97E1E952E8DE2BCC0231521E8C'
);
GO

-- The ENCRYPTED_VALUE is generated for you by the SSMS wizard or PowerShell
CREATE COLUMN ENCRYPTION KEY [CEK]
WITH VALUES
(
    COLUMN_MASTER_KEY = [CMK],
    ALGORITHM = 'RSA_OAEP',
    ENCRYPTED_VALUE = 0x016E000001630075007200720065006E0074...
);
GO

CREATE TABLE dbo.Patients
(
    PatientId INT IDENTITY(1, 1) NOT NULL CONSTRAINT PK_Patients PRIMARY KEY CLUSTERED,
    SSN NVARCHAR(11) COLLATE Latin1_General_BIN2
        ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = [CEK],
                        ENCRYPTION_TYPE = Deterministic,
                        ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NOT NULL,
    FirstName NVARCHAR(50) NULL,
    LastName NVARCHAR(50) NULL,
    BirthDate DATETIME2(7)
        ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = [CEK],
                        ENCRYPTION_TYPE = Randomized,
                        ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NOT NULL
);

On the application side, it's one setting in the connection string, and your inserts have to use parameters:

"Data Source=server63; Integrated Security=true; Column Encryption Setting=enabled";

cmd.CommandText = @"INSERT INTO dbo.Patients (SSN, FirstName, LastName, BirthDate)
                    VALUES (@SSN, @FirstName, @LastName, @BirthDate);";

SqlParameter paramSSN = cmd.CreateParameter();
paramSSN.ParameterName = @"@SSN";
paramSSN.DbType = DbType.String;
paramSSN.Value = ssn;
paramSSN.Size = 11;
cmd.Parameters.Add(paramSSN);
// ...same for the other parameters
cmd.ExecuteNonQuery();

A couple of things to keep in mind:

  • Keep using Transparent Data Encryption (TDE). Always Encrypted protects specific columns; TDE protects the files.

  • The certificate has to be in the certificate store on the client machine or the web/app server. No certificate, no plaintext.

  • Deterministic columns need a BIN2 collation.

  • In 2016, the client support was .NET Framework 4.6 and up, and 4.6.2 had a known issue with intermittent decryption failures. Use a current driver.


Dynamic Data Masking


Dynamic Data Masking (DDM) shows masked values to users without privileged access, while users with the UNMASK permission see the real data.

CREATE TABLE dbo.Employees
(
    EmployeeId INT NOT NULL IDENTITY(1, 1),
    FirstName VARCHAR(25) NOT NULL,
    LastName VARCHAR(25) NOT NULL,
    CreditCard VARCHAR(16) NULL,
    Salary INT NULL,
    EmailAddress VARCHAR(50) NULL,
    PhoneNumber VARCHAR(12) NULL
);
GO

ALTER TABLE dbo.Employees ALTER COLUMN Salary ADD MASKED WITH (FUNCTION = 'default()');
ALTER TABLE dbo.Employees ALTER COLUMN CreditCard ADD MASKED WITH (FUNCTION = 'partial(2,"XXXX",2)');
ALTER TABLE dbo.Employees ALTER COLUMN EmailAddress ADD MASKED WITH (FUNCTION = 'email()');
ALTER TABLE dbo.Employees ALTER COLUMN PhoneNumber ADD MASKED WITH (FUNCTION = 'partial(5,"XXXXXXX",0)');
GO

INSERT INTO dbo.Employees (FirstName, LastName, CreditCard, Salary, EmailAddress, PhoneNumber)
VALUES ('Jeff', 'Taylor', '1234123412341234', 12000, 'jtaylor@mydomain.com', '123-123-1234');

To test this simply, create a read-only user and look at the table as that user:

CREATE USER TestUser WITHOUT LOGIN;
ALTER ROLE db_datareader ADD MEMBER TestUser;

EXECUTE AS USER = 'TestUser';
SELECT * FROM dbo.Employees;   -- credit card, salary, email and phone are masked
REVERT;

GRANT UNMASK TO TestUser;
EXECUTE AS USER = 'TestUser';
SELECT * FROM dbo.Employees;   -- everything is visible
REVERT;

REVOKE UNMASK FROM TestUser;

This is a quick and easy add for production environments where developers need to query real tables.


However, there is a catch: masking isn't encryption, and it isn't a security boundary. A user who can run ad hoc queries can still guess a masked value with something like WHERE Salary > 100000. Use it to keep sensitive data off people's screens, not to protect it from someone determined.


Row-Level Security


Row-Level Security (RLS) filters which rows a user can see, using a predicate function and a security policy. The application doesn't change. The query doesn't change. SQL Server applies the filter for you.

CREATE SCHEMA Security;
GO

CREATE FUNCTION Security.fn_SalesRepFilter (@SalesRep SYSNAME)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN
    SELECT 1 AS Result
    WHERE @SalesRep = USER_NAME()
       OR USER_NAME() = 'SalesManager';
GO

CREATE SECURITY POLICY Security.SalesFilter
    ADD FILTER PREDICATE Security.fn_SalesRepFilter(SalesRep) ON dbo.Orders
    WITH (STATE = ON);

The criteria can be as simple as a user ID or as complicated as you want. You can even ALTER the security policy to point at a different function, based on time of day or anything else, without disabling it.


Keep in mind that the predicate function runs for every row the query touches, so keep it simple and make sure the columns it uses are indexed.


Query Store


Think of Query Store as the flight recorder, or black box, for your database. It captures every query, its execution plans, and its runtime statistics: CPU, memory, logical reads, and plan changes over time.

ALTER DATABASE [YourDatabase] SET QUERY_STORE = ON;
ALTER DATABASE [YourDatabase] SET QUERY_STORE (OPERATION_MODE = READ_WRITE);

Let's say you have a stored procedure with some parameter sniffing. For those who haven't run into it, parameter sniffing is when SQL Server compiles a plan for the first parameter value it sees, then reuses that plan for every value after it, even when it's a terrible fit. One customer has 10 orders, another has 10 million, and they both get the same plan.


With Query Store, you can find the good plan in the history and force it:

EXEC sp_query_store_force_plan @query_id = 48, @plan_id = 49;

-- And when you've fixed the real problem
EXEC sp_query_store_unforce_plan @query_id = 48, @plan_id = 49;

It's also the easiest way I know to compare performance before and after a deployment or an upgrade. Turn it on, deploy, and look at the regressed queries report.


Keep in mind that forcing a plan is a band-aid while you fix the query or the indexes. It isn't the fix. Also, Query Store is on by default for new databases starting in SQL Server 2022, but on 2016 you have to turn it on yourself.


Temporal Tables


Data is rarely static. A system-versioned temporal table keeps the full history of every row, with start and end timestamps, so you can query the table as of any point in time. Each temporal table is actually two tables: one for current data and one for history. SQL Server maintains both, and it doesn't use a trigger to do it.

CREATE SCHEMA History;
GO

CREATE TABLE dbo.MyTemporalTable
(
    MyTemporalTableId INT NOT NULL IDENTITY(1, 1),
    UserName VARCHAR(25) NOT NULL,
    UserGroupId INT NOT NULL,
    CreatedDatetime DATETIME2(7) NOT NULL CONSTRAINT DF_MyTemporalTable_CreatedDatetime DEFAULT (GETDATE()),
    ModifiedDatetime DATETIME2(7) NULL,
    SysStartTime DATETIME2(7) GENERATED ALWAYS AS ROW START NOT NULL,
    SysEndTime DATETIME2(7) GENERATED ALWAYS AS ROW END NOT NULL,
    PERIOD FOR SYSTEM_TIME (SysStartTime, SysEndTime),
    CONSTRAINT PK_MyTemporalTable PRIMARY KEY (MyTemporalTableId)
)
WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = History.MyTemporalTable));
GO

Now you can ask what the table looked like at any moment, or across a range:

-- As of a point in time
SELECT * FROM dbo.MyTemporalTable
FOR SYSTEM_TIME AS OF '2026-11-04 20:32:54'
WHERE UserGroupId = 1;

-- Every version of the rows between two times
DECLARE @Start DATETIME2 = '2026-11-04 20:32:54', @End DATETIME2 = '2026-11-04 20:35:00';
SELECT * FROM dbo.MyTemporalTable
FOR SYSTEM_TIME BETWEEN @Start AND @End
WHERE UserGroupId = 1;

Remember that UPDATE with no WHERE clause from the top of this post? The old rows are sitting in the history table. Query them AS OF a minute before the mistake, and put them back. No restore. No downtime.


A couple of things to keep in mind:

  • The History schema has to exist before you create the table.

  • You can't just drop a temporal table. Turn off SYSTEM_VERSIONING first, then drop both the current table and the history table, or the history table hangs around as a regular table.

  • The times are stored in UTC.

  • On a high-churn table, the history grows fast. I recommend page compression on the history table.


In-Memory OLTP


One more quick one. In-Memory OLTP shipped in 2012, but it was very limited. In 20,16 they picked up LEFT and RIGHT OUTER JOIN, SELECT DISTINCT, OR and NOT, subqueries in every clause of a SELECT, nested stored procedure calls, UNION and UNION ALL, and all the built-in math functions. That made them practical for a lot more real code.


Conclusion


JSON, DROP IF EXISTS, and temporal tables change how you write code day to day, and Query Store changes how you troubleshoot it.


Next up in the series is SQL Server 2017, where SQL Server moved to Linux and Docker and picked up a handful of string functions I use constantly.


If you're using any of these, or you've got a temporal table that saved your Friday afternoon, I'd love to hear about it. Feel free to reach out or comment below!

Comments


©2021-2026 by Jeff Taylor

bottom of page