Category: Databases

Create scalar functions (DP-800 Exam Prep)

This post is a part of the DP-800: Developing AI-Enabled Database Solutions Exam Prep Hub.
This topic falls under these sections:
Design and develop database solutions (35–40%)
   --> Implement programmability objects
      --> Create scalar functions


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Introduction

Scalar functions are reusable database objects that encapsulate business logic and return a single scalar value (such as an integer, string, date, or decimal). They allow developers to centralize calculations, formatting rules, and validation logic, reducing code duplication and improving maintainability.

Scalar functions are widely used in SQL Server and Azure SQL Database applications for tasks such as calculating discounts, formatting names, determining tax amounts, converting units, and implementing business rules. They are also useful in AI-enabled database solutions for standardizing data transformations and feature calculations before data is consumed by analytics or AI models.

For the DP-800: Developing AI-Enabled Database Solutions certification exam, you should understand:

  • What scalar functions are
  • How to create, modify, and delete scalar functions
  • User-defined scalar functions versus built-in functions
  • Function parameters and return values
  • Deterministic and nondeterministic functions
  • Inline scalar function optimization (scalar UDF inlining)
  • Performance considerations
  • Best practices for implementation

Understanding scalar functions is important because they promote reusable, maintainable, and consistent business logic.


What Is a Scalar Function?

A scalar function is a database object that:

  • Accepts zero or more input parameters
  • Executes one or more T-SQL statements
  • Returns exactly one scalar value

Examples of scalar values include:

  • Integer
  • Decimal
  • Date
  • Time
  • String
  • Bit
  • Uniqueidentifier

Unlike stored procedures, scalar functions always return a single value and can often be used within SQL expressions.


Built-In vs. User-Defined Scalar Functions

SQL Server includes many built-in scalar functions.

Examples include:

  • UPPER()
  • LOWER()
  • LEN()
  • ROUND()
  • ABS()
  • YEAR()
  • MONTH()
  • DATEADD()
  • ISNULL()
  • COALESCE()

Developers can also create user-defined scalar functions (UDFs) when built-in functionality does not meet business requirements.


Creating a Scalar Function

Basic syntax:

CREATE FUNCTION dbo.fnCalculateTax
(
@Amount DECIMAL(10,2)
)
RETURNS DECIMAL(10,2)
AS
BEGIN
RETURN @Amount * 0.07;
END;

The function accepts one parameter and returns the calculated tax amount.


Calling a Scalar Function

A scalar function is invoked by referencing its name.

Example:

SELECT dbo.fnCalculateTax(100.00);

Result:

7.00

Scalar functions can also be used within SELECT statements.

Example:

SELECT
InvoiceID,
Amount,
dbo.fnCalculateTax(Amount) AS TaxAmount
FROM Sales.Invoices;

Using Multiple Parameters

Functions can accept multiple parameters.

Example:

CREATE FUNCTION dbo.fnCalculateTotal
(
@Price DECIMAL(10,2),
@Quantity INT
)
RETURNS DECIMAL(10,2)
AS
BEGIN
RETURN @Price * @Quantity;
END;

Usage:

SELECT dbo.fnCalculateTotal(25.00,4);

Returns:

100.00

Using Local Variables

Functions may declare local variables.

Example:

CREATE FUNCTION dbo.fnGetDiscount
(
@Amount DECIMAL(10,2)
)
RETURNS DECIMAL(10,2)
AS
BEGIN
DECLARE @Discount DECIMAL(10,2);
IF @Amount >= 1000
SET @Discount = @Amount * 0.10;
ELSE
SET @Discount = @Amount * 0.05;
RETURN @Discount;
END;

Returning Character Values

Scalar functions frequently return strings.

Example:

CREATE FUNCTION dbo.fnFullName
(
@FirstName NVARCHAR(50),
@LastName NVARCHAR(50)
)
RETURNS NVARCHAR(101)
AS
BEGIN
RETURN @FirstName + ' ' + @LastName;
END;

Usage:

SELECT dbo.fnFullName('John','Smith');

Returns:

John Smith

Returning Dates

Functions can return date values.

Example:

CREATE FUNCTION dbo.fnNextYear
(
@CurrentDate DATE
)
RETURNS DATE
AS
BEGIN
RETURN DATEADD(YEAR,1,@CurrentDate);
END;

Using Functions in Queries

Scalar functions may appear in:

  • SELECT
  • WHERE
  • ORDER BY
  • GROUP BY (when appropriate)
  • HAVING
  • Computed columns
  • CHECK constraints (subject to determinism and other SQL Server rules)

Example:

SELECT
EmployeeID,
dbo.fnFullName(FirstName,LastName) AS EmployeeName
FROM HumanResources.Employees;

Deterministic Functions

A deterministic function always returns the same result when given the same input values.

Example:

Input: 10
Output: 20

The result never changes.

Examples include:

  • Mathematical calculations
  • String manipulation
  • Unit conversions

Deterministic functions are important for indexed views, persisted computed columns, and other features that require predictable results.


Nondeterministic Functions

A nondeterministic function can return different results even with identical inputs.

Examples:

  • GETDATE()
  • SYSDATETIME()
  • NEWID()
  • RAND() (without a fixed seed)

User-defined scalar functions that rely on nondeterministic functions also become nondeterministic.


Scalar UDF Inlining (SQL Server 2019 and Later)

Prior to SQL Server 2019, scalar UDFs often introduced significant performance overhead because they executed row by row.

SQL Server 2019 introduced scalar UDF inlining, allowing eligible scalar functions to be automatically transformed into relational expressions during query optimization.

Benefits include:

  • Reduced CPU usage
  • Improved query performance
  • Better parallelism
  • Fewer context switches

Not every scalar function qualifies for inlining. SQL Server considers factors such as the function’s logic, supported constructs, and compatibility level.

For the DP-800 exam, it is important to understand that scalar UDF inlining can significantly improve performance for eligible functions.


Altering a Function

Functions can be modified using ALTER FUNCTION.

Example:

ALTER FUNCTION dbo.fnCalculateTax
(
@Amount DECIMAL(10,2)
)
RETURNS DECIMAL(10,2)
AS
BEGIN
RETURN @Amount * 0.08;
END;

Dropping a Function

Example:

DROP FUNCTION dbo.fnCalculateTax;

This removes the function from the database.


Viewing a Function Definition

Developers can examine a function’s definition using:

sp_helptext 'dbo.fnCalculateTax';

Or:

SELECT OBJECT_DEFINITION(OBJECT_ID('dbo.fnCalculateTax'));

Schema Binding

Scalar functions may use WITH SCHEMABINDING.

Example:

CREATE FUNCTION dbo.fnSquare
(
@Value INT
)
RETURNS INT
WITH SCHEMABINDING
AS
BEGIN
RETURN @Value * @Value;
END;

Schema binding:

  • Prevents incompatible schema changes
  • Helps ensure object consistency
  • May be required for certain database features

Error Handling

Scalar functions have several limitations compared to stored procedures.

For example:

  • They cannot use TRY...CATCH.
  • They cannot execute dynamic SQL (EXEC or sp_executesql).
  • They cannot modify database state (such as inserting into permanent user tables).
  • They cannot start or commit transactions.

Because of these restrictions, scalar functions should contain focused, side-effect-free logic.


Scalar Functions vs. Stored Procedures

FeatureScalar FunctionStored Procedure
Returns one valueYesNo
Can be used in SELECT statementsYesNo
Can accept parametersYesYes
Returns a scalar data typeYesNo
Performs complex procedural operationsLimitedYes
Can modify database stateNoYes

Scalar Functions vs. Table-Valued Functions

FeatureScalar FunctionTable-Valued Function
Returns one valueYesNo
Returns a tableNoYes
Used in expressionsYesLimited
Suitable for row calculationsYesNo

AI-Enabled Database Scenarios

Scalar functions are useful in AI-enabled database solutions for standardizing calculations and transformations.

Examples include:

  • Calculating confidence score categories
  • Normalizing numeric values
  • Formatting prompts before storage
  • Standardizing feature values
  • Creating reusable text-cleaning logic
  • Calculating similarity thresholds
  • Generating reusable business metrics
  • Computing feature engineering values

Using reusable functions helps ensure consistent preprocessing across AI workflows.


Performance Considerations

Although scalar functions improve code reuse, developers should be aware of performance implications.

Consider the following:

  • Excessive scalar function calls on millions of rows can impact performance.
  • Scalar UDF inlining in SQL Server 2019 and later can significantly reduce overhead for eligible functions.
  • Keep functions simple and deterministic whenever possible.
  • Avoid unnecessary computations inside frequently executed functions.
  • Test execution plans when scalar functions are used in large queries.

Best Practices

  • Keep scalar functions focused on a single task.
  • Use descriptive naming conventions such as fnCalculateTax.
  • Keep functions deterministic when practical.
  • Avoid unnecessary complexity.
  • Take advantage of scalar UDF inlining where applicable.
  • Document business logic contained in functions.
  • Reuse functions rather than duplicating code.
  • Test functions with representative data volumes.
  • Monitor execution plans for performance bottlenecks.

Common Exam Tips

For the DP-800 exam, remember these key points:

  • Scalar functions return exactly one value.
  • Scalar functions can accept zero or more parameters.
  • They can be used within SELECT, WHERE, ORDER BY, and other SQL expressions.
  • Built-in scalar functions differ from user-defined scalar functions.
  • ALTER FUNCTION modifies an existing function.
  • DROP FUNCTION removes a function.
  • Deterministic functions always return the same result for the same inputs.
  • SQL Server 2019 introduced scalar UDF inlining to improve the performance of eligible scalar functions.
  • Scalar functions cannot modify permanent database objects or execute dynamic SQL.

Practice Exam Questions

Question 1

A developer wants to create a reusable database object that accepts one or more parameters and returns a single calculated value. Which object should be created?

A. Scalar function

B. View

C. Stored procedure

D. Table-valued function

Answer: A

Explanation: A scalar function is designed to accept parameters and return a single scalar value that can be used within SQL expressions.


Question 2

Which statement correctly describes a user-defined scalar function?

A. It always returns a table.

B. It returns exactly one scalar value.

C. It cannot accept parameters.

D. It automatically creates an index.

Answer: B

Explanation: A scalar function returns a single scalar value, such as an integer, string, date, or decimal, and may accept zero or more parameters.


Question 3

A developer wants to use a custom calculation directly within a SELECT statement for every returned row. Which database object is most appropriate?

A. Trigger

B. View

C. Scalar function

D. Sequence

Answer: C

Explanation: Scalar functions can be called directly within SELECT statements and expressions, making them suitable for reusable row-level calculations.


Question 4

Which SQL Server version introduced scalar UDF inlining to improve the performance of eligible scalar functions?

A. SQL Server 2012

B. SQL Server 2014

C. SQL Server 2019

D. SQL Server 2017

Answer: C

Explanation: SQL Server 2019 introduced scalar UDF inlining, allowing eligible scalar functions to be optimized into relational expressions during query compilation.


Question 5

Which of the following is an example of a nondeterministic function?

A. ABS()

B. LEN()

C. GETDATE()

D. UPPER()

Answer: C

Explanation: GETDATE() returns the current system date and time, which changes over time, making it nondeterministic.


Question 6

A developer needs to modify the definition of an existing scalar function while keeping the same object. Which statement should be used?

A. CREATE FUNCTION

B. ALTER FUNCTION

C. UPDATE FUNCTION

D. MODIFY FUNCTION

Answer: B

Explanation: ALTER FUNCTION changes the definition of an existing function without requiring it to be dropped and recreated.


Question 7

Which statement about scalar functions is correct?

A. They can insert rows into permanent user tables.

B. They can execute dynamic SQL.

C. They can begin and commit transactions.

D. They return a single scalar value and can be used in SQL expressions.

Answer: D

Explanation: Scalar functions return one value and can be used in SELECT, WHERE, ORDER BY, and other SQL expressions. They cannot perform operations such as modifying permanent tables or executing dynamic SQL.


Question 8

Why are deterministic scalar functions important?

A. They always create clustered indexes.

B. They always execute faster than built-in functions.

C. They always return the same result for the same input values and are required for certain SQL Server features such as indexed views and persisted computed columns.

D. They automatically improve query parallelism.

Answer: C

Explanation: Deterministic functions consistently return the same output for the same inputs, making them suitable for features that require predictable results.


Question 9

Which statement best describes the relationship between scalar functions and stored procedures?

A. Both can always be used interchangeably within a SELECT statement.

B. Scalar functions return a single value and can be used in SQL expressions, whereas stored procedures are designed for procedural operations and are not used as expressions.

C. Stored procedures always return a single scalar value.

D. Scalar functions can modify permanent tables just like stored procedures.

Answer: B

Explanation: Scalar functions are expression-oriented and return one value, while stored procedures are intended for broader procedural tasks and cannot be invoked as scalar expressions in queries.


Question 10

How can scalar functions benefit AI-enabled database solutions?

A. They automatically train machine learning models.

B. They replace vector indexes.

C. They eliminate the need for ETL processes.

D. They provide reusable and consistent data transformations that help standardize inputs for analytics and AI workloads.

Answer: D

Explanation: Scalar functions encapsulate reusable business logic and transformations, helping ensure that AI models and analytical processes receive consistently prepared data.


Go to the DP-800 Exam Prep Hub main page

Create views (DP-800 Exam Prep)

This post is a part of the DP-800: Developing AI-Enabled Database Solutions Exam Prep Hub.
This topic falls under these sections:
Design and develop database solutions (35–40%)
   --> Implement programmability objects
      --> Create views


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Introduction

Views are one of the most commonly used database objects in SQL Server and Azure SQL Database. A view is a virtual table whose contents are defined by a SQL query. Unlike a physical table, a standard view does not store data itself. Instead, it stores the SELECT statement that retrieves data from one or more underlying tables or other views.

Views simplify complex queries, improve security, promote code reuse, and provide an abstraction layer between applications and the underlying database schema. They are frequently used in reporting solutions, business intelligence applications, APIs, and AI-enabled database solutions where consistent access to curated data is essential.

For the DP-800: Developing AI-Enabled Database Solutions certification exam, you should understand:

  • What views are and when to use them
  • How to create and modify views
  • Simple vs. complex views
  • Updatable views
  • Schema binding
  • Indexed views
  • Security considerations
  • Best practices for view design

Understanding views is an important skill because they simplify application development while improving maintainability and security.


What Is a View?

