SQL Server Row Level Security (RLS) is one of the top new features shipped in SQL Server 2016. With RLS, you can control access to rows in a table based on the characteristics of the user executing a query.
The access restriction logic is located in the database tier and access restrictions are always applied, thus they cannot be skipped.
SQL Server Row Level Security by Example
Below I will showcase SQL Server Row-Level Security with the use of a simple scenario. This example features a fictitious school’s database and more specifically a table containing the school’s student records. Each student is assigned an advisor. By using Row-Level Security, it is possible for each advisor to see only the records of his students. In the same scenario, only the school principal can view all student records.
--
-- Row Level Security Example
--
USE master;
GO
--Create sample database
CREATE DATABASE RLSDemoDB;
GO
--Use the sample database
USE RLSDemoDB;
GO
--Create four database users
CREATE USER Advisor1 WITHOUT LOGIN;
CREATE USER Advisor2 WITHOUT LOGIN;
CREATE USER Advisor3 WITHOUT LOGIN;
CREATE USER Principal WITHOUT LOGIN;
--Create the students table
CREATE TABLE tblStudents
(
code VARCHAR(10) NOT NULL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
advisorCode sysname,
classID INT,
GPA FLOAT
);
--Insert sample data
INSERT tblStudents
VALUES ( 'ST001', 'Student1','Advisor1', 1,3.2),
( 'ST002', 'Student2','Advisor1', 3,3.3),
( 'ST003', 'Student3','Advisor1', 5,2.8),
( 'ST004', 'Student4','Advisor2', 2,3.9),
( 'ST005', 'Student5','Advisor2', 4,3.1),
( 'ST006', 'Student6','Advisor2', 5,1.8),
( 'ST007', 'Student7','Advisor3', 6,2.2),
( 'ST008', 'Student8','Advisor3', 4,3.7),
( 'ST009', 'Student9','Advisor3', 3,3.6),
( 'ST010', 'Student10','Advisor4',2,3.5)
GO
Strengthen your SQL Server Administration Skills – Enroll to our Online Course!
Via the course, you will learn essential hands-on SQL Server Administration tips on SQL Server maintenance, security, performance, integration, error handling and more. Many live demonstrations and downloadable resources included!
(Lifetime Access/ Live Demos / Downloadable Resources and more!)
Let’s check the table contents before enabling the security policy:
Now let’s grant SELECT access to all users which are the three advisors and the principal:
--Grant SELECT access to users
GRANT SELECT ON tblStudents TO Advisor1;
GRANT SELECT ON tblStudents TO Advisor2;
GRANT SELECT ON tblStudents TO Advisor3;
GRANT SELECT ON tblStudents TO Principal;
GO
Now it’s time to create the Security policy. First we have to create the schema:
--Create security schema
CREATE SCHEMA Security;
GO
Then, we need to create the function that will be used for checking the executing user:
--Create function that checks the executing user
CREATE FUNCTION Security.fn_securitypredicate(@advisorCode AS sysname)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN SELECT 1 AS fn_securitypredicate_result
WHERE @advisorCode= USER_NAME() OR USER_NAME() = 'Principal';
GO
Finally we create and enable the security policy which uses the schema and the function created above:
--Create security policy
CREATE SECURITY POLICY StudentFilter
ADD FILTER PREDICATE Security.fn_securitypredicate(advisorCode)
ON dbo.tblStudents
WITH (STATE = ON);
GO
Now let’s retrieve the records from the the tblStudents table, each time within the context of a different user (i.e. advisor1, advisor2, advisor3 and principal).
If we execute the above query as the user ‘Advisor1‘ we can only see the student records that have ‘Advisor1’ as their advisor:
If we execute the above query as the user ‘Advisor2‘ we can only see the student records that have ‘Advisor2’ as their advisor:
If we execute the above query as the user ‘Advisor3‘ we can only see the student records that have ‘Advisor3’ as their advisor:
If we execute the above query as the user ‘Principal‘ we can see all student records:
If we disable the policy, then we return to the original state where all the records are retrieved from the tblStudents table within the context of any user that was granted the SELECT permission on the table:
From the above example you can see that it’s quite easy to control access to your data at the most granular level in the database, that is the record level, by using Row-Level Security in SQL Server 2016 or later.
Secure your SQL Server Instances with DBA Security Advisor
DBA Security Advisor, is our SQL Server security tool, which can help you assess your SQL Server instances against a rich set of security checks. The assessment report, includes recommendations and remediation scripts that can help you better secure your SQL Server instances and databases (learn more…).
Artemakis Artemiou is a seasoned Senior Database and AI/Automation Architect with over 20 years of expertise in the IT industry. As a Certified Database, Cloud, and AI professional, he has been recognized as a thought leader, earning the prestigious Microsoft Data Platform MVP title for nine consecutive years (2009-2018). Driven by a passion for simplifying complex topics, Artemakis shares his expertise through articles, online courses, and speaking engagements. He empowers professionals around the globe to excel in Databases, Cloud, AI, Automation, and Software Development. Committed to innovation and education, Artemakis strives to make technology accessible and impactful for everyone.
Views:6,396
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent. Read More
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
Cookie
Duration
Description
cookielawinfo-checkbox-analytics
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional
11 months
The cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy
11 months
The cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.