A view is a stored SELECT statement that presents data as though it were a table.

Applications can query a view just like a table.

Example:

SELECT *
FROM dbo.vwCustomerOrders;

Although it behaves like a table, the data is retrieved from the underlying objects each time the view is queried (unless the view is indexed).


Benefits of Views

Views provide numerous advantages, including:

  • Simplifying complex queries
  • Hiding unnecessary columns
  • Restricting sensitive data
  • Providing a consistent interface for applications
  • Improving code maintainability
  • Supporting data abstraction
  • Enabling reusable business logic
  • Simplifying report development

Views help separate the logical database model from the physical implementation.


Creating a View

Basic syntax:

CREATE VIEW dbo.vwCustomers
AS
SELECT
CustomerID,
FirstName,
LastName,
EmailAddress
FROM dbo.Customers;

Applications can query the view:

SELECT *
FROM dbo.vwCustomers;

Creating a View from Multiple Tables

Views commonly combine data from related tables.

Example:

CREATE VIEW dbo.vwCustomerOrders
AS
SELECT
c.CustomerID,
c.FirstName,
c.LastName,
o.OrderID,
o.OrderDate,
o.TotalAmount
FROM dbo.Customers AS c
INNER JOIN dbo.Orders AS o
ON c.CustomerID = o.CustomerID;

This view simplifies reporting by eliminating the need for repeated JOIN statements.


Simple Views

A simple view references a single table and contains little or no additional logic.

Example:

CREATE VIEW dbo.vwActiveProducts
AS
SELECT
ProductID,
ProductName,
Price
FROM dbo.Products
WHERE IsActive = 1;

Simple views are often updatable.


Complex Views

A complex view may include:

  • Multiple tables
  • JOINs
  • GROUP BY
  • Aggregate functions
  • UNION
  • DISTINCT
  • Calculated columns
  • Subqueries

Example:

CREATE VIEW dbo.vwMonthlySales
AS
SELECT
YEAR(OrderDate) AS SalesYear,
MONTH(OrderDate) AS SalesMonth,
SUM(TotalAmount) AS MonthlySales
FROM dbo.Orders
GROUP BY
YEAR(OrderDate),
MONTH(OrderDate);

Complex views are primarily used for reporting and analytics.


Using Aliases

Column aliases improve readability.

Example:

SELECT
CustomerID,
FirstName + ' ' + LastName AS FullName
FROM dbo.Customers;

Meaningful column names make views easier to consume.


Filtering Data

Views frequently filter rows.

Example:

CREATE VIEW dbo.vwOpenOrders
AS
SELECT *
FROM dbo.Orders
WHERE Status = 'Open';

Applications automatically see only open orders.


Using Calculated Columns

Views can include calculated values.

Example:

SELECT
ProductName,
UnitPrice,
Quantity,
UnitPrice * Quantity AS ExtendedPrice
FROM dbo.OrderDetails;

Calculated columns eliminate repeated calculations across applications.


Modifying a View

Views can be modified using:

ALTER VIEW dbo.vwCustomers
AS
SELECT
CustomerID,
FirstName,
LastName,
EmailAddress,
PhoneNumber
FROM dbo.Customers;

ALTER VIEW updates the stored definition while preserving permissions.


Deleting a View

To remove a view:

DROP VIEW dbo.vwCustomers;

Only the view is removed; the underlying tables remain unchanged.


Viewing the Definition of a View

Developers can inspect a view’s definition using:

sp_helptext 'dbo.vwCustomers';

Or:

SELECT OBJECT_DEFINITION(OBJECT_ID('dbo.vwCustomers'));

This is useful for maintenance and troubleshooting.


Updatable Views

Many views support INSERT, UPDATE, and DELETE operations.

Generally, a view is updatable when it:

  • References a single base table
  • Does not contain aggregate functions
  • Does not contain GROUP BY
  • Does not contain DISTINCT
  • Does not contain UNION
  • Does not contain calculated aggregate results

Example:

UPDATE dbo.vwCustomers
SET EmailAddress = 'newemail@example.com'
WHERE CustomerID = 100;

The underlying table is updated.


WITH CHECK OPTION

WITH CHECK OPTION prevents updates or inserts that would cause rows to no longer satisfy the view’s filter.

Example:

CREATE VIEW dbo.vwActiveEmployees
AS
SELECT *
FROM dbo.Employees
WHERE IsActive = 1
WITH CHECK OPTION;

This ensures that modifications through the view maintain its filtering criteria.


Schema Binding

Views can be created using WITH SCHEMABINDING.

Example:

CREATE VIEW dbo.vwCustomerSales
WITH SCHEMABINDING
AS
SELECT
CustomerID,
COUNT_BIG(*) AS OrderCount
FROM dbo.Orders
GROUP BY CustomerID;

Benefits include:

  • Prevents changes to referenced tables that would invalidate the view
  • Required for indexed views
  • Improves schema stability

When schema binding is used:

  • Table names must include the schema name.
  • Referenced tables cannot be dropped or modified in ways that break the view until the view is altered or dropped.

Indexed Views

Normally, views do not store data.

An indexed view stores the results of the view physically by creating a unique clustered index on the view.

Benefits:

  • Faster query performance
  • Reduced computation for expensive aggregations
  • Useful for reporting workloads

Requirements include:

  • WITH SCHEMABINDING
  • Deterministic expressions
  • Additional SQL Server restrictions
  • A unique clustered index created first

Example:

CREATE UNIQUE CLUSTERED INDEX IX_vwCustomerSales
ON dbo.vwCustomerSales(CustomerID);

Keep in mind that indexed views can improve read performance but may increase the cost of INSERT, UPDATE, and DELETE operations because the indexed view must also be maintained.


Views and Security

Views are commonly used to restrict access to sensitive information.

Example:

Base table:

EmployeeID
Name
Salary
SocialSecurityNumber

View:

EmployeeID
Name

Users receive access to the view instead of the underlying table.

This supports the principle of least privilege by exposing only the necessary columns and rows.


Nested Views

A view can reference another view.

Example:

Orders
vwOpenOrders
vwRecentOpenOrders

Although supported, excessive nesting can:

  • Reduce performance
  • Complicate troubleshooting
  • Make execution plans harder to understand

Microsoft generally recommends minimizing unnecessary layers of nested views.


Limitations of Views

Standard views:

  • Do not normally store data
  • Cannot accept parameters (use table-valued functions if parameters are required)
  • May become invalid if underlying objects change (unless schema binding is used)
  • May not always improve performance
  • Can become difficult to maintain if overly complex

Views vs. Tables

FeatureViewTable
Stores dataNo (except indexed views)Yes
Contains rows physicallyNormally noYes
Can join multiple tablesYesNo
Can simplify queriesYesNo
Used for abstractionYesLimited

Views vs. Stored Procedures

FeatureViewStored Procedure
Returns result setsYesYes
Accepts parametersNoYes
Can perform data modificationsLimitedYes
Reusable in SELECT statementsYesNo

AI-Enabled Database Scenarios

Views are valuable in AI-enabled database solutions because they provide a consistent and secure layer over operational data.

Common uses include:

  • Creating curated datasets for machine learning
  • Exposing only relevant columns for AI models
  • Simplifying feature engineering queries
  • Combining business data with vector metadata
  • Preparing reporting datasets for model evaluation
  • Restricting sensitive information before AI processing

Views help ensure that AI applications consume consistent, high-quality data while reducing the complexity of application queries.


Best Practices

  • Use meaningful and consistent naming conventions (for example, vwCustomerOrders).
  • Keep views focused on a single business purpose.
  • Avoid unnecessary nested views.
  • Use aliases to improve readability.
  • Use WITH SCHEMABINDING when appropriate, especially for indexed views.
  • Consider indexed views only when query performance benefits outweigh maintenance costs.
  • Grant permissions to views instead of base tables when restricting data access.
  • Document complex business logic contained within views.
  • Periodically review execution plans to ensure views are not introducing unnecessary overhead.

Common Exam Tips

For the DP-800 exam, remember these key points:

  • A view is a stored SELECT statement that behaves like a virtual table.
  • Standard views do not physically store data.
  • Indexed views physically store data after a unique clustered index is created.
  • ALTER VIEW modifies an existing view while preserving permissions.
  • WITH CHECK OPTION ensures rows modified through a view continue to satisfy the view’s filter.
  • WITH SCHEMABINDING prevents incompatible schema changes and is required for indexed views.
  • Simple views are often updatable; views containing aggregates, GROUP BY, DISTINCT, or UNION generally are not.
  • Views are commonly used to simplify queries and improve security.

Practice Exam Questions

Question 1

A developer wants to simplify a frequently used query that joins the Customers and Orders tables without duplicating the JOIN logic throughout an application. Which database object should be created?

A. A stored procedure

B. A trigger

C. A view

D. A sequence

Answer: C

Explanation: A view stores a SELECT statement that can join multiple tables, allowing applications to query the view instead of repeatedly writing the same JOIN logic.


Question 2

Which statement correctly describes a standard SQL Server view?

A. It always stores its data physically.

B. It stores the SELECT statement that defines the virtual table.

C. It automatically creates a clustered index.

D. It requires a PRIMARY KEY.

Answer: B

Explanation: A standard view stores only its definition (the SELECT statement). Data is retrieved from the underlying tables each time the view is queried.


Question 3

A database administrator wants to prevent changes to the underlying tables that would invalidate a view. Which option should be used when creating the view?

A. WITH CHECK OPTION

B. ENCRYPTION

C. WITH SCHEMABINDING

D. RECOMPILE

Answer: C

Explanation: WITH SCHEMABINDING binds the view to the schema of the referenced tables, preventing changes that would invalidate the view.


Question 4

Which statement about indexed views is correct?

A. They require a unique clustered index before additional indexes can be created.

B. They automatically update only once per day.

C. They cannot reference aggregate functions.

D. They never increase the cost of data modifications.

Answer: A

Explanation: An indexed view requires WITH SCHEMABINDING and a unique clustered index as the first index. Data modifications to underlying tables also update the indexed view.


Question 5

A view is defined with the following clause:

WITH CHECK OPTION

What is the primary purpose of this clause?

A. To encrypt the view definition.

B. To ensure that INSERT and UPDATE operations through the view continue to satisfy the view’s filtering criteria.

C. To improve query performance.

D. To automatically rebuild indexes.

Answer: B

Explanation: WITH CHECK OPTION prevents modifications through the view that would produce rows no longer visible through that view.


Question 6

Which characteristic generally allows a view to be updatable?

A. It contains GROUP BY and aggregate functions.

B. It contains a UNION operator.

C. It references a single base table without aggregate operations.

D. It contains DISTINCT and calculated aggregates.

Answer: C

Explanation: Simple views that reference a single base table and avoid constructs such as GROUP BY, DISTINCT, and UNION are often updatable.


Question 7

Which statement best describes an indexed view?

A. It always executes more slowly than a standard view.

B. It physically stores the results of the view after a unique clustered index is created.

C. It can only reference one table.

D. It cannot be queried using SELECT statements.

Answer: B

Explanation: Indexed views materialize their data through a unique clustered index, improving performance for certain read-heavy workloads.


Question 8

Why are views commonly used to improve database security?

A. They automatically encrypt data.

B. They replace the need for permissions.

C. They allow administrators to expose only selected columns and rows while restricting access to the underlying tables.

D. They prevent all updates to data.

Answer: C

Explanation: Views can limit the data users see, making them an effective way to implement the principle of least privilege.


Question 9

A developer modifies an existing view by using ALTER VIEW. What happens to the permissions already granted on that view?

A. They are automatically removed.

B. They are transferred to the underlying tables.

C. They are preserved.

D. They are converted to DENY permissions.

Answer: C

Explanation: Using ALTER VIEW changes the view definition while preserving existing permissions on the view.


Question 10

Which statement best explains why views are useful in AI-enabled database solutions?

A. They automatically generate machine learning models.

B. They replace the need for indexes.

C. They eliminate all data transformations.

D. They provide consistent, reusable, and secure datasets that simplify AI data preparation.

Answer: D

Explanation: Views provide a stable abstraction layer that exposes curated, consistent datasets while helping to restrict sensitive data, making them valuable for analytics and AI workloads.


Go to the DP-800 Exam Prep Hub main page

Design and implement partitioning for tables and indexes (DP-800 Exam Prep)

This post is a part of the DP-800: Developing AI-Enabled Database Solutions Exam Prep Hub.
This topic falls under these sections:
Design and develop database solutions (35–40%)
   --> Design and implement database objects
      --> Design and implement partitioning for tables and indexes


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Introduction

As databases grow from thousands to millions or even billions of rows, managing and querying data efficiently becomes increasingly challenging. Large tables can lead to longer query execution times, larger maintenance windows, slower backups, and increased index fragmentation. SQL Server and Azure SQL provide table and index partitioning to help address these challenges.

Partitioning divides a large table or index into smaller, more manageable pieces called partitions. Although users and applications continue to view the data as a single table, SQL Server stores and manages the data in separate partitions based on a defined partitioning strategy.

For the DP-800: Developing AI-Enabled Database Solutions certification exam, you should understand:

  • What partitioning is
  • Benefits and limitations of partitioning
  • Partition functions
  • Partition schemes
  • Partition elimination
  • Partition switching
  • Partitioned indexes
  • Maintenance strategies
  • Best practices

Partitioning is especially valuable in AI-enabled database solutions that store large volumes of historical, telemetry, or transactional data.


What Is Table Partitioning?

Table partitioning divides one logical table into multiple physical partitions.

Applications continue to query the table normally:

SELECT *
FROM Sales;

Internally, SQL Server stores the data across multiple partitions.

Example:

Sales Table
├── Partition 1 (2022)
├── Partition 2 (2023)
├── Partition 3 (2024)
└── Partition 4 (2025)

Each partition contains only a subset of the rows.


Why Partition Tables?

Partitioning improves the manageability of very large tables.

Benefits include:

  • Faster maintenance
  • Easier archival
  • Improved query performance through partition elimination
  • Faster index maintenance
  • Improved data loading
  • Simplified backup strategies
  • Better scalability

It is important to understand that partitioning alone does not automatically improve every query. Benefits are greatest when queries filter on the partitioning column.


Common Partitioning Scenarios

Partitioning is commonly used for:

  • Sales history
  • Financial transactions
  • IoT telemetry
  • Sensor data
  • Event logs
  • AI inference logs
  • Audit records
  • Web clickstream data
  • Time-series databases

Most implementations partition by date.


Horizontal vs. Vertical Partitioning

Horizontal Partitioning

Rows are divided across partitions.

Example:

Sales
-----------------------
2022 rows
2023 rows
2024 rows
2025 rows

SQL Server table partitioning is horizontal partitioning.


Vertical Partitioning

Columns are divided into separate tables.

Example:

Customer Table

  • CustomerID
  • Name
  • City

CustomerDetails Table

  • CustomerID
  • Biography
  • Photo

Vertical partitioning is a database design technique, not SQL Server table partitioning.


Partition Functions

A partition function determines how rows are assigned to partitions.

It defines boundary values.

Example:

CREATE PARTITION FUNCTION pfSalesDate
(DATE)
AS RANGE RIGHT
FOR VALUES
(
('2023-01-01'),
('2024-01-01'),
('2025-01-01')
);

The partition function divides data according to the specified boundary values.


RANGE LEFT vs. RANGE RIGHT

Partition functions support two boundary options.

RANGE LEFT

Boundary value belongs to the partition on the left.

Example:

Boundary:

100

Value 100 belongs to:

Partition 1

RANGE RIGHT

Boundary value belongs to the partition on the right.

Example:

Boundary:

100

Value 100 belongs to:

Partition 2

Candidates should understand the difference because it frequently appears in certification exams.


Partition Schemes

A partition function determines how rows are divided.

A partition scheme determines where those partitions are stored.

Example:

CREATE PARTITION SCHEME psSales
AS PARTITION pfSalesDate
ALL TO ([PRIMARY]);

Alternatively, different partitions may reside on different filegroups.

Example:

2022 → FG_2022
2023 → FG_2023
2024 → FG_2024
2025 → FG_2025

Creating a Partitioned Table

Example:

CREATE TABLE Sales
(
SaleID INT,
SaleDate DATE,
Amount MONEY
)
ON psSales(SaleDate);

Rows are automatically placed into the appropriate partition based on the SaleDate value.


Filegroups

Partitions can be stored in different filegroups.

Benefits include:

  • Independent backup
  • Independent restore
  • Better storage management
  • Distribution across storage devices

Although many Azure SQL Database deployments use the PRIMARY filegroup, understanding filegroups remains important for SQL Server and the DP-800 exam.


Partition Elimination

One of the biggest advantages of partitioning is partition elimination.

Instead of scanning every partition, SQL Server reads only the partitions needed for the query.

Example:

SELECT *
FROM Sales
WHERE SaleDate
BETWEEN '2025-01-01'
AND '2025-01-31';

SQL Server may read only the partition containing January 2025 data.

Benefits include:

  • Reduced I/O
  • Faster execution
  • Lower CPU usage

Partition elimination works best when predicates reference the partitioning column.


Partitioned Indexes

Indexes can also be partitioned.

Types include:

  • Clustered indexes
  • Nonclustered indexes
  • Columnstore indexes

A partitioned index aligns with the table partitions.


Aligned Indexes

An aligned index uses:

  • The same partition function
  • The same partition scheme

Benefits:

  • Easier maintenance
  • Faster partition switching
  • Simplified index rebuilds

Microsoft generally recommends aligned indexes whenever possible.


Non-Aligned Indexes

A non-aligned index uses different partitioning than the underlying table or is not partitioned at all.

Advantages:

  • Flexibility

Disadvantages:

  • More complex maintenance
  • Cannot participate in some partition operations
  • May reduce the benefits of partition switching

Partition Switching

Partition switching is one of SQL Server’s most powerful maintenance features.

Instead of copying millions of rows, SQL Server simply changes metadata.

Example:

Current Table
├── Partition 2024
├── Partition 2025
└── Partition 2026
Switch 2024
Archive Table

The operation completes very quickly because no data movement occurs.


Benefits of Partition Switching

Typical uses include:

  • Archiving old data
  • Loading new data
  • ETL processing
  • Data warehouse maintenance
  • Rolling window scenarios

Large tables can be maintained with minimal downtime.


Sliding Window Technique

Many databases maintain a rolling time window.

Example:

Keep:
2023
2024
2025
Remove:
2022
Add:
2026

Partition switching makes this process extremely efficient.


Index Maintenance

Large indexes can be rebuilt one partition at a time.

Example:

ALTER INDEX IX_Sales
ON Sales
REBUILD PARTITION = 4;

Benefits:

  • Shorter maintenance windows
  • Less locking
  • Reduced resource consumption

Statistics

Each partition maintains its own data distribution statistics.

Accurate statistics help the SQL Server Query Optimizer generate efficient execution plans.

Regular statistics updates remain important for partitioned tables.


Choosing a Partition Key

The partition key should:

  • Be commonly filtered
  • Divide data evenly
  • Support partition elimination
  • Match maintenance requirements

Good candidates include:

  • TransactionDate
  • OrderDate
  • EventDate
  • CustomerRegion
  • FiscalYear

Date columns are the most common partition keys.


When Not to Partition

Partitioning is not appropriate for every table.

Avoid partitioning when:

  • Tables are small.
  • Queries rarely filter on the partition key.
  • Maintenance requirements are minimal.
  • Administrative complexity outweighs the benefits.

Partitioning introduces additional design and maintenance considerations.


AI-Enabled Database Scenarios

Partitioning is valuable in AI-enabled solutions because AI systems often generate large volumes of data.

Examples include:

  • Prompt history
  • Chat logs
  • Model inference records
  • Telemetry
  • IoT streams
  • Sensor data
  • Feature store history
  • Training datasets
  • Experiment tracking

Partitioning enables efficient archival, querying, and maintenance of these growing datasets.


Best Practices

  • Partition only large tables that benefit from improved manageability or query performance.
  • Choose a partition key that aligns with common filtering patterns.
  • Use aligned indexes whenever practical.
  • Partition by date for most time-series workloads.
  • Use partition elimination to reduce unnecessary I/O.
  • Use partition switching for fast archival and data loading.
  • Monitor partition sizes to avoid skewed data distribution.
  • Keep statistics updated on partitioned tables.
  • Test execution plans to confirm partition elimination is occurring.

Common Exam Tips

For the DP-800 exam, remember these key points:

  • A partition function defines how rows are divided into partitions.
  • A partition scheme maps partitions to filegroups.
  • Partition elimination allows SQL Server to read only the necessary partitions when queries filter on the partition key.
  • Partition switching is a metadata operation and does not physically copy data.
  • Aligned indexes use the same partition function and partition scheme as the underlying table.
  • RANGE LEFT and RANGE RIGHT determine which partition contains the boundary value.
  • Partitioning improves manageability and can improve query performance, but it does not automatically make every query faster.

Practice Exam Questions

Question 1

A company stores ten years of sales data and frequently queries only the current month’s transactions. Which SQL Server feature can help reduce the amount of data scanned by these queries?

A. Database mirroring

B. Table partitioning

C. Row-level security

D. Dynamic data masking

Answer: B

Explanation: Table partitioning, combined with partition elimination, enables SQL Server to access only the relevant partition when queries filter on the partitioning column, reducing I/O and improving performance.


Question 2

What is the primary purpose of a partition function?

A. To define the physical storage location of partitions

B. To create indexes for each partition

C. To determine how rows are assigned to partitions based on boundary values

D. To rebuild fragmented indexes

Answer: C

Explanation: A partition function defines the partition boundaries and determines which partition stores each row.


Question 3

Which SQL Server object maps partitions to one or more filegroups?

A. Partition scheme

B. Partition function

C. File stream

D. Sequence

Answer: A

Explanation: A partition scheme associates the partitions defined by a partition function with specific filegroups.


Question 4

A query filters on the partitioning column of a partitioned table. Which optimization allows SQL Server to read only the required partitions?

A. Predicate pushdown

B. Partition elimination

C. Batch mode execution

D. Adaptive joins

Answer: B

Explanation: Partition elimination enables SQL Server to skip partitions that cannot contain qualifying rows, reducing I/O and improving performance.


Question 5

Which statement accurately describes partition switching?

A. It copies data row by row between tables.

B. It compresses partitions before moving them.

C. It moves an entire partition using a metadata operation without copying the data.

D. It permanently merges two partitions into one.

Answer: C

Explanation: Partition switching is a metadata-only operation that quickly transfers a partition between compatible tables without physically moving the data.


Question 6

Which partitioning strategy is most commonly used for large transactional and historical databases?

A. Partitioning by customer name

B. Partitioning by transaction date

C. Partitioning by product description

D. Partitioning by postal code

Answer: B

Explanation: Date-based partitioning is common because it supports efficient querying, maintenance, archival, and sliding-window scenarios.


Question 7

Which statement about aligned indexes is correct?

A. They always use a different partition scheme than the table.

B. They cannot be rebuilt independently.

C. They use the same partition function and partition scheme as the underlying table.

D. They eliminate the need for clustered indexes.

Answer: C

Explanation: An aligned index shares the same partition function and partition scheme as its table, simplifying maintenance and enabling features such as partition switching.


Question 8

What is the primary benefit of rebuilding an index one partition at a time?

A. It automatically repartitions the table.

B. It reduces maintenance impact by limiting the work to the affected partition.

C. It converts nonclustered indexes into clustered indexes.

D. It eliminates the need to update statistics.

Answer: B

Explanation: Rebuilding only the affected partition reduces resource usage, shortens maintenance windows, and minimizes locking compared to rebuilding the entire index.


Question 9

Which statement best describes RANGE RIGHT in a partition function?

A. Boundary values belong to the partition on the left.

B. Boundary values are ignored.

C. Boundary values are stored in every partition.

D. Boundary values belong to the partition on the right.

Answer: D

Explanation: With RANGE RIGHT, rows containing the boundary value are placed into the partition to the right of the boundary.


Question 10

A company maintains five years of historical telemetry data and archives the oldest year every January while adding a new year’s partition. Which partitioning technique best supports this maintenance strategy?

A. Computed columns

B. Filtered indexes

C. Sliding window partitioning using partition switching

D. Indexed views

Answer: C

Explanation: A sliding-window strategy combined with partition switching enables administrators to efficiently archive old partitions and add new ones with minimal downtime because the operation is metadata-based.


Go to the DP-800 Exam Prep Hub main page

Design and Implement SEQUENCES (DP-800 Exam Prep)

This post is a part of the DP-800: Developing AI-Enabled Database Solutions Exam Prep Hub.
This topic falls under these sections:
Design and develop database solutions (35–40%)
   --> Design and implement database objects
      --> Design and Implement SEQUENCES


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Introduction

Many database applications require automatically generated numeric values for records such as order numbers, invoice numbers, customer identifiers, shipment IDs, and transaction references. While SQL Server developers have traditionally relied on IDENTITY columns to generate sequential numbers, SQL Server also provides a more flexible object called a SEQUENCE.

A SEQUENCE is a user-defined database object that generates a sequence of numeric values according to rules that you specify. Unlike an IDENTITY column, a SEQUENCE is independent of any table and can be shared across multiple tables or applications.

For the DP-800: Developing AI-Enabled Database Solutions certification exam, you should understand:

  • What SEQUENCE objects are
  • How SEQUENCES differ from IDENTITY columns
  • How to create and use SEQUENCES
  • Sequence options such as START WITH, INCREMENT BY, MINVALUE, MAXVALUE, CYCLE, and CACHE
  • Performance considerations
  • Best practices and common use cases

Understanding SEQUENCES is important because they provide greater flexibility for generating unique numeric values across modern SQL Server and Azure SQL Database solutions.


What Is a SEQUENCE?

A SEQUENCE is a schema-bound database object that generates a series of numeric values.

Unlike an IDENTITY column:

  • It is independent of tables.
  • Multiple tables can use the same SEQUENCE.
  • Values can be generated before an INSERT occurs.
  • Applications can request values whenever needed.

The database maintains the current value of the sequence.


Common Use Cases

SEQUENCES are commonly used for:

  • Invoice numbers
  • Purchase order numbers
  • Ticket numbers
  • Customer IDs across multiple tables
  • Order tracking numbers
  • Shipment numbers
  • Financial transaction identifiers
  • Distributed applications
  • Data warehouse surrogate keys

SEQUENCE vs. IDENTITY

FeatureSEQUENCEIDENTITY
Independent database object
Bound to a table
Shared across multiple tables
Generate values before INSERT
Can restartLimited (DBCC CHECKIDENT)
Supports cycling
Supports cachingInternal only
Retrieved explicitlyAutomatically during INSERT

A common DP-800 exam objective is knowing when to choose a SEQUENCE instead of an IDENTITY column.


Creating a SEQUENCE

Basic syntax:

CREATE SEQUENCE dbo.OrderSequence
AS INT
START WITH 1
INCREMENT BY 1;

This sequence:

  • Starts at 1
  • Increments by 1
  • Generates INT values

Using NEXT VALUE FOR

Values are generated using the NEXT VALUE FOR function.

Example:

SELECT NEXT VALUE FOR dbo.OrderSequence;

Output:

1

The next execution returns:

2

Then:

3

Each call advances the sequence.


Using a SEQUENCE During INSERT

Example:

INSERT INTO Orders
(
OrderID,
CustomerID
)
VALUES
(
NEXT VALUE FOR dbo.OrderSequence,
1001
);

The generated sequence value becomes the OrderID.


Sharing a SEQUENCE Across Multiple Tables

One of the biggest advantages of SEQUENCES is that multiple tables can use the same object.

Example:

OrderSequence
┌─────┴─────┐
│ │
Orders ArchivedOrders

Both tables generate identifiers from the same sequence.

This guarantees unique values across both tables.


Choosing the Data Type

Supported numeric types include:

  • TINYINT
  • SMALLINT
  • INT
  • BIGINT
  • DECIMAL
  • NUMERIC

Example:

CREATE SEQUENCE dbo.InvoiceSequence
AS BIGINT;

Choose a type large enough for expected future growth.


START WITH

The START WITH clause specifies the first value.

Example:

CREATE SEQUENCE dbo.InvoiceSequence
AS INT
START WITH 1000;

Generated values:

1000
1001
1002

INCREMENT BY

Defines how much the sequence changes.

Example:

INCREMENT BY 10

Generated values:

10
20
30
40

Negative increments are also supported.

Example:

INCREMENT BY -1

Produces:

100
99
98
97

MINVALUE and MAXVALUE

A sequence can define minimum and maximum values.

Example:

CREATE SEQUENCE dbo.SmallSequence
AS INT
MINVALUE 1
MAXVALUE 100;

After reaching the maximum value, behavior depends on whether CYCLE is enabled.


CYCLE Option

The CYCLE option restarts the sequence after reaching its maximum (or minimum for descending sequences).

Example:

CREATE SEQUENCE dbo.TestSequence
AS INT
START WITH 1
MAXVALUE 5
CYCLE;

Generated values:

1
2
3
4
5
1
2

Without CYCLE, requesting another value after reaching the limit results in an error.

Use CYCLE only when reused values are acceptable.


NO CYCLE

NO CYCLE is the default behavior.

Example:

CREATE SEQUENCE dbo.OrderSequence
AS INT
NO CYCLE;

Once the maximum value is reached, SQL Server raises an error rather than restarting.

This is appropriate for identifiers that must remain unique.


CACHE Option

To improve performance, SQL Server can cache sequence values in memory.

Example:

CREATE SEQUENCE dbo.OrderSequence
AS INT
CACHE 100;

Benefits:

  • Fewer disk writes
  • Higher throughput
  • Better scalability

Trade-off:

If SQL Server stops unexpectedly, cached values that were not used are lost, resulting in gaps in the sequence.


NO CACHE

Disables sequence caching.

Example:

NO CACHE

Benefits:

  • Reduces gaps caused by unexpected shutdowns

Trade-offs:

  • Slightly slower performance
  • Increased metadata updates

Restarting a SEQUENCE

A sequence can be restarted.

Example:

ALTER SEQUENCE dbo.OrderSequence
RESTART WITH 5000;

The next generated value will be 5000.

This is useful after data migrations or when implementing new numbering schemes.


Altering a SEQUENCE

Existing sequences can be modified.

Example:

ALTER SEQUENCE dbo.OrderSequence
INCREMENT BY 5;

Future values increase by 5.


Dropping a SEQUENCE

Example:

DROP SEQUENCE dbo.OrderSequence;

This removes the sequence object from the database.


Obtaining Multiple Sequence Values

Applications can retrieve sequence values before performing inserts.

Example:

DECLARE @OrderID INT;
SET @OrderID =
NEXT VALUE FOR dbo.OrderSequence;

This is useful when:

  • Creating parent-child records
  • Generating invoice numbers
  • Passing identifiers between services
  • Building distributed workflows

Sequence Gaps

An important exam concept is that SEQUENCES do not guarantee gap-free numbering.

Gaps may occur because of:

  • Transaction rollbacks
  • Application failures
  • Cached values lost during server restart
  • Deleted rows
  • Unused generated values

Therefore, SEQUENCES should not be used when legal or regulatory requirements demand consecutive numbers with no gaps.


Performance Considerations

SEQUENCES generally perform very well.

Performance is improved by:

  • Using CACHE
  • Selecting appropriate data types
  • Avoiding unnecessary contention
  • Sharing sequences when appropriate

High-volume OLTP systems often use cached sequences for improved throughput.


SEQUENCES in Distributed Applications

Because SEQUENCES are independent objects, they are useful in distributed architectures.

Examples include:

  • Microservices
  • Azure Functions
  • Event-driven systems
  • Service Bus workflows
  • Multi-table transactional systems

Applications can reserve identifiers before inserting data.


AI-Enabled Database Scenarios

Although SEQUENCES are not AI-specific, they are useful in AI-enabled database solutions for generating unique identifiers for:

  • AI inference requests
  • Prompt execution logs
  • Conversation sessions
  • Vector embedding batches
  • Training jobs
  • Experiment tracking
  • Model evaluation records

Using a shared sequence ensures consistent identifiers across related AI components.


Best Practices

  • Use SEQUENCES when multiple tables require a common numbering scheme.
  • Use BIGINT if long-term growth is expected.
  • Use CACHE for high-throughput transactional workloads.
  • Avoid relying on sequence values being gap-free.
  • Do not use CYCLE for primary keys or other values that must remain globally unique.
  • Choose START WITH carefully to accommodate business requirements.
  • Document shared sequences to prevent accidental reuse.
  • Monitor sequence exhaustion when using small numeric data types.
  • Restart sequences only after careful planning.

Common Exam Tips

For the DP-800 exam, remember these key facts:

  • A SEQUENCE is a database object, not a table property.
  • NEXT VALUE FOR retrieves the next sequence value.
  • Multiple tables can share the same SEQUENCE.
  • SEQUENCES can generate values before an INSERT statement.
  • CACHE improves performance but may introduce gaps after an unexpected shutdown.
  • Transaction rollbacks do not return consumed sequence values.
  • CYCLE restarts a sequence after reaching its limit; NO CYCLE raises an error instead.
  • SEQUENCES are often preferred over IDENTITY when values must be shared across tables or generated outside of INSERT operations.

Practice Exam Questions

Question 1

A developer needs a single numbering mechanism that can generate unique identifiers for both the Orders and ArchivedOrders tables. Which feature should be used?

A. A DEFAULT constraint

B. An IDENTITY column

C. A computed column

D. A SEQUENCE

Answer: D

Explanation: A SEQUENCE is an independent database object that can be shared by multiple tables, making it ideal for generating unique identifiers across related tables.


Question 2

Which statement best describes a SEQUENCE object?

A. It is bound to a single table and generates values only during INSERT operations.

B. It can only generate BIGINT values.

C. It automatically creates a clustered index.

D. It is an independent database object that generates numeric values according to defined rules.

Answer: D

Explanation: A SEQUENCE is a standalone database object that can generate numeric values independently of any table and supports several numeric data types.


Question 3

Which function retrieves the next available value from a SQL Server SEQUENCE?

A. NEXT IDENTITY

B. GET NEXT

C. NEXT VALUE FOR

D. CURRENT VALUE

Answer: C

Explanation: The NEXT VALUE FOR function retrieves and advances a SEQUENCE to its next value.


Question 4

Why might a developer choose a SEQUENCE instead of an IDENTITY column?

A. Because SEQUENCES cannot contain gaps.

B. Because a SEQUENCE automatically enforces referential integrity.

C. Because a SEQUENCE can generate values before an INSERT and be shared across multiple tables.

D. Because SEQUENCES automatically create foreign keys.

Answer: C

Explanation: Unlike an IDENTITY column, a SEQUENCE is independent of tables and can generate values before inserts, making it useful across multiple tables or applications.


Question 5

What is the primary benefit of enabling the CACHE option on a SEQUENCE?

A. It guarantees gap-free numbering.

B. It improves performance by reducing metadata updates.

C. It automatically encrypts sequence values.

D. It prevents transaction rollbacks.

Answer: B

Explanation: Caching sequence values reduces the frequency of metadata updates, improving throughput. However, cached values may be lost during an unexpected shutdown, creating gaps.


Question 6

Which statement about sequence values is correct?

A. Sequence values are returned to the pool if a transaction rolls back.

B. Sequence values are always consecutive with no gaps.

C. Transaction rollbacks do not reclaim sequence values that have already been generated.

D. Sequence values can only be generated during INSERT statements.

Answer: C

Explanation: Once a sequence value is generated, it is consumed. If a transaction later rolls back, that value is not reused, so gaps are expected.


Question 7

A SEQUENCE is created with MAXVALUE 5 and the CYCLE option enabled. What happens after the value 5 is generated?

A. SQL Server raises an error.

B. The sequence automatically restarts at its minimum (or starting) value.

C. The sequence becomes read-only.

D. SQL Server automatically increases the maximum value.

Answer: B

Explanation: The CYCLE option causes a sequence to restart after reaching its maximum value rather than generating an error.


Question 8

Which statement about the NO CYCLE option is correct?

A. It causes sequence values to restart automatically.

B. It caches all generated values.

C. It allows duplicate sequence values.

D. It prevents the sequence from restarting after reaching its limit and raises an error instead.

Answer: D

Explanation: NO CYCLE is the default behavior. Once the sequence reaches its maximum or minimum value, SQL Server raises an error instead of restarting the sequence.


Question 9

Which of the following is a common use case for a SEQUENCE?

A. Automatically maintaining historical versions of rows

B. Enforcing referential integrity

C. Generating invoice numbers shared across multiple applications

D. Validating JSON documents

Answer: C

Explanation: SEQUENCES are frequently used to generate shared numbering schemes, such as invoice numbers, order numbers, or ticket identifiers across multiple systems.


Question 10

A developer uses a cached SEQUENCE to generate order numbers. After an unexpected SQL Server restart, several sequence values are missing. What is the most likely explanation?

A. The PRIMARY KEY constraint removed duplicate values.

B. Transaction rollbacks deleted the missing values.

C. The sequence automatically renumbered existing rows.

D. Cached sequence values that had not yet been issued were lost during the restart.

Answer: D

Explanation: Cached sequence values are stored in memory to improve performance. If SQL Server stops unexpectedly, any unused cached values are lost, resulting in gaps in the generated sequence.


Go to the DP-800 Exam Prep Hub main page

Design and implement database constraints, including PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK, and DEFAULT (DP-800 Exam Prep)

This post is a part of the DP-800: Developing AI-Enabled Database Solutions Exam Prep Hub.
This topic falls under these sections:
Design and develop database solutions (35–40%)
   --> Design and implement database objects
      --> Design and implement database constraints, including PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK, and DEFAULT


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Introduction

Database constraints are one of the most important mechanisms for maintaining data integrity in SQL Server and Azure SQL Database. A constraint is a rule that SQL Server automatically enforces whenever data is inserted, updated, or deleted. Instead of relying solely on application logic, constraints ensure that only valid, consistent, and meaningful data is stored in the database.

For the DP-800: Developing AI-Enabled Database Solutions certification exam, you should understand:

  • The purpose of each constraint type
  • When to use each constraint
  • How constraints enforce data integrity
  • How constraints affect performance and database design
  • Best practices for implementing constraints

Proper use of constraints improves application reliability, reduces programming errors, and helps maintain high-quality data for reporting, analytics, and AI-enabled applications.


What Are Database Constraints?

A database constraint is a rule applied to a table or column that restricts the type of data that can be stored.

Constraints help ensure:

  • Entity integrity
  • Referential integrity
  • Domain integrity
  • Data consistency
  • Data accuracy

Without constraints, invalid or inconsistent data can easily enter the database, leading to application errors and unreliable reports.


Types of Constraints

The primary constraint types covered on the DP-800 exam include:

ConstraintPurpose
PRIMARY KEYUniquely identifies each row
FOREIGN KEYMaintains relationships between tables
UNIQUEPrevents duplicate values
CHECKRestricts acceptable values
DEFAULTAutomatically supplies a value when none is provided

PRIMARY KEY Constraint

Purpose

A PRIMARY KEY uniquely identifies every row in a table.

Characteristics:

  • Values must be unique.
  • NULL values are not allowed.
  • Only one PRIMARY KEY can exist per table.
  • SQL Server automatically creates a unique index to enforce the constraint (clustered by default unless otherwise specified).

Example

CREATE TABLE Customers
(
CustomerID INT PRIMARY KEY,
FirstName NVARCHAR(50),
LastName NVARCHAR(50)
);

Every customer must have a unique CustomerID.


Composite Primary Keys

A PRIMARY KEY may consist of multiple columns.

Example:

CREATE TABLE OrderDetails
(
OrderID INT,
ProductID INT,
Quantity INT,
PRIMARY KEY (OrderID, ProductID)
);

The combination of OrderID and ProductID must be unique.

Composite keys are commonly used in junction (bridge) tables.


Natural vs. Surrogate Keys

Natural Key

A value that already exists in the business domain.

Examples:

  • Social Security Number
  • Email address
  • Vehicle Identification Number (VIN)

Advantages:

  • Business meaning
  • No additional column required

Disadvantages:

  • May change
  • Can be lengthy
  • May not always be unique globally

Surrogate Key

An artificial identifier created solely for the database.

Example:

CustomerID INT IDENTITY(1,1)

Advantages:

  • Stable
  • Compact
  • Efficient for indexing
  • Easy to join

Most SQL Server applications use surrogate keys as PRIMARY KEY values.


FOREIGN KEY Constraint

Purpose

A FOREIGN KEY maintains referential integrity between related tables.

It ensures that values in one table correspond to existing values in another.


Example

CREATE TABLE Orders
(
OrderID INT PRIMARY KEY,
CustomerID INT,
CONSTRAINT FK_Orders_Customers
FOREIGN KEY (CustomerID)
REFERENCES Customers(CustomerID)
);

An order cannot reference a customer that does not exist.


Referential Integrity

Foreign keys prevent:

  • Orphan records
  • Invalid relationships
  • Accidental inconsistencies

Example:

Customers

CustomerID
1
2
3

Orders

CustomerID
2

CustomerID 5 cannot be inserted because it does not exist.


Cascade Actions

Foreign keys support optional cascading behavior.

CASCADE DELETE

Deleting the parent automatically deletes child rows.

Example:

FOREIGN KEY(CustomerID)
REFERENCES Customers(CustomerID)
ON DELETE CASCADE

CASCADE UPDATE

Updates to the parent key automatically update child rows.

Example:

ON UPDATE CASCADE

SET NULL

When the parent row is deleted, the child foreign key becomes NULL.

ON DELETE SET NULL

Requires the foreign key column to allow NULL values.


SET DEFAULT

When the parent row is deleted, the child receives its default value.

ON DELETE SET DEFAULT

Requires a DEFAULT constraint on the foreign key column.


NO ACTION (Default)

SQL Server prevents deletion or update if related child rows exist.

This is the default behavior.


UNIQUE Constraint

Purpose

A UNIQUE constraint prevents duplicate values while allowing the column to serve as an alternate key.

Unlike a PRIMARY KEY:

  • Multiple UNIQUE constraints may exist in a table.
  • A UNIQUE constraint is not the table’s primary identifier.

Example

CREATE TABLE Employees
(
EmployeeID INT PRIMARY KEY,
EmailAddress NVARCHAR(255) UNIQUE
);

No two employees can have the same email address.


UNIQUE and NULL Values

A UNIQUE constraint allows at most one NULL value in SQL Server.

Example:

Email
alice@example.com
bob@example.com
NULL

A second NULL violates the UNIQUE constraint.


Composite UNIQUE Constraints

Example:

UNIQUE (FirstName, LastName, BirthDate)

Only the combination must be unique.


CHECK Constraint

Purpose

A CHECK constraint restricts allowable values.

It enforces business rules directly within the database.


Example

CHECK (Salary > 0)

Negative salaries cannot be inserted.


Multiple Conditions

Example:

CHECK
(
Age >= 18
AND Age <= 65
)

Character Validation

Example:

CHECK
(
Status IN
('New','Active','Closed')
)

Only approved values are permitted.


Date Validation

Example:

CHECK
(
HireDate <= GETDATE()
)

Preventing future hire dates may be appropriate depending on business requirements. (Be aware that nondeterministic functions such as GETDATE() can affect certain indexing scenarios, but they are permitted in CHECK constraints.)


DEFAULT Constraint

Purpose

DEFAULT automatically supplies a value when none is specified.


Example

Status NVARCHAR(20)
DEFAULT 'Pending'

If Status is omitted:

INSERT INTO Orders
(OrderID)
VALUES
(101);

SQL Server inserts:

Pending

Using Functions

Defaults often use built-in functions.

Example:

CreatedDate DATETIME2
DEFAULT SYSDATETIME()

Other common examples include:

DEFAULT NEWID()
DEFAULT SUSER_SNAME()

Named Constraints

Rather than allowing SQL Server to generate names automatically, explicitly naming constraints simplifies administration.

Example:

CONSTRAINT PK_Customers
PRIMARY KEY(CustomerID)

Benefits include:

  • Easier troubleshooting
  • Easier scripting
  • Easier deployment
  • Easier maintenance

Adding Constraints to Existing Tables

Example:

ALTER TABLE Employees
ADD CONSTRAINT CK_Salary
CHECK (Salary > 0);

Example:

ALTER TABLE Employees
ADD CONSTRAINT UQ_Email
UNIQUE (EmailAddress);

Removing Constraints

Example:

ALTER TABLE Employees
DROP CONSTRAINT CK_Salary;

Constraint Evaluation

Constraints are enforced whenever data modifications occur.

Examples include:

  • INSERT
  • UPDATE
  • MERGE

If a constraint is violated:

  • The statement fails.
  • The transaction may be rolled back depending on transaction handling.
  • SQL Server returns an error.

Constraints vs. Indexes

Although related, constraints and indexes serve different purposes.

ConstraintIndex
Enforces business rulesImproves query performance
Maintains data integritySpeeds data retrieval
May automatically create an indexDoes not enforce business rules (except unique indexes)

For example:

  • PRIMARY KEY creates a unique index.
  • UNIQUE creates a unique index.
  • CHECK does not create an index.
  • DEFAULT does not create an index.

Constraints and AI-Enabled Applications

AI applications depend on high-quality, trustworthy data.

Constraints help ensure:

  • Clean training data
  • Accurate feature engineering
  • Reliable vector metadata
  • Consistent model inputs
  • Reduced preprocessing effort

For example:

  • CHECK constraints can prevent impossible values (such as negative ages).
  • FOREIGN KEY constraints ensure relationships remain valid.
  • DEFAULT constraints automatically populate timestamps used for AI event tracking.
  • UNIQUE constraints prevent duplicate identities that could bias analytics.

Best Practices

  • Define PRIMARY KEY constraints for every table.
  • Prefer surrogate keys for most transactional systems.
  • Use FOREIGN KEY constraints to enforce relationships instead of relying solely on application logic.
  • Use UNIQUE constraints for alternate keys such as email addresses or account numbers.
  • Apply CHECK constraints to enforce business rules whenever practical.
  • Use DEFAULT constraints for common initial values such as timestamps and statuses.
  • Explicitly name constraints using consistent naming conventions.
  • Avoid disabling constraints except during carefully managed bulk loading scenarios.
  • Review cascade actions carefully to avoid unintended data loss.
  • Validate existing data before adding new constraints to production tables.

Common Exam Tips

For the DP-800 exam, remember these important facts:

  • Every table can have only one PRIMARY KEY, but it may consist of one or more columns.
  • A PRIMARY KEY cannot contain NULL values.
  • A FOREIGN KEY enforces referential integrity between related tables.
  • NO ACTION is the default behavior for FOREIGN KEY delete and update operations.
  • A table can have multiple UNIQUE constraints.
  • A CHECK constraint enforces domain or business rules.
  • A DEFAULT constraint supplies a value only when one is not explicitly provided during an INSERT.
  • PRIMARY KEY and UNIQUE constraints automatically create unique indexes to enforce uniqueness.
  • CHECK and DEFAULT constraints do not create indexes.

Practice Exam Questions

Question 1

A database designer needs to ensure that every customer record has a unique identifier that cannot contain NULL values. Which constraint should be used?

A. UNIQUE

B. CHECK

C. PRIMARY KEY

D. FOREIGN KEY

Answer: C

Explanation: A PRIMARY KEY uniquely identifies every row in a table and does not allow NULL values. Each table can have only one PRIMARY KEY.


Question 2

An Orders table contains a CustomerID column that must always reference an existing customer in the Customers table. Which constraint enforces this relationship?

A. FOREIGN KEY

B. DEFAULT

C. UNIQUE

D. CHECK

Answer: A

Explanation: A FOREIGN KEY enforces referential integrity by ensuring that values in one table correspond to existing values in another table.


Question 3

A company wants every new order to receive a status of “Pending” unless another value is explicitly supplied during insertion. Which constraint should be implemented?

A. CHECK

B. UNIQUE

C. FOREIGN KEY

D. DEFAULT

Answer: D

Explanation: A DEFAULT constraint automatically assigns a value when one is not provided in an INSERT statement.


Question 4

A database must prevent employees from having duplicate email addresses, but EmployeeID already serves as the table’s PRIMARY KEY. Which constraint should be added to the EmailAddress column?

A. PRIMARY KEY

B. DEFAULT

C. UNIQUE

D. CHECK

Answer: C

Explanation: A UNIQUE constraint enforces uniqueness for a column without making it the table’s primary identifier.


Question 5

Which constraint is best suited to ensure that an employee’s salary is always greater than zero?

A. CHECK

B. UNIQUE

C. DEFAULT

D. FOREIGN KEY

Answer: A

Explanation: A CHECK constraint validates that column values satisfy a specified logical condition, such as Salary > 0.


Question 6

Which statement about PRIMARY KEY constraints is correct?

A. A table can contain multiple PRIMARY KEY constraints.

B. PRIMARY KEY values may contain NULL values.

C. PRIMARY KEY constraints automatically enforce uniqueness and prevent NULL values.

D. PRIMARY KEY constraints cannot be referenced by FOREIGN KEY constraints.

Answer: C

Explanation: A PRIMARY KEY enforces uniqueness and does not permit NULL values. It is also commonly referenced by FOREIGN KEY constraints.


Question 7

What is the default action if a parent row referenced by a FOREIGN KEY is deleted without specifying any cascade option?

A. CASCADE

B. SET NULL

C. SET DEFAULT

D. NO ACTION

Answer: D

Explanation: Unless another referential action is specified, SQL Server uses NO ACTION, preventing deletion when related child rows exist.


Question 8

A junction table contains OrderID and ProductID, and each combination must be unique. Which design is most appropriate?

A. Add separate UNIQUE constraints to each column.

B. Create a composite PRIMARY KEY using OrderID and ProductID.

C. Create a DEFAULT constraint on both columns.

D. Use a CHECK constraint to compare the values.

Answer: B

Explanation: A composite PRIMARY KEY ensures that the combination of OrderID and ProductID is unique while allowing each individual value to appear multiple times as part of different combinations.


Question 9

Which statement best describes a UNIQUE constraint?

A. It prevents duplicate values and can be defined multiple times within a table.

B. It automatically creates foreign key relationships.

C. It validates numeric ranges.

D. It supplies default values during inserts.

Answer: A

Explanation: A table may contain multiple UNIQUE constraints, each preventing duplicate values in a column or combination of columns.


Question 10

Why are database constraints particularly valuable in AI-enabled database solutions?

A. They automatically generate machine learning models.

B. They improve graphics rendering performance.

C. They eliminate the need for indexes.

D. They help ensure high-quality, consistent data for analytics and AI workloads.

Answer: D

Explanation: Constraints improve data quality by enforcing consistency, valid relationships, and business rules, which reduces data cleansing and improves the reliability of AI models and analytical processes.


Go to the DP-800 Exam Prep Hub main page

Design and implement JSON columns and indexes (DP-800 Exam Prep)

This post is a part of the DP-800: Developing AI-Enabled Database Solutions Exam Prep Hub.
This topic falls under these sections:
Design and develop database solutions (35–40%)
   --> Design and implement database objects
      --> Design and implement JSON columns and indexes


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Introduction

JSON (JavaScript Object Notation) has become one of the most widely used formats for exchanging data between applications, web services, APIs, cloud platforms, and AI solutions. Modern database applications frequently need to store, query, validate, and index JSON documents alongside traditional relational data.

SQL Server and Azure SQL Database provide extensive built-in support for working with JSON, allowing developers to:

  • Store JSON documents
  • Validate JSON data
  • Query individual properties
  • Modify JSON documents
  • Convert relational data to JSON
  • Convert JSON into relational tables
  • Improve performance by indexing JSON values

For the DP-800: Developing AI-Enabled Database Solutions certification exam, understanding how JSON is stored, queried, and indexed is an important skill because many AI-enabled applications exchange information using JSON.


Why Use JSON?

JSON offers a flexible way to store semi-structured data that doesn’t fit neatly into fixed relational tables.

Common scenarios include:

  • REST API payloads
  • Application configuration
  • Product catalogs
  • Customer preferences
  • Event logs
  • IoT telemetry
  • AI prompts and responses
  • Chat conversation history
  • Metadata storage

Rather than creating dozens of optional columns, JSON allows variable attributes to be stored in a single column.


JSON Support in SQL Server

Unlike some database systems, SQL Server stores JSON as text rather than as a dedicated JSON data type.

Typically, JSON documents are stored in:

  • NVARCHAR(MAX)
  • NVARCHAR(n)

Example:

CREATE TABLE Orders
(
OrderID INT PRIMARY KEY,
CustomerInfo NVARCHAR(MAX)
);

A row might contain:

{
"CustomerID": 125,
"Name": "John Smith",
"City": "Seattle",
"LoyaltyLevel": "Gold"
}

Although stored as text, SQL Server provides built-in functions that understand JSON syntax.


Validating JSON

Before using JSON data, developers should ensure it contains valid JSON.

SQL Server provides the ISJSON() function.

Example:

SELECT ISJSON(CustomerInfo)
FROM Orders;

Returns:

  • 1 = Valid JSON
  • 0 = Invalid JSON

Example using a CHECK constraint:

ALTER TABLE Orders
ADD CONSTRAINT CK_ValidJSON
CHECK (ISJSON(CustomerInfo) = 1);

This prevents invalid JSON from being stored.


Extracting Values with JSON_VALUE()

The JSON_VALUE() function extracts a scalar value from a JSON document.

Example:

SELECT
JSON_VALUE(CustomerInfo,'$.Name')
FROM Orders;

Result:

John Smith

Common uses include:

  • Filtering
  • Sorting
  • Displaying attributes
  • Reporting

Extracting Objects and Arrays with JSON_QUERY()

JSON_QUERY() retrieves an object or array rather than a scalar value.

Example JSON:

{
"CustomerID": 25,
"Orders":
[
{"OrderID":1},
{"OrderID":2}
]
}

Query:

SELECT
JSON_QUERY(CustomerInfo,'$.Orders')
FROM Orders;

Returns the JSON array.


Updating JSON with JSON_MODIFY()

JSON_MODIFY() updates properties without replacing the entire document.

Example:

UPDATE Orders
SET CustomerInfo =
JSON_MODIFY(CustomerInfo,
'$.City',
'Chicago');

Useful when applications maintain customer preferences or AI-generated metadata.


Parsing JSON into Rows with OPENJSON()

OPENJSON converts JSON into relational rows.

Example:

SELECT *
FROM OPENJSON(@json);

Example JSON:

{
"Name":"Alice",
"City":"Boston"
}

Returns:

KeyValue
NameAlice
CityBoston

Using WITH to Define a Schema

OPENJSON becomes much more useful when mapping JSON to columns.

Example:

SELECT *
FROM OPENJSON(@json)
WITH
(
Name NVARCHAR(100),
City NVARCHAR(100),
Age INT
);

This converts JSON directly into relational columns.


Producing JSON with FOR JSON

SQL Server can return query results as JSON.

Example:

SELECT CustomerID,
Name,
City
FROM Customers
FOR JSON AUTO;

Output:

[
{
"CustomerID":1,
"Name":"Alice",
"City":"Boston"
}
]

FOR JSON PATH

FOR JSON PATH provides greater control over the structure.

Example:

SELECT CustomerID,
Name
FROM Customers
FOR JSON PATH;

Developers commonly use this when building REST APIs.


Common JSON Functions

FunctionPurpose
ISJSON()Validate JSON
JSON_VALUE()Return scalar value
JSON_QUERY()Return object or array
JSON_MODIFY()Update JSON
OPENJSON()Convert JSON into rows
FOR JSONProduce JSON output

These functions appear frequently in Microsoft documentation and certification objectives.


Why JSON Indexing Matters

JSON itself is stored as text.

Without indexing, SQL Server must scan every JSON document to locate requested values.

This becomes expensive for large tables.

Example:

SELECT *
FROM Orders
WHERE JSON_VALUE(CustomerInfo,'$.City')='Seattle';

Without indexing, SQL Server evaluates JSON_VALUE() for every row.


Indexing JSON Data

Because JSON is stored in NVARCHAR columns, SQL Server cannot directly create an index on an arbitrary JSON property.

Instead, developers create computed columns that expose JSON properties and then index those computed columns.

This is the recommended approach for SQL Server and Azure SQL Database and is an important DP-800 exam objective.


Creating a Computed Column

Example:

ALTER TABLE Orders
ADD CustomerCity AS
JSON_VALUE(CustomerInfo,'$.City');

SQL Server now treats CustomerCity as a regular column.


Creating an Index

Once the computed column exists, it can be indexed.

Example:

CREATE INDEX IX_Orders_CustomerCity
ON Orders(CustomerCity);

Queries filtering on CustomerCity can now use the index rather than scanning every JSON document.


Persisted Computed Columns

Computed columns may be marked PERSISTED.

Example:

ALTER TABLE Orders
ADD CustomerCity
AS JSON_VALUE(CustomerInfo,'$.City')
PERSISTED;

Benefits include:

  • Value stored physically
  • Faster reads
  • Reduced recalculation

Trade-offs include:

  • Increased storage
  • Slightly slower INSERT/UPDATE operations

JSON Path Expressions

SQL Server identifies JSON elements using path expressions.

Examples:

$.Name
$.Address.City
$.Orders[0]
$.Orders[1].Price

The dollar sign ($) represents the root of the JSON document.

Understanding JSON path syntax is essential for using JSON functions correctly.


Nested JSON

Example:

{
"Customer":
{
"Name":"Alice",
"Address":
{
"City":"Boston"
}
}
}

Extracting City:

SELECT
JSON_VALUE(CustomerInfo,
'$.Customer.Address.City');

Working with JSON Arrays

Example JSON:

{
"Products":
[
{"ID":1},
{"ID":2},
{"ID":3}
]
}

Retrieve the array:

SELECT
JSON_QUERY(OrderInfo,'$.Products');

Convert to rows:

SELECT *
FROM OPENJSON
(
JSON_QUERY(OrderInfo,'$.Products')
);

JSON Design Considerations

JSON is ideal when:

  • Attributes vary significantly between rows.
  • Schema flexibility is required.
  • Data originates from APIs.
  • AI systems generate dynamic metadata.
  • Semi-structured information must be stored.

Relational tables are preferable when:

  • Strong relationships exist.
  • Frequent joins are required.
  • Referential integrity must be enforced.
  • Structured reporting dominates the workload.

Many production databases combine relational columns with JSON columns.


JSON and AI Applications

JSON is heavily used throughout AI-enabled database solutions.

Common examples include:

  • Storing AI prompt templates
  • Saving LLM responses
  • Recording chat history
  • Persisting vector search metadata
  • Storing application configuration
  • Capturing model parameters
  • Logging AI inference results

Because AI services frequently communicate using JSON, SQL Server’s JSON functionality is an important integration capability.


Performance Considerations

When working with JSON:

  • Validate incoming JSON using ISJSON().
  • Avoid repeatedly evaluating JSON_VALUE() in large queries.
  • Create computed columns for frequently queried properties.
  • Index computed columns used in WHERE, JOIN, or ORDER BY clauses.
  • Persist computed columns when read performance outweighs storage costs.
  • Avoid storing extremely large documents unless necessary.
  • Use OPENJSON() for efficient ingestion of structured JSON payloads.

Best Practices

  • Store only valid JSON documents.
  • Keep relational data relational whenever practical.
  • Use JSON for flexible or semi-structured attributes.
  • Use JSON_VALUE() for scalar values.
  • Use JSON_QUERY() for arrays and objects.
  • Use JSON_MODIFY() for updates.
  • Use OPENJSON() to transform JSON into relational rows.
  • Create computed columns for frequently searched JSON properties.
  • Index computed columns to improve query performance.
  • Test execution plans to verify indexes are being used.

Common Exam Tips

For the DP-800 exam, remember these key points:

  • SQL Server stores JSON as NVARCHAR, not as a native JSON data type.
  • ISJSON() validates JSON syntax.
  • JSON_VALUE() returns a scalar value.
  • JSON_QUERY() returns an object or array.
  • JSON_MODIFY() updates JSON documents.
  • OPENJSON() converts JSON into relational rows.
  • FOR JSON AUTO and FOR JSON PATH generate JSON output from SQL queries.
  • JSON properties are typically indexed by exposing them through computed columns and creating indexes on those columns.
  • Persisted computed columns can improve read performance at the cost of additional storage and update overhead.

Practice Exam Questions

Question 1

A developer needs to verify that incoming API payloads contain valid JSON before storing them in a table. Which SQL Server function should be used?

A. JSON_QUERY()

B. OPENJSON()

C. JSON_VALUE()

D. ISJSON()

Answer: D

Explanation: ISJSON() validates whether a string contains properly formatted JSON. It returns 1 for valid JSON and 0 for invalid JSON, making it ideal for validation and CHECK constraints.


Question 2

A developer wants to retrieve the value of the City property from a JSON document stored in an NVARCHAR column. Which function should be used?

A. JSON_VALUE()

B. JSON_QUERY()

C. JSON_MODIFY()

D. OPENJSON()

Answer: A

Explanation: JSON_VALUE() extracts a single scalar value from a JSON document, such as a string, number, or Boolean.


Question 3

Which statement accurately describes how SQL Server stores JSON data?

A. SQL Server stores JSON in a dedicated JSON data type.

B. SQL Server stores JSON as XML internally.

C. SQL Server stores JSON as character data, typically in an NVARCHAR column.

D. SQL Server automatically converts JSON into relational columns.

Answer: C

Explanation: SQL Server does not provide a native JSON data type. JSON documents are stored as text, typically in NVARCHAR(MAX) or NVARCHAR(n) columns.


Question 4

A query frequently filters on the value returned by JSON_VALUE(CustomerInfo,'$.City'). What is the recommended way to improve query performance?

A. Create a clustered index on the JSON column.

B. Create a computed column using JSON_VALUE() and index the computed column.

C. Replace the JSON column with XML.

D. Create a foreign key on the JSON column.

Answer: B

Explanation: SQL Server cannot directly index an arbitrary JSON property. The recommended approach is to expose the property through a computed column and then create an index on that computed column.


Question 5

A developer needs to retrieve an entire JSON array from a document rather than a single scalar value. Which function should be used?

A. JSON_QUERY()

B. JSON_VALUE()

C. ISJSON()

D. JSON_MODIFY()

Answer: A

Explanation: JSON_QUERY() returns a JSON object or array, whereas JSON_VALUE() returns only scalar values.


Question 6

Which SQL Server feature converts relational query results into JSON output?

A. OPENJSON

B. JSON_VALUE

C. FOR JSON

D. JSON_MODIFY

Answer: C

Explanation: The FOR JSON clause formats SQL query results as JSON. Both AUTO and PATH modes are available.


Question 7

A developer receives a JSON document containing thousands of customer records and wants to transform it into relational rows for loading into SQL Server. Which function should be used?

A. JSON_QUERY()

B. JSON_MODIFY()

C. ISJSON()

D. OPENJSON()

Answer: D

Explanation: OPENJSON() parses JSON documents and converts them into rows and columns. It is commonly used for importing JSON data.


Question 8

What is the primary advantage of creating a persisted computed column based on a JSON property?

A. It automatically encrypts the JSON document.

B. It physically stores the computed value, reducing recalculation during queries.

C. It compresses the JSON document.

D. It converts JSON into XML.

Answer: B

Explanation: A persisted computed column stores its calculated value on disk, improving query performance by avoiding repeated evaluation of the expression.


Question 9

Which JSON path expression retrieves the City property nested inside an Address object?

A. $.City.Address

B. $.Address.City

C. $.Address[City]

D. $.City->Address

Answer: B

Explanation: JSON path expressions begin at the root ($) and navigate nested objects using dot notation, such as $.Address.City.


Question 10

Which scenario is the best candidate for storing information in a JSON column instead of creating many optional relational columns?

A. A highly normalized customer master table with strict referential integrity

B. A table containing only integer values

C. A fixed employee payroll table with mandatory attributes

D. A product catalog in which different product categories have different sets of optional attributes

Answer: D

Explanation: JSON is well suited for semi-structured or variable data, such as product attributes that differ across categories, avoiding the need for numerous nullable columns while maintaining flexibility.


Go to the DP-800 Exam Prep Hub main page

Design and implement specialized tables, including in-memory, temporal, external, ledger, and graph tables (DP-800 Exam Prep)

This post is a part of the DP-800: Developing AI-Enabled Database Solutions Exam Prep Hub.
This topic falls under these sections:
Design and develop database solutions (35–40%)
   --> Design and implement database objects
      --> Design and implement specialized tables, including in-memory, temporal, external, ledger, and graph


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Introduction

Modern SQL Server and Azure SQL Database environments provide several specialized table types designed to address specific business, performance, security, and analytical requirements. Rather than relying solely on traditional row-based tables, developers can use specialized tables to improve transaction throughput, maintain historical data automatically, access external data sources, provide tamper-evident records, or model complex relationships.

For the DP-800: Developing AI-Enabled Database Solutions certification exam, you should understand:

  • When to use each specialized table type
  • How each table is implemented
  • Their advantages and limitations
  • Common business scenarios
  • Performance considerations
  • Best practices

Understanding these table types is especially important because many modern AI-enabled applications require historical analysis, secure auditing, graph-based relationships, or access to large external datasets.


Overview of Specialized Tables

SQL Server and Azure SQL support several specialized table types:

Table TypePrimary Purpose
In-Memory TablesHigh-performance OLTP workloads
Temporal TablesAutomatic historical data tracking
External TablesQuery external data without importing it
Ledger TablesTamper-evident data and auditability
Graph TablesModel complex relationships between entities

Each solves a different architectural challenge.


In-Memory Tables

What Are In-Memory Tables?

In-memory tables are stored primarily in memory instead of traditional disk-based storage. They are part of the In-Memory OLTP feature in SQL Server and Azure SQL Database.

Unlike conventional tables, in-memory tables are optimized for extremely fast transaction processing.

They use:

  • Memory-optimized data structures
  • Lock-free algorithms
  • Latch-free architecture
  • Optimistic concurrency

These improvements reduce contention and dramatically improve throughput.


Benefits

Advantages include:

  • Extremely low latency
  • High transaction throughput
  • Reduced locking
  • Reduced blocking
  • Improved scalability
  • Better concurrency

Applications can often process several times more transactions compared to equivalent disk-based tables.


Typical Use Cases

Common scenarios include:

  • Financial trading
  • E-commerce transactions
  • Reservation systems
  • Gaming platforms
  • Real-time telemetry
  • IoT ingestion
  • Session state storage
  • High-volume order processing

Memory-Optimized Filegroup

Although data is stored in memory during operation, SQL Server still requires a memory-optimized filegroup for durability.

Example:

ALTER DATABASE SalesDB
ADD FILEGROUP InMemoryFG CONTAINS MEMORY_OPTIMIZED_DATA;

Creating a Memory-Optimized Table

Example:

CREATE TABLE Orders
(
OrderID INT NOT NULL PRIMARY KEY NONCLUSTERED,
CustomerID INT,
OrderDate DATETIME2
)
WITH
(
MEMORY_OPTIMIZED = ON,
DURABILITY = SCHEMA_AND_DATA
);

Durability Options

SCHEMA_AND_DATA

Both schema and data survive server restart.

Recommended for:

  • Production applications
  • Financial systems
  • Business transactions

SCHEMA_ONLY

Only the table definition persists.

Data disappears after restart.

Useful for:

  • Temporary data
  • Session caches
  • ETL staging
  • Intermediate processing

Memory-Optimized Indexes

Memory-optimized tables require indexes.

Supported types include:

  • Hash indexes
  • Nonclustered indexes

Hash indexes perform exceptionally well for equality searches.

Example:

INDEX IX_Order HASH(OrderID)
WITH (BUCKET_COUNT = 100000)

Limitations

Developers should know:

  • Not every SQL feature is supported.
  • Memory planning is important.
  • Some T-SQL functionality differs.
  • Requires appropriate database configuration.

Temporal Tables

What Are Temporal Tables?

Temporal tables automatically maintain a complete history of data changes.

Whenever a row is:

  • Updated
  • Deleted

SQL Server automatically copies the previous version into a history table.

This eliminates the need for custom audit triggers.


Components

A temporal table consists of:

  • Current table
  • History table
  • System versioning

SQL Server manages the history automatically.


Period Columns

Temporal tables include two hidden datetime columns:

ValidFrom
ValidTo

These define the period during which each row version was valid.


Creating a Temporal Table

Example:

CREATE TABLE Employees
(
EmployeeID INT PRIMARY KEY,
Name NVARCHAR(100),
Salary DECIMAL(10,2),
ValidFrom DATETIME2 GENERATED ALWAYS AS ROW START,
ValidTo DATETIME2 GENERATED ALWAYS AS ROW END,
PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo)
)
WITH
(
SYSTEM_VERSIONING = ON
);

Querying Historical Data

SQL provides temporal query options.

Example:

SELECT *
FROM Employees
FOR SYSTEM_TIME AS OF '2025-01-01';

This retrieves the table exactly as it existed at the specified point in time.

Other options include:

  • FROM…TO
  • BETWEEN
  • CONTAINED IN
  • ALL

Benefits

Temporal tables provide:

  • Automatic history
  • Point-in-time recovery
  • Audit support
  • Trend analysis
  • Easier reporting

Typical Use Cases

Examples include:

  • Employee history
  • Customer profile changes
  • Insurance records
  • Compliance reporting
  • AI training using historical snapshots

External Tables

What Are External Tables?

External tables allow SQL Server or Azure SQL to query data stored outside the database without importing it.

The external data remains in its original location.

SQL accesses it through metadata.


Supported Data Sources

External tables can access:

  • Azure Data Lake Storage
  • Azure Blob Storage
  • Hadoop
  • Microsoft Fabric OneLake
  • SQL Server
  • Oracle (through supported virtualization technologies)
  • Parquet files
  • CSV files
  • Delta Lake (supported platforms)

PolyBase

SQL Server commonly uses PolyBase to query external data.

PolyBase allows T-SQL queries against external sources.

Example architecture:

SQL Server
External Table
Azure Data Lake

Advantages

Benefits include:

  • No data duplication
  • Large-scale analytics
  • Access data lakes
  • Simplified ETL
  • Lower storage costs

Common AI Scenarios

AI projects frequently use external tables to access:

  • Training datasets
  • Data lake files
  • Feature engineering data
  • Parquet datasets
  • Fabric Lakehouse data

Considerations

Performance depends on:

  • Network speed
  • External storage
  • Predicate pushdown
  • File formats
  • Data partitioning

Ledger Tables

What Are Ledger Tables?

Ledger tables provide tamper-evident records.

They use cryptographic hashing to detect unauthorized modifications.

Ledger technology helps organizations prove that data has not been altered.


Why Ledger Tables Matter

Industries with regulatory requirements often require immutable records.

Examples include:

  • Banking
  • Healthcare
  • Government
  • Supply chain
  • Legal systems

How They Work

Ledger tables automatically maintain:

  • Transaction history
  • Cryptographic digests
  • Verification metadata

Attempts to modify historical records become detectable.


Updatable Ledger Tables

These support:

  • INSERT
  • UPDATE
  • DELETE

While preserving historical versions.


Append-Only Ledger Tables

These allow:

  • INSERT

Only.

Rows cannot be updated or deleted.

Useful for:

  • Financial journals
  • Event logs
  • Blockchain-style records

Benefits

Ledger tables provide:

  • Data integrity
  • Nonrepudiation
  • Tamper evidence
  • Simplified auditing
  • Regulatory compliance

Typical Use Cases

Examples include:

  • Financial transactions
  • Audit logs
  • Medical records
  • Government systems
  • Digital contracts

Graph Tables

What Are Graph Tables?

Graph tables model relationships between entities.

Instead of relying solely on foreign keys, graph databases represent information as:

  • Nodes
  • Edges

This structure is ideal for highly connected data.


Node Tables

Node tables store entities.

Examples:

  • Customers
  • Products
  • Employees
  • Devices
  • Companies

Example:

CREATE TABLE Person
(
ID INT,
Name NVARCHAR(100)
)
AS NODE;

Edge Tables

Edge tables define relationships.

Example:

CREATE TABLE FriendOf
AS EDGE;

Possible relationships:

  • Friend of
  • Purchased
  • Works for
  • Located in
  • Connected to

Graph Queries

Graph queries use the MATCH clause.

Example:

SELECT *
FROM Person,
FriendOf,
Person
WHERE MATCH(Person-(FriendOf)->Person);

Advantages

Graph tables simplify:

  • Relationship traversal
  • Network analysis
  • Recommendation systems
  • Fraud detection
  • Organizational charts

AI Use Cases

Graph tables are increasingly valuable for AI because they model relationships that traditional relational databases handle less efficiently.

Examples include:

  • Knowledge graphs
  • Recommendation engines
  • Customer relationship analysis
  • Social networks
  • Supply chain analysis
  • Fraud detection

Choosing the Correct Specialized Table

RequirementBest Choice
Maximum OLTP performanceIn-Memory Table
Automatic historyTemporal Table
Access data lakeExternal Table
Tamper-evident recordsLedger Table
Relationship analysisGraph Table

Comparing Specialized Tables

FeatureIn-MemoryTemporalExternalLedgerGraph
High-speed transactions
Historical tracking
External data
Tamper detection
Relationship modeling
AI training support

Best Practices

In-Memory Tables

  • Use for high-volume OLTP workloads.
  • Choose an appropriate bucket count for hash indexes.
  • Monitor memory consumption carefully.
  • Use SCHEMA_AND_DATA for durable business data.

Temporal Tables

  • Use for audit and historical reporting.
  • Periodically archive large history tables if appropriate.
  • Query historical versions using FOR SYSTEM_TIME.

External Tables

  • Prefer efficient file formats such as Parquet.
  • Partition large datasets.
  • Minimize unnecessary data movement.
  • Push filtering to the external source whenever possible.

Ledger Tables

  • Use when regulatory compliance or auditability is required.
  • Understand the difference between append-only and updatable ledger tables.
  • Regularly verify ledger digests as part of governance processes.

Graph Tables

  • Use when relationships are central to the data model.
  • Avoid replacing well-designed relational models unnecessarily.
  • Combine graph and relational tables where appropriate.

Common Exam Tips

For the DP-800 exam, remember these important distinctions:

  • In-memory tables improve OLTP performance through memory optimization and optimistic concurrency.
  • Temporal tables automatically maintain historical versions of data using system versioning.
  • External tables allow SQL queries against data stored outside the database without importing it.
  • Ledger tables provide cryptographically verifiable, tamper-evident records for auditing and compliance.
  • Graph tables represent entities and relationships using node and edge tables and support graph pattern matching with the MATCH clause.
  • SCHEMA_ONLY memory-optimized tables do not preserve data after a restart, while SCHEMA_AND_DATA tables do.
  • Append-only ledger tables support inserts only; updatable ledger tables support inserts, updates, and deletes while preserving history.

Practice Exam Questions

Question 1

A financial trading application requires extremely high transaction throughput while minimizing locking and blocking. Which table type should be implemented?

A. Temporal table

B. In-memory table

C. Ledger table

D. External table

Answer: B

Explanation: In-memory tables use memory-optimized storage and lock-free, latch-free processing to maximize OLTP performance and concurrency.


Question 2

A company wants SQL Server to automatically maintain historical versions of customer records whenever updates occur. Which feature should be used?

A. External table

B. Graph table

C. Temporal table

D. Ledger table

Answer: C

Explanation: Temporal tables automatically maintain current and historical versions of rows using system versioning, eliminating the need for custom audit triggers.


Question 3

A database administrator needs to query Parquet files stored in Azure Data Lake without copying the data into SQL Server. Which table type is most appropriate?

A. External table

B. Ledger table

C. In-memory table

D. Temporal table

Answer: A

Explanation: External tables provide metadata that enables SQL queries against external data sources such as Azure Data Lake and Parquet files without importing the data.


Question 4

Which specialized table type provides cryptographic verification that historical records have not been altered?

A. Graph table

B. External table

C. Temporal table

D. Ledger table

Answer: D

Explanation: Ledger tables use cryptographic hashing and transaction digests to create tamper-evident records suitable for auditing and regulatory compliance.


Question 5

Which statement about memory-optimized tables configured with SCHEMA_ONLY durability is correct?

A. Both schema and data survive a server restart.

B. The table cannot contain indexes.

C. The table definition remains, but the data is lost after a restart.

D. The table is automatically converted to a temporal table.

Answer: C

Explanation: SCHEMA_ONLY durability preserves only the table definition. Data stored in the table is not retained after the SQL Server instance restarts.


Question 6

Which SQL Server feature is specifically designed to model entities and their relationships using node and edge tables?

A. Ledger

B. PolyBase

C. Temporal

D. Graph

Answer: D

Explanation: Graph tables use node and edge tables to represent entities and relationships and support graph pattern matching using the MATCH clause.


Question 7

A retail company wants to analyze historical pricing information exactly as it existed on a specific date six months ago. Which query capability supports this requirement?

A. MATCH

B. FOR SYSTEM_TIME AS OF

C. OPENROWSET

D. MERGE

Answer: B

Explanation: The FOR SYSTEM_TIME AS OF clause queries a temporal table as it existed at a specified point in time.


Question 8

Which workload is the best candidate for a clustered in-memory table?

A. A data warehouse containing historical sales data

B. A compliance audit archive

C. A product catalog that rarely changes

D. A high-volume online order processing system

Answer: D

Explanation: In-memory tables are designed for OLTP workloads with frequent inserts, updates, and concurrent transactions.


Question 9

What is the primary advantage of using external tables in AI-enabled database solutions?

A. They automatically encrypt all external files.

B. They eliminate the need for indexes.

C. They enable SQL queries against externally stored datasets without duplicating the data.

D. They automatically convert relational data into graph structures.

Answer: C

Explanation: External tables allow SQL Server and Azure SQL to access external data sources directly, making them ideal for AI workloads that consume large datasets stored in data lakes.


Question 10

Which scenario is the best fit for an append-only ledger table?

A. A customer profile database requiring frequent updates

B. A temporary ETL staging table

C. A social network relationship graph

D. A financial transaction journal where records must never be modified or deleted

Answer: D

Explanation: Append-only ledger tables permit inserts but prevent updates and deletes, making them ideal for immutable transaction logs and regulatory audit records.


Go to the DP-800 Exam Prep Hub main page

Design and implement tables, including data types, size, columns, indexes, and column store indexes (DP-800 Exam Prep)

This post is a part of the DP-800: Developing AI-Enabled Database Solutions Exam Prep Hub.
This topic falls under these sections:
Design and develop database solutions (35–40%)
   --> Design and implement database objects
      --> Design and implement tables, including data types, size, columns, indexes, and column store indexes


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Introduction

One of the most fundamental skills measured on the DP-800: Developing AI-Enabled Database Solutions exam is the ability to design and implement efficient database tables. Every SQL solution—whether supporting traditional applications, analytics, or AI-enabled workloads—depends on well-designed tables that maximize performance, maintain data integrity, minimize storage requirements, and scale effectively.

Poor table design often results in slow queries, excessive storage consumption, locking issues, and difficult maintenance. Conversely, properly designed tables improve application responsiveness, simplify development, and reduce infrastructure costs.

This article covers the key concepts required for the DP-800 exam, including:

  • Choosing appropriate data types
  • Determining column sizes
  • Designing table structures
  • Creating clustered and nonclustered indexes
  • Understanding filtered, included, and composite indexes
  • Implementing columnstore indexes
  • Best practices and common design mistakes

Designing Tables

A table stores related information organized into rows and columns.

Good table design should achieve the following goals:

  • Eliminate unnecessary duplication
  • Support efficient queries
  • Enforce data integrity
  • Reduce storage requirements
  • Support future growth
  • Minimize maintenance

A typical design process includes:

  1. Identify entities
  2. Define columns
  3. Choose data types
  4. Select appropriate sizes
  5. Determine nullable columns
  6. Define primary keys
  7. Create foreign keys
  8. Add indexes based on workload

Choosing Appropriate Data Types

Selecting the correct data type is one of the most important database design decisions.

Using oversized or inappropriate data types increases:

  • Storage usage
  • Memory usage
  • Network traffic
  • Index size
  • Backup size
  • Query execution time

Integer Data Types

Data TypeStorageRange
TINYINT1 byte0–255
SMALLINT2 bytes-32,768 to 32,767
INT4 bytes±2.1 billion
BIGINT8 bytesExtremely large values

Example:

CustomerID INT
OrderID BIGINT
Age TINYINT

CustomerID INT

OrderID BIGINT

Age TINYINT




Decimal and Numeric

Used for precise financial calculations.

Price DECIMAL(10,2)

Price DECIMAL(10,2)



  • 10 total digits
  • 2 digits after the decimal

Examples:

12345678.90
99999999.99

12345678.90
99999999.99<b
r>


</b


Floating Point Types

Used for scientific calculations.

FLOAT
REAL

FLOAT



REAL

  • Measurements
  • Statistics
  • Sensor data

Avoid for:

  • Currency
  • Accounting
  • Financial systems

Character Data Types

CHAR

Fixed-length storage.

CHAR(2)

CHAR(2)



  • Country codes
  • State abbreviations
  • Status values

VARCHAR

Variable-length storage.

VARCHAR(100)

VARCHAR(100)



Ideal for:

  • Names
  • Email addresses
  • Descriptions

NCHAR and NVARCHAR

Support Unicode characters.

NVARCHAR(100)

NVARCHAR(100)



  • Multiple languages
  • International names
  • Emoji
  • Unicode symbols

VARCHAR(MAX)

Stores very large text.

Use only when necessary.

Examples:

  • Documents
  • Long descriptions
  • JSON

Avoid using MAX columns unnecessarily because they reduce performance.


Date and Time Data Types

Common options include:

TypeDescription
DATEDate only
TIMETime only
DATETIME2Date and time with high precision
DATETIMEOFFSETDate/time plus time zone

Microsoft recommends DATETIME2 for most new applications.

Example:

CreatedDate DATETIME2

Binary Data Types

Examples include:

VARBINARY
VARBINARY(MAX)

VARBINARY



VARBINARY(MAX)

  • Images
  • Encryption keys
  • Files
  • AI embeddings (in some scenarios)

UniqueIdentifier

Stores globally unique identifiers (GUIDs).

CustomerGuid UNIQUEIDENTIFIER

CustomerGuid UNIQUEIDENTIFIER



  • Globally unique
  • Useful for distributed systems

Drawbacks:

  • Larger indexes
  • Can fragment clustered indexes when generated randomly

NULL vs NOT NULL

Every column should explicitly define whether NULL values are allowed.

Example:

FirstName NVARCHAR(50) NOT NULL
MiddleName NVARCHAR(50) NULL

FirstName NVARCHAR(50) NOT NULL

MiddleName NVARCHAR(50) NULL



  • Improves data integrity
  • Simplifies queries
  • Often improves performance

Identity Columns

Automatically generate sequential values.

Example:

CustomerID INT IDENTITY(1,1)

CustomerID INT IDENTITY(1,1)



Start at 1

Increment by 1

Commonly used as surrogate primary keys.


Computed Columns

Values calculated from other columns.

Example:

FullName AS FirstName + ' ' + LastName

FullName AS FirstName + ‘ ‘ + LastName




Sparse Columns

Designed for tables with many NULL values.

Benefits:

  • Reduce storage
  • Useful for optional attributes

Trade-off:

Slightly higher processing overhead.


Table Constraints

Constraints enforce data integrity.

Primary Key

Uniquely identifies each row.

PRIMARY KEY (CustomerID)

PRIMARY KEY (CustomerID)



  • Unique
  • NOT NULL
  • Automatically indexed

Foreign Key

Maintains relationships between tables.

FOREIGN KEY (CustomerID)
REFERENCES Customers(CustomerID)

UNIQUE Constraint

Prevents duplicate values.

Example:

EmailAddress UNIQUE

CHECK Constraint

Restricts acceptable values.

Example:

CHECK (Salary > 0)

DEFAULT Constraint

Automatically inserts default values.

Example:

CreatedDate DATETIME2
DEFAULT GETDATE()

Index Fundamentals

Indexes improve query performance by reducing table scans.

Without indexes:

SQL Server reads every row.

SQL Server reads every row.



SQL Server quickly locates matching rows.

SQL Server quickly locates matching rows.



  • WHERE
  • JOIN
  • ORDER BY
  • GROUP BY

Clustered Index

Determines the physical order of rows.

Each table can have only one clustered index.

Example:

CREATE CLUSTERED INDEX IX_Customers
ON Customers(CustomerID);

CREATE CLUSTERED INDEX IX_Customers

ON Customers(CustomerID);



  • Primary keys
  • Sequential values

Nonclustered Index

Stores a separate searchable structure.

A table can have many nonclustered indexes.

Example:

CREATE INDEX IX_LastName
ON Customers(LastName);

CREATE INDEX IX_LastName

ON Customers(LastName);




Composite Index

Contains multiple columns.

Example:

CREATE INDEX IX_OrderDateCustomer
ON Orders(OrderDate, CustomerID);

CREATE INDEX IX_OrderDateCustomer

ON Orders(OrderDate, CustomerID);



The leftmost column should be the most selective or frequently filtered.


Included Columns

Include non-key columns to create covering indexes.

Example:

CREATE INDEX IX_LastName
ON Customers(LastName)
INCLUDE (FirstName, EmailAddress);

CREATE INDEX IX_LastName

ON Customers(LastName)

INCLUDE (FirstName, EmailAddress);



  • Reduces key lookups
  • Improves SELECT performance

Filtered Index

Indexes only selected rows.

Example:

CREATE INDEX IX_ActiveCustomers
ON Customers(Status)
WHERE Status='Active';

CREATE INDEX IX_ActiveCustomers

ON Customers(Status)



WHERE Status=’Active’;

  • Smaller index
  • Faster maintenance
  • Better query performance

Covering Index

A covering index contains every column required by a query.

Example:

Query:

SELECT FirstName, LastName
FROM Customers
WHERE LastName='Smith';

SELECT FirstName, LastName

FROM Customers

WHERE LastName=’Smith’;



  • LastName (key)
  • FirstName (included)

No lookup to the base table is required.


Index Maintenance

Indexes require regular maintenance.

Common tasks include:

  • Rebuild indexes
  • Reorganize indexes
  • Update statistics
  • Monitor fragmentation

Highly fragmented indexes reduce performance.


Columnstore Indexes

Columnstore indexes store data by columns rather than rows.

Traditional storage:

Row 1
Row 2
Row 3

Row 1

Row 2

Row 3



CustomerID
FirstName
LastName
City

CustomerID

FirstName

LastName

City




Benefits of Columnstore Indexes

Advantages include:

  • High compression
  • Reduced storage
  • Faster aggregations
  • Parallel processing
  • Batch execution mode

Ideal for:

  • Data warehouses
  • Reporting
  • Analytics
  • AI feature engineering
  • Large fact tables

Clustered Columnstore Index

Entire table stored in column format.

Example:

CREATE CLUSTERED COLUMNSTORE INDEX CCI_Sales
ON Sales;

CREATE CLUSTERED COLUMNSTORE INDEX CCI_Sales

ON Sales;



  • Fact tables
  • Large analytical workloads

Nonclustered Columnstore Index

Adds columnstore capabilities to an existing rowstore table.

Example:

CREATE NONCLUSTERED COLUMNSTORE INDEX NCCI_Sales
ON Sales
(
Revenue,
Quantity,
ProductID
);

CREATE NONCLUSTERED COLUMNSTORE INDEX NCCI_Sales

ON Sales


(
Reven
ue,
Quantity,

ProductID

);




Rowstore vs Columnstore

FeatureRowstoreColumnstore
Best forOLTPAnalytics
InsertsExcellentGood
UpdatesExcellentModerate
AggregationsModerateExcellent
CompressionLowVery High
Large scansSlowerMuch Faster

Choosing the Right Index

ScenarioRecommended Index
Primary keyClustered
Frequent lookupsNonclustered
Multi-column searchesComposite
ReportingColumnstore
Active records onlyFiltered
Covering queriesIncluded columns

Best Practices

  • Choose the smallest appropriate data type.
  • Avoid VARCHAR(MAX) unless required.
  • Use DATETIME2 instead of DATETIME for new development.
  • Define NOT NULL whenever appropriate.
  • Create indexes based on query patterns rather than every column.
  • Avoid excessive indexing because each index increases insert, update, and delete costs.
  • Use composite indexes carefully, considering column order.
  • Regularly rebuild or reorganize fragmented indexes.
  • Use clustered columnstore indexes for large analytical tables.
  • Test index changes using execution plans and performance metrics.

Common Exam Tips

For the DP-800 exam, remember these key points:

  • Smaller data types improve storage efficiency.
  • Clustered indexes determine physical row order.
  • A table can have only one clustered index.
  • Multiple nonclustered indexes are allowed.
  • Included columns create covering indexes.
  • Filtered indexes reduce storage and improve performance for selective queries.
  • Composite index column order matters.
  • Columnstore indexes are optimized for analytical workloads.
  • DATETIME2 is preferred over DATETIME for new applications.
  • FLOAT should not be used for financial data.

Practice Exam Questions

Question 1

A database designer needs to store a person’s age. The maximum expected value is 120. Which data type is the most storage-efficient?

A. INT

B. SMALLINT

C. TINYINT

D. BIGINT

Answer: C

Explanation: TINYINT stores values from 0 to 255 using only one byte, making it the most efficient choice for age values.


Question 2

A company stores customer names in multiple languages, including Japanese and Arabic. Which data type should be used?

A. CHAR

B. VARCHAR

C. TEXT

D. NVARCHAR

Answer: D

Explanation: NVARCHAR supports Unicode characters, making it suitable for multilingual applications.


Question 3

Which index determines the physical order of rows within a SQL Server table?

A. Nonclustered index

B. Filtered index

C. Clustered index

D. Columnstore index

Answer: C

Explanation: A clustered index defines the physical storage order of rows. Each table can have only one clustered index.


Question 4

A reporting system performs large aggregation queries against a fact table containing hundreds of millions of rows. Which index type is most appropriate?

A. Clustered columnstore index

B. Nonclustered index

C. Filtered index

D. XML index

Answer: A

Explanation: Clustered columnstore indexes are optimized for large analytical workloads, providing high compression and fast aggregations.


Question 5

Why might a developer create a filtered index?

A. To improve backup performance

B. To index only rows matching a specific condition

C. To encrypt indexed values

D. To automatically partition a table

Answer: B

Explanation: A filtered index includes only rows that satisfy a defined predicate, reducing storage and maintenance while improving performance for targeted queries.


Question 6

A table has a composite index on (OrderDate, CustomerID). Which query is most likely to benefit directly from the index?

A. Filtering only on CustomerID

B. Filtering only on ProductID

C. Filtering on OrderDate

D. Filtering only on TotalAmount

Answer: C

Explanation: Composite indexes are most effective when queries use the leftmost indexed column. A filter on OrderDate can efficiently leverage the index.


Question 7

Which statement about clustered indexes is correct?

A. A table can have many clustered indexes.

B. Clustered indexes cannot contain primary keys.

C. Clustered indexes store data separately from the table.

D. A table can have only one clustered index.

Answer: D

Explanation: Because a clustered index defines the physical order of the rows, only one clustered index can exist per table.


Question 8

A developer wants to eliminate expensive key lookups for a frequently executed query without changing the indexed search column. Which feature should be used?

A. Sparse columns

B. Included columns

C. Identity columns

D. Computed columns

Answer: B

Explanation: Included columns allow additional non-key columns to be stored in a nonclustered index, creating a covering index that can avoid key lookups.


Question 9

Which data type is recommended for storing currency values that require exact precision?

A. FLOAT

B. REAL

C. DECIMAL

D. MONEY with floating-point conversion

Answer: C

Explanation: DECIMAL provides fixed precision and scale, making it appropriate for financial calculations where exact values are required.


Question 10

Why are columnstore indexes particularly valuable for AI and analytics workloads?

A. They increase transaction locking.

B. They optimize sequential identity generation.

C. They eliminate the need for primary keys.

D. They provide high compression and significantly accelerate large scan and aggregation queries.

Answer: D

Explanation: Columnstore indexes organize data by column, enabling excellent compression and efficient execution of analytical queries common in reporting, feature engineering, and AI scenarios.


Go to the DP-800 Exam Prep Hub main page.

Identify Azure Database Services for open-source database systems (DP-900 Exam Prep)

This post is a part of the DP-900: Microsoft Azure Data Fundamentals Exam Prep Hub. 
This topic falls under these sections:
Identify considerations for relational data on Azure (20–25%)
--> Describe relational Azure data services
--> Identify Azure database services for open-source database systems


Note that there are 10 practice questions (with answers and explanations) for each section to help you solidify your knowledge of the material. Also, there are 2 practice tests with 60 questions each available on the hub below the exam topics section.

In addition to the Azure SQL family, Microsoft Azure provides fully managed database services for popular open-source relational database systems. These services allow organizations to run familiar technologies like PostgreSQL and MySQL in the cloud without managing infrastructure.

For the DP-900 exam, you should understand which services are available, what they support, and when to use them.


What Are Open-Source Database Systems?

Open-source database systems are relational databases whose source code is publicly available and widely used across industries.

Common examples include:

  • PostgreSQL
  • MySQL
  • MariaDB

These systems are known for flexibility, cost-effectiveness, and strong community support.


Azure Services for Open-Source Databases

Azure offers managed services for these databases, allowing you to run them in a Platform as a Service (PaaS) model.


1. Azure Database for PostgreSQL

Azure Database for PostgreSQL

A fully managed PostgreSQL database service.

Key Features

  • Automated backups and patching
  • Built-in high availability
  • Scaling options for compute and storage
  • Security features (encryption, network isolation)
  • Support for PostgreSQL extensions

Deployment Options

  • Flexible Server (most commonly used)

Use Cases

  • Web and mobile applications
  • Analytics workloads
  • Applications already using PostgreSQL

Best for: PostgreSQL-based applications moving to Azure


2. Azure Database for MySQL

Azure Database for MySQL

A fully managed MySQL database service.

Key Features

  • Automated backups and patching
  • High availability options
  • Scaling for performance
  • Built-in security features
  • Compatible with popular MySQL tools

Use Cases

  • Web applications (e.g., LAMP stack)
  • E-commerce platforms
  • Content management systems

Best for: Applications built on MySQL


3. Azure Database for MariaDB (Legacy Note)

Azure Database for MariaDB

  • Previously offered as a managed service
  • Now being retired (important exam awareness point)

💡 DP-900 Tip:
Know that MariaDB exists, but focus primarily on PostgreSQL and MySQL.


Key Characteristics of Azure Open-Source Database Services

These services share common benefits:

Platform as a Service (PaaS)

  • No infrastructure management
  • Azure handles patching, backups, and updates

High Availability

  • Built-in redundancy
  • Automatic failover options

Scalability

  • Scale compute and storage independently

Security

  • Encryption at rest and in transit
  • Network security (firewalls, private endpoints)

When to Use Open-Source Database Services in Azure

Choose these services when:

  • You are already using PostgreSQL or MySQL
  • You want to migrate existing applications with minimal changes
  • You prefer open-source technologies
  • You want a managed service without infrastructure overhead

Comparison with Azure SQL Family

FeatureAzure SQL ServicesOpen-Source Azure Services
Database EngineSQL ServerPostgreSQL / MySQL
LanguageT-SQLPostgreSQL SQL / MySQL SQL
Use CaseMicrosoft ecosystemOpen-source ecosystem
ManagementPaaS / IaaS optionsPrimarily PaaS

Why This Matters for DP-900

On the exam, you may be asked to:

  • Identify Azure services for PostgreSQL or MySQL
  • Choose the correct service for an open-source workload
  • Understand the benefits of managed database services
  • Compare Azure SQL vs open-source options

Summary — Exam-Relevant Takeaways

✔ Azure supports open-source relational databases:

  • Azure Database for PostgreSQL
  • Azure Database for MySQL

✔ These are PaaS services:

  • Azure manages infrastructure, backups, and patching

✔ Key benefits:

  • High availability
  • Scalability
  • Security

✔ Use them when:

  • Migrating existing open-source applications
  • Building apps using PostgreSQL or MySQL

✔ Be aware:

  • MariaDB support exists but is being phased out

Go to the Practice Exam Questions for this topic.

Go to the DP-900 Exam Prep Hub main page.

Practice Questions: Identify Azure Database Services for open-source database systems (DP-900 Exam Prep)

Practice Questions


Question 1

Which Azure service is used to host a managed PostgreSQL database?

A. Azure SQL Database
B. Azure Database for PostgreSQL
C. Azure Cosmos DB
D. Azure Synapse Analytics

Answer: B

Explanation:
Azure Database for PostgreSQL is the managed service for PostgreSQL workloads.


Question 2

Which Azure service is BEST suited for hosting a MySQL-based web application?

A. Azure SQL Managed Instance
B. Azure Database for MySQL
C. Azure Data Lake Storage
D. Azure Blob Storage

Answer: B

Explanation:
Azure Database for MySQL is designed for MySQL workloads, commonly used in web apps.


Question 3

What type of service are Azure Database for PostgreSQL and Azure Database for MySQL?

A. Infrastructure as a Service (IaaS)
B. Platform as a Service (PaaS)
C. Software as a Service (SaaS)
D. On-premises solutions

Answer: B

Explanation:
These services are PaaS offerings, meaning Azure manages infrastructure and maintenance.


Question 4

Which task is handled by Azure in open-source database PaaS services?

A. Writing SQL queries
B. Managing application code
C. Performing backups and patching
D. Designing database schema

Answer: C

Explanation:
Azure handles operational tasks like backups, patching, and updates.


Question 5

Which scenario is BEST suited for Azure Database for PostgreSQL?

A. Running a NoSQL database
B. Migrating an existing PostgreSQL application to Azure
C. Storing unstructured files
D. Running machine learning models

Answer: B

Explanation:
This service is ideal for migrating or running PostgreSQL workloads in Azure.


Question 6

Which of the following is an open-source relational database supported by Azure?

A. Microsoft SQL Server
B. Oracle Database
C. PostgreSQL
D. Azure Cosmos DB

Answer: C

Explanation:
PostgreSQL is a widely used open-source relational database supported by Azure.


Question 7

Which Azure database service for open-source systems is being retired?

A. Azure Database for PostgreSQL
B. Azure Database for MySQL
C. Azure Database for MariaDB
D. Azure SQL Database

Answer: C

Explanation:
Azure Database for MariaDB is being phased out.


Question 8

Which feature is commonly provided by Azure open-source database services?

A. Manual scaling only
B. No security features
C. Built-in high availability
D. No backup support

Answer: C

Explanation:
These services include built-in high availability and redundancy.


Question 9

Which is a key benefit of using Azure Database for MySQL instead of installing MySQL on a VM?

A. Full OS control
B. Reduced management overhead
C. No support for scaling
D. Limited security features

Answer: B

Explanation:
PaaS reduces administrative tasks like maintenance and patching.


Question 10

Which factor is MOST important when choosing Azure Database for PostgreSQL or MySQL?

A. Whether the data is unstructured
B. The need for OS-level access
C. The existing database engine used by the application
D. The need for NoSQL capabilities

Answer: C

Explanation:
Choice is typically driven by the database engine already used (PostgreSQL vs MySQL).


✅ Quick Exam Takeaways

Azure Database for PostgreSQL → PostgreSQL workloads
Azure Database for MySQL → MySQL workloads
✔ Both are PaaS services (Azure manages infrastructure)

✔ Key benefits:

  • Automated backups
  • Patching and updates
  • High availability
  • Scalability

✔ Use when:

  • Migrating open-source databases
  • Building apps on PostgreSQL or MySQL

✔ Be aware:

  • MariaDB is being retired

Go to the DP-900 Exam Prep Hub main page.