Tag: Triggers

Design and implement controls for deployment pipelines, including branching policies, triggers in approvals, authentication tables, and code owners – Part 2 (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:
Secure, optimize, and deploy database solutions (35–40%)
   --> Implement CI/CD by using SQL Database Projects
      --> Design and implement controls for deployment pipelines, including branching policies, triggers in approvals, authentication tables, and code owners


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

In Part 1, you learned how branching strategies, pull requests, branch protection policies, and Code Owners help organizations maintain secure and reliable SQL Database Projects. In this section, we focus on how deployment pipelines automatically execute, how approvals and authentication secure deployments, and how organizations protect production environments.


Pipeline Triggers

A pipeline trigger determines when a build or deployment pipeline starts.

Rather than requiring developers to manually start every pipeline, modern CI/CD systems automatically execute pipelines based on predefined events.

Common trigger types include:

  • Source code commits
  • Pull requests
  • Scheduled executions
  • Manual execution
  • Completion of another pipeline
  • Tag creation
  • Release approvals

Choosing the appropriate trigger helps balance automation with governance.


Continuous Integration Triggers

Continuous Integration (CI) pipelines usually start automatically after code changes.

Typical CI trigger:

Developer Commit
Git Repository
Automatic Build
Compile SQL Database Project
Run Validation
Publish Build Artifact

Benefits include:

  • Immediate feedback
  • Early detection of errors
  • Frequent validation
  • Consistent builds
  • Reduced integration problems

Common CI Trigger Events

Commit Trigger

The pipeline starts whenever a developer commits changes.

Example:

Commit to feature branch
Build Pipeline Starts

Useful for:

  • Early validation
  • Fast feedback
  • Developer productivity

Pull Request Trigger

Instead of triggering on every commit, organizations often build whenever a pull request is created or updated.

Example:

Feature Branch
Create Pull Request
Automatic Validation
Review

Benefits:

  • Ensures only validated code reaches protected branches
  • Prevents broken code from being merged
  • Supports branch protection policies

Scheduled Trigger

Some validation pipelines execute on a schedule.

Example:

Every Night
Run Full Test Suite

Useful for:

  • Long-running tests
  • Security scanning
  • Dependency validation
  • Performance testing

Manual Trigger

Certain deployments should never execute automatically.

Example:

Release Manager
Start Production Deployment

Manual triggers provide additional governance before production releases.


Continuous Delivery Triggers

Continuous Delivery (CD) pipelines move validated artifacts through multiple environments.

Example:

Build Artifact
Development
Testing
Staging
Production

Each stage may have different approval requirements.


Deployment Approvals

Approvals ensure that qualified personnel review changes before deployment.

Instead of automatically deploying to production, pipelines pause until an authorized user approves the release.

Example:

Deployment Ready
Approval Required
Manager Approves
Deployment Continues

Types of Deployment Approvals

Manual Approval

A designated reviewer manually approves deployment.

Common reviewers include:

  • Database Administrator
  • Development Lead
  • Security Team
  • Operations Team
  • Product Owner

Multi-Stage Approval

Different environments require different reviewers.

Example:

EnvironmentRequired Approval
DevelopmentNone
TestTeam Lead
StagingDBA
ProductionDBA + Operations Manager

This layered approval process minimizes production risk.


Conditional Approval

Approval requirements may depend on:

  • Database type
  • Environment
  • Change size
  • Security classification
  • Time of deployment

Example:

Production Deployment
Contains Schema Changes?
Yes
Require DBA Approval

Environment Protection

Modern DevOps platforms allow organizations to protect deployment environments.

Environment protection can require:

  • Manual approvals
  • Deployment windows
  • Authentication verification
  • Security policies
  • Health checks

Example:

Pipeline
Staging
Approval
Production

Only authorized deployments can proceed.


Deployment Gates

Deployment gates evaluate conditions before allowing deployment.

Common gates include:

  • Successful testing
  • Security scan completion
  • Vulnerability assessment
  • Performance validation
  • Business approval
  • Service availability

Example:

Security Scan Passed?
Yes
Continue Deployment

If any gate fails, deployment stops automatically.


Authentication in Deployment Pipelines

Authentication verifies the identity of the pipeline when accessing resources.

The deployment pipeline may need to access:

  • SQL Server
  • Azure SQL Database
  • Azure Key Vault
  • Azure Storage
  • Azure AI Services
  • Microsoft Fabric
  • Azure OpenAI
  • Azure Resource Manager

Secure authentication is essential because deployment pipelines often operate without human intervention.


Authentication Methods

Common authentication methods include:

  • Microsoft Entra ID (Azure AD)
  • Managed Identity
  • Service Principal
  • OAuth tokens
  • Personal Access Tokens (PATs)
  • SQL Authentication (legacy scenarios)

Microsoft recommends avoiding passwords whenever possible.


Service Principals

A Service Principal represents an application identity in Microsoft Entra ID.

Instead of using a person’s account, the deployment pipeline authenticates using its own identity.

Example:

Pipeline
Service Principal
Microsoft Entra ID
Azure SQL Database

Benefits:

  • Non-interactive authentication
  • Fine-grained permissions
  • Centralized identity management
  • Easy auditing
  • Supports automation

Managed Identity

A Managed Identity is the preferred authentication method for Azure-hosted services.

Instead of storing credentials, Azure automatically manages authentication.

Example:

Azure DevOps Agent
Managed Identity
Microsoft Entra ID
Azure SQL Database

Advantages include:

  • No stored passwords
  • Automatic credential rotation
  • Improved security
  • Simplified administration
  • Reduced risk of credential leakage

Managed Identity is increasingly emphasized across Microsoft certifications, including DP-800.


System-Assigned vs User-Assigned Managed Identity

System-Assigned Managed Identity

Characteristics:

  • Tied to one Azure resource
  • Automatically created
  • Automatically deleted with the resource
  • Ideal for single-resource scenarios

Example:

App Service
System Managed Identity
Azure SQL

User-Assigned Managed Identity

Characteristics:

  • Independent Azure resource
  • Shared across multiple services
  • Longer lifecycle
  • Reusable

Example:

Managed Identity
Web App
Azure Function
Azure SQL Database

Useful when multiple applications require the same identity.


Least Privilege Principle

Deployment identities should have only the permissions necessary to perform deployments.

Avoid granting:

  • sysadmin
  • db_owner (unless required)
  • Subscription Owner
  • Global Administrator

Instead, assign only the permissions needed.

Example:

Deployment pipeline requires:

  • ALTER TABLE
  • CREATE PROCEDURE
  • CREATE VIEW

It does not require:

  • DROP DATABASE
  • Server Administration
  • Security Administration

Following the principle of least privilege reduces the impact of compromised credentials.


Secrets Management

Pipelines often require sensitive information, such as:

  • Connection strings
  • API keys
  • Certificates
  • Tokens
  • Database credentials

Hardcoding these values in source control is a major security risk.


Azure Key Vault

Azure Key Vault is the recommended solution for storing secrets.

Instead of embedding credentials:

Pipeline
Azure Key Vault
Retrieve Secret
Deploy Database

Benefits include:

  • Centralized secret storage
  • Encryption at rest
  • Access auditing
  • Role-based access control
  • Automatic secret rotation
  • Integration with Azure DevOps and GitHub Actions

Secure Pipeline Variables

CI/CD platforms support secure variables that:

  • Encrypt values
  • Hide secrets in logs
  • Restrict access
  • Limit modification permissions

Examples include:

  • SQL connection strings
  • Azure subscription IDs
  • API tokens
  • Storage account keys

Sensitive values should never be committed to a Git repository.


Environment-Specific Configuration

Different deployment environments often require different configuration values.

Example:

EnvironmentDatabase
DevelopmentDevDB
TestingTestDB
StagingStageDB
ProductionProdDB

Pipelines should dynamically retrieve the correct configuration for each environment rather than hardcoding values.


Deployment Strategies

Different deployment strategies reduce downtime and deployment risk.

Common strategies include:

Incremental Deployment

Deploy only changed objects.

Advantages:

  • Faster deployments
  • Lower risk
  • Reduced downtime

Rolling Deployment

Deploy changes gradually across multiple instances.

Useful for:

  • High availability
  • Large distributed systems

Blue-Green Deployment

Maintain two production environments.

Blue Environment
(Current)
Switch
Green Environment
(New Version)

Advantages:

  • Minimal downtime
  • Fast rollback
  • Lower deployment risk

Canary Deployment

Deploy to a small subset of users first.

If successful:

5%
25%
50%
100%

This strategy helps identify issues before a full rollout.


Best Practices for Secure Deployment Pipelines

Microsoft recommends the following practices:

  • Automate builds whenever possible.
  • Require approvals for production deployments.
  • Use Microsoft Entra ID authentication.
  • Prefer Managed Identity over stored credentials.
  • Store secrets in Azure Key Vault.
  • Apply least privilege permissions.
  • Protect production environments with approval gates.
  • Separate development, test, staging, and production environments.
  • Monitor deployment history and audit logs.
  • Validate deployments before promotion to production.

DP-800 Exam Tips

For the exam, be prepared to identify when to use:

  • Pull request triggers versus commit triggers.
  • Manual approvals for production deployments.
  • Managed Identity instead of passwords or embedded credentials.
  • Service Principals for automated, non-interactive deployments.
  • Azure Key Vault for secure secrets management.
  • Environment protection rules to safeguard production resources.
  • Least privilege permissions for deployment identities.
  • Appropriate deployment strategies such as blue-green, rolling, or incremental deployments based on business requirements.

Part 2 Summary

In this section, you learned how organizations secure and automate SQL deployment pipelines through:

  • Pipeline triggers and CI/CD automation
  • Manual and conditional deployment approvals
  • Environment protection and deployment gates
  • Authentication using Microsoft Entra ID
  • Service Principals and Managed Identity
  • Least privilege access
  • Secrets management with Azure Key Vault
  • Secure pipeline variables
  • Environment-specific configuration
  • Common deployment strategies
  • Microsoft-recommended security and governance practices

Go to the DP-800 Exam Prep Hub main page

Design and implement controls for deployment pipelines, including branching policies, triggers in approvals, authentication tables, and code owners – Part 1 (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:
Secure, optimize, and deploy database solutions (35–40%)
   --> Implement CI/CD by using SQL Database Projects
      --> Design and implement controls for deployment pipelines, including branching policies, triggers in approvals, authentication tables, and code owners


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

Microsoft expects SQL AI Developers to understand not only how to develop database solutions but also how to deploy them safely, consistently, and securely using modern DevOps practices.

Organizations rarely allow developers to deploy SQL changes directly into production. Instead, database changes pass through controlled deployment pipelines that validate the code, enforce security policies, require approvals, and ensure only authorized changes reach production.

Modern SQL development emphasizes:

  • Source-controlled database projects
  • Automated builds
  • Automated testing
  • Controlled deployments
  • Secure authentication
  • Governance through branching policies and approvals
  • Auditable deployment history

Understanding these concepts is essential for both the DP-800 exam and real-world enterprise database development.


What Are Deployment Pipeline Controls?

Deployment pipeline controls are rules and processes that ensure database changes move safely from development to production.

Instead of allowing developers to make direct changes to production databases, organizations require every change to follow a controlled workflow.

A typical workflow looks like this:

Developer
Feature Branch
Pull Request
Code Review
Automated Build
Unit Tests
Integration Tests
Approval
Deployment Pipeline
Development
Test
Staging
Production

Each stage reduces the risk of introducing errors into production.


Why Deployment Controls Matter

Without deployment controls, organizations often experience:

  • Accidental schema changes
  • Lost database objects
  • Unauthorized modifications
  • Production outages
  • Failed deployments
  • Data corruption
  • Compliance violations
  • Security risks

Deployment controls provide:

  • Consistency
  • Repeatability
  • Security
  • Governance
  • Auditability
  • Faster recovery
  • Higher software quality

For enterprise environments, these controls are considered mandatory.


SQL Database Projects and Deployment Pipelines

SQL Database Projects represent an entire database schema as source-controlled code.

Instead of modifying objects directly inside SQL Server Management Studio (SSMS), developers modify project files.

Example:

Tables
Customers.sql
Orders.sql
Products.sql
Views
SalesView.sql
Stored Procedures
usp_CreateOrder.sql
Functions
fn_TotalSales.sql

The deployment pipeline compares the project against the target database and generates the necessary deployment script automatically.

Benefits include:

  • Version history
  • Repeatable deployments
  • Easier collaboration
  • Automated validation
  • Reduced deployment risk

CI/CD Overview

CI/CD stands for:

Continuous Integration (CI)

Developers frequently merge changes into a shared repository.

Every commit automatically triggers:

  • Build validation
  • SQL compilation
  • Static code analysis
  • Unit testing
  • Artifact creation

Example:

Developer Commit
Git Repository
Automatic Build
Database Project Build
Validation
Package Generated

Continuous Delivery (CD)

Continuous Delivery automates deployments through multiple environments.

Example:

Development
QA
Staging
Production

Each deployment can require approvals before continuing.

Benefits include:

  • Faster releases
  • Fewer deployment errors
  • Repeatable deployments
  • Reliable rollback strategies

Understanding Branching Strategies

Branching is one of the most important deployment controls.

A branch is an independent line of development inside source control.

Instead of every developer modifying the main branch directly, developers work in isolated branches.

Example:

Main
├── Feature A
├── Feature B
├── Bug Fix
└── Feature C

Each branch is reviewed before merging.


Why Branching Is Important

Branching allows developers to:

  • Work independently
  • Prevent conflicts
  • Test safely
  • Review code
  • Protect production code
  • Isolate unfinished features

Without branching:

  • Developers overwrite one another’s work.
  • Unfinished code reaches production.
  • Rollbacks become difficult.

Common Branching Strategies

Several branching strategies are commonly used.


Feature Branch Workflow

The most common approach.

Each new feature receives its own branch.

Example:

Main
├── feature/AddOrders
├── feature/AddInvoices
├── feature/SearchCustomers

Advantages:

  • Easy code review
  • Simple testing
  • Low risk
  • Small pull requests

This is one of the most common approaches for SQL Database Projects.


GitFlow

GitFlow introduces several branch types.

Main
Develop
Feature Branches
Release Branches
Hotfix Branches

Typical workflow:

Main
Develop
Feature Branch
Develop
Release
Main

Advantages:

  • Strong release management
  • Good for large teams
  • Stable production releases

Disadvantages:

  • More complex
  • Additional branch management

Trunk-Based Development

Developers merge frequently into a single shared branch.

Main
Developer 1
Developer 2
Developer 3
Developer 4

Developers create very short-lived branches.

Advantages:

  • Small changes
  • Faster integration
  • Less merge complexity

Disadvantages:

  • Requires excellent automated testing
  • Requires disciplined developers

Branch Protection Policies

Branch protection prevents unsafe changes.

The main branch is typically protected.

Developers cannot:

  • Force push
  • Delete the branch
  • Merge without approval
  • Merge failed builds
  • Bypass policies

Example policy:

Main Branch
✓ Build must succeed
✓ Two reviewers required
✓ No direct commits
✓ Status checks pass
✓ Linked work item required
✓ Up-to-date before merge

These policies dramatically reduce deployment mistakes.


Common Branch Protection Rules

Organizations often require:

Required Pull Requests

Direct commits are blocked.

Developers must create a pull request.


Required Reviewers

Example:

Minimum Reviewers = 2

Multiple reviewers reduce errors.


Successful Build Required

If automated validation fails, merging is blocked.

Example:

Build Failed
Merge Blocked

Required Status Checks

Policies verify that:

  • Unit tests passed
  • Integration tests passed
  • Security scans completed
  • SQL build succeeded
  • Code quality passed

Only then is the merge allowed.


Prevent Force Push

Force pushes rewrite Git history.

Most organizations disable them for protected branches.


Prevent Branch Deletion

Important branches should never be accidentally removed.

Branch protection prevents deletion.


Pull Requests (PRs)

A pull request requests permission to merge one branch into another.

Example:

Feature Branch
Pull Request
Review
Approval
Merge

A pull request usually includes:

  • Description
  • Changed files
  • SQL object modifications
  • Reviewer comments
  • Build status
  • Test results

Benefits of Pull Requests

Pull requests improve quality by encouraging:

  • Peer review
  • Knowledge sharing
  • Early defect detection
  • Security review
  • Coding standard enforcement

For SQL projects, reviewers often examine:

  • Table changes
  • Index changes
  • Stored procedures
  • Permissions
  • Migration scripts
  • Performance impacts

Code Reviews

Code reviews help identify issues before deployment.

Reviewers commonly check:

Correctness

Does the SQL produce the expected results?

Performance

Are indexes appropriate?

Will queries scale?

Security

Are permissions appropriate?

Is SQL injection prevented?

Maintainability

Is the code readable?

Are naming standards followed?

Backward Compatibility

Will existing applications continue working?


Code Owners

One important governance feature is Code Owners.

A Code Owners file automatically assigns reviewers based on the files that change.

Example:

Tables/*
→ Database Team
StoredProcedures/*
→ Backend Team
Security/*
→ Security Team

When a developer modifies a protected object, the correct experts are automatically requested to review the change.

Benefits of Code Owners

Code Owners provide several advantages:

  • Automatic reviewer assignment
  • Faster review workflows
  • Consistent governance
  • Improved accountability
  • Better code quality
  • Subject matter expert validation
  • Compliance with organizational policies

For example:

  • Changes to security-related scripts can require approval from the security team.
  • Changes to database schema objects can require approval from database administrators.
  • Changes to deployment scripts can require DevOps team approval.

This ensures that critical database components are always reviewed by the appropriate personnel before deployment.


Best Practices for Branching and Pull Requests

Microsoft recommends following modern DevOps practices when managing SQL Database Projects.

Some recommended best practices include:

  • Create small, focused feature branches.
  • Keep branches short-lived.
  • Merge changes frequently.
  • Require pull requests for protected branches.
  • Require successful builds before merging.
  • Require automated tests before deployment.
  • Require peer reviews.
  • Protect the main branch from direct commits.
  • Use Code Owners for sensitive database objects.
  • Document pull requests with clear descriptions.
  • Resolve merge conflicts promptly.
  • Use descriptive branch names such as:
    • feature/AddCustomerSearch
    • bugfix/FixDeadlockIssue
    • hotfix/CorrectCustomerIndex

Following these practices improves collaboration, reduces deployment risk, and helps maintain a reliable, auditable database development process.


Part 1 Summary

In this first part, you learned the foundational deployment pipeline controls that are central to modern SQL DevOps and the DP-800 exam:

  • The purpose of deployment pipeline controls
  • The role of SQL Database Projects in CI/CD
  • Continuous Integration (CI) and Continuous Delivery (CD)
  • Common branching strategies (Feature Branch, GitFlow, and Trunk-Based Development)
  • Branch protection policies and why they matter
  • Pull requests and peer code reviews
  • Code Owners and automated reviewer assignment
  • Best practices for secure and reliable database development

Go to the DP-800 Exam Prep Hub main page

Create triggers (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 triggers


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

Triggers are special types of stored procedures that automatically execute (or “fire”) in response to specific database events. Unlike stored procedures, which must be executed explicitly by a user or application, triggers are invoked automatically by SQL Server when certain Data Manipulation Language (DML), Data Definition Language (DDL), or logon events occur.

Triggers are commonly used to enforce complex business rules, maintain audit trails, synchronize related data, validate changes, and perform automated actions that occur whenever data or database objects are modified. While triggers are powerful, they should be used judiciously because they can add complexity and affect database performance if not carefully designed.

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

  • What triggers are
  • DML triggers
  • DDL triggers
  • AFTER and INSTEAD OF triggers
  • The inserted and deleted logical tables
  • Creating, altering, disabling, enabling, and dropping triggers
  • Nested and recursive triggers
  • Performance considerations
  • Best practices
  • AI-enabled database scenarios

Understanding triggers is important because they provide automatic execution of business logic while helping maintain data integrity and automate administrative tasks.


What Is a Trigger?

A trigger is a database object that automatically executes when a specified event occurs.

Triggers are associated with:

  • Tables
  • Views
  • Databases
  • SQL Server instances (for certain DDL and logon events)

Triggers cannot be executed directly using the EXEC statement.

Instead, SQL Server executes them automatically when the triggering event occurs.


Types of Triggers

SQL Server supports several types of triggers:

  • DML triggers
  • DDL triggers
  • Logon triggers

The DP-800 exam primarily focuses on DML and DDL triggers.


DML Triggers

Data Manipulation Language (DML) triggers fire when data is modified.

They respond to:

  • INSERT
  • UPDATE
  • DELETE

Typical uses include:

  • Auditing data changes
  • Enforcing business rules
  • Validating updates
  • Synchronizing tables
  • Recording historical information

AFTER Triggers

An AFTER trigger executes only after the triggering statement completes successfully.

Example:

CREATE TRIGGER trgCustomerAudit
ON Sales.Customers
AFTER INSERT
AS
BEGIN
INSERT INTO Sales.CustomerAudit
(
CustomerID,
AuditDate
)
SELECT
CustomerID,
GETDATE()
FROM inserted;
END;

The trigger records newly inserted customers after the insert operation succeeds.


INSTEAD OF Triggers

An INSTEAD OF trigger executes in place of the triggering action.

Example:

CREATE TRIGGER trgPreventDelete
ON Sales.Customers
INSTEAD OF DELETE
AS
BEGIN
PRINT 'Deleting customers is not permitted.';
END;

The DELETE statement never executes because the trigger replaces it.

INSTEAD OF triggers are commonly used on:

  • Views
  • Complex update scenarios
  • Custom validation logic

DDL Triggers

DDL triggers respond to schema changes.

Common events include:

  • CREATE TABLE
  • ALTER TABLE
  • DROP TABLE
  • CREATE PROCEDURE
  • ALTER PROCEDURE
  • DROP PROCEDURE

Example:

CREATE TRIGGER trgAuditDDL
ON DATABASE
FOR CREATE_TABLE
AS
BEGIN
PRINT 'A table was created.';
END;

DDL triggers help monitor or prevent unauthorized schema modifications.


Logon Triggers

Logon triggers execute when a user establishes a SQL Server session.

Typical uses include:

  • Restricting connections
  • Recording login activity
  • Enforcing security policies

Logon triggers are created at the server level and are not supported in Azure SQL Database.


The inserted Logical Table

Whenever rows are inserted or updated, SQL Server creates a temporary logical table named inserted.

It contains the new version of affected rows.

Example:

SELECT *
FROM inserted;

The inserted table exists only during trigger execution.


The deleted Logical Table

Whenever rows are deleted or updated, SQL Server creates a logical table named deleted.

It contains the original version of affected rows.

Example:

SELECT *
FROM deleted;

For UPDATE operations:

  • deleted contains old values.
  • inserted contains new values.

Auditing Changes

Triggers are frequently used to create audit trails.

Example:

CREATE TRIGGER trgAuditSalary
ON HumanResources.Employees
AFTER UPDATE
AS
BEGIN
INSERT INTO HumanResources.SalaryAudit
(
EmployeeID,
OldSalary,
NewSalary,
ChangeDate
)
SELECT
d.EmployeeID,
d.Salary,
i.Salary,
GETDATE()
FROM deleted d
INNER JOIN inserted i
ON d.EmployeeID = i.EmployeeID;
END;

This trigger records salary changes for auditing purposes.


Enforcing Business Rules

Triggers can prevent invalid operations.

Example:

CREATE TRIGGER trgNoNegativeInventory
ON Inventory.Products
AFTER UPDATE
AS
BEGIN
IF EXISTS
(
SELECT *
FROM inserted
WHERE Quantity < 0
)
BEGIN
RAISERROR
(
'Inventory cannot be negative.',
16,
1
);
ROLLBACK TRANSACTION;
END;
END;

The trigger rolls back the transaction if inventory becomes negative.


Multi-Row Operations

Triggers execute once per SQL statement, not once per affected row.

For example:

UPDATE Sales.Customers
SET City = 'Miami';

If 10,000 rows are updated, the trigger executes only once.

The inserted and deleted tables contain all affected rows.

Developers should always write triggers using set-based logic, not assumptions that only one row is affected.


Nested Triggers

A trigger can cause another trigger to fire.

Example:

  • Trigger A updates Table B.
  • Table B has Trigger B.
  • Trigger B executes automatically.

This behavior is called nested triggers.

SQL Server supports nested triggers up to a configurable limit.


Recursive Triggers

A recursive trigger fires itself either directly or indirectly.

Example:

  • Trigger updates its own table.
  • That update causes the same trigger to execute again.

Recursive triggers are disabled by default in many environments and should be used with caution to avoid infinite loops.


Enabling and Disabling Triggers

Disable a trigger:

DISABLE TRIGGER trgCustomerAudit
ON Sales.Customers;

Enable it:

ENABLE TRIGGER trgCustomerAudit
ON Sales.Customers;

Disabling a trigger preserves its definition while preventing it from firing.


Modifying a Trigger

Use ALTER TRIGGER.

Example:

ALTER TRIGGER trgCustomerAudit
ON Sales.Customers
AFTER INSERT
AS
BEGIN
PRINT 'Customer inserted.';
END;

Deleting a Trigger

Use:

DROP TRIGGER trgCustomerAudit;

Viewing Trigger Definitions

Developers can inspect a trigger using:

sp_helptext 'trgCustomerAudit';

Or:

SELECT OBJECT_DEFINITION
(
OBJECT_ID('trgCustomerAudit')
);

Triggers vs. Stored Procedures

FeatureTriggerStored Procedure
Executes automaticallyYesNo
Invoked by EXECNoYes
Responds to database eventsYesNo
Accepts parametersNoYes
Returns result setsNot intended for callersYes

Triggers vs. Constraints

FeatureTriggerConstraint
Enforces simple rulesPossibleYes
Enforces complex business logicYesLimited
Can reference multiple tablesYesLimited
Executes automaticallyYesYes

Constraints should generally be preferred for simple validation rules because they are simpler and often more efficient.


Performance Considerations

Triggers execute within the same transaction as the triggering statement.

Poorly designed triggers can:

  • Increase transaction duration
  • Increase locking
  • Reduce concurrency
  • Consume additional CPU resources
  • Introduce blocking
  • Increase deadlock risk

Best practices include:

  • Keep trigger logic simple.
  • Use set-based operations.
  • Avoid unnecessary queries.
  • Avoid long-running operations.
  • Minimize external dependencies.
  • Do not assume only one row is affected.

Security Considerations

Triggers can:

  • Audit sensitive changes
  • Prevent unauthorized updates
  • Enforce compliance policies
  • Record administrative activity
  • Restrict schema modifications using DDL triggers

Proper permissions should be applied because trigger code executes in the database context.


AI-Enabled Database Scenarios

Triggers can support AI-enabled database solutions by automating actions whenever data changes.

Examples include:

  • Recording changes that require new embeddings to be generated
  • Logging modifications to AI training datasets
  • Flagging rows for downstream vectorization processes
  • Updating AI metadata tables after inserts or updates
  • Capturing prompt history for auditing
  • Initiating workflows that prepare data for intelligent search or Retrieval-Augmented Generation (RAG)

Although triggers cannot directly invoke external AI services, they can populate work queues or status tables that downstream applications or services process.


Best Practices

  • Prefer constraints for simple validation.
  • Use triggers only when automatic behavior is required.
  • Write triggers using set-based logic.
  • Minimize execution time.
  • Avoid recursive logic unless absolutely necessary.
  • Test triggers with multi-row operations.
  • Document business rules implemented by triggers.
  • Avoid unnecessary nested trigger chains.
  • Monitor trigger performance.
  • Audit only the information that is required.

Common Exam Tips

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

  • Triggers execute automatically in response to events.
  • DML triggers respond to INSERT, UPDATE, and DELETE statements.
  • DDL triggers respond to schema changes.
  • AFTER triggers execute after the triggering statement completes successfully.
  • INSTEAD OF triggers replace the triggering action.
  • inserted contains new row values.
  • deleted contains original row values.
  • Triggers fire once per statement, not once per row.
  • Use ALTER TRIGGER to modify a trigger.
  • Use DISABLE TRIGGER, ENABLE TRIGGER, and DROP TRIGGER to manage trigger lifecycle.

Practice Exam Questions

Question 1

A developer wants database logic to execute automatically whenever rows are inserted into a table. Which database object should be used?

A. Stored procedure

B. Trigger

C. View

D. Scalar function

Answer: B

Explanation: Triggers automatically execute in response to specified database events such as INSERT, UPDATE, or DELETE operations.


Question 2

Which type of trigger executes only after the triggering statement has completed successfully?

A. BEFORE trigger

B. INSTEAD OF trigger

C. AFTER trigger

D. LOGON trigger

Answer: C

Explanation: An AFTER trigger fires only after the triggering DML statement has completed successfully and any associated constraints have been processed.


Question 3

During an UPDATE operation, which logical table contains the original values of the modified rows?

A. inserted

B. updated

C. original

D. deleted

Answer: D

Explanation: During an UPDATE, the deleted logical table contains the original row values, while the inserted table contains the new values.


Question 4

Which trigger type replaces the original INSERT, UPDATE, or DELETE operation?

A. AFTER trigger

B. DDL trigger

C. INSTEAD OF trigger

D. Recursive trigger

Answer: C

Explanation: An INSTEAD OF trigger executes instead of the triggering statement, allowing custom processing or validation.


Question 5

A trigger is written assuming that only one row is updated at a time. Why is this a problem?

A. SQL Server executes one trigger for every row.

B. Triggers always execute asynchronously.

C. Triggers execute once per SQL statement and may process many affected rows.

D. UPDATE statements cannot affect multiple rows.

Answer: C

Explanation: SQL Server fires DML triggers once per statement, so developers must use set-based logic to correctly process all affected rows.


Question 6

Which statement disables a trigger while preserving its definition?

A. REMOVE TRIGGER

B. DROP TRIGGER

C. ALTER TRIGGER

D. DISABLE TRIGGER

Answer: D

Explanation: DISABLE TRIGGER prevents a trigger from firing without deleting it, allowing it to be re-enabled later.


Question 7

Which statement best describes a DDL trigger?

A. It responds to changes in table data.

B. It responds to schema modification events such as CREATE, ALTER, or DROP statements.

C. It executes only during user logins.

D. It replaces the execution of stored procedures.

Answer: B

Explanation: DDL triggers respond to schema-related events, making them useful for auditing or preventing structural database changes.


Question 8

Which object is generally preferred for enforcing a simple rule such as ensuring a value is greater than zero?

A. AFTER trigger

B. CHECK constraint

C. DDL trigger

D. Stored procedure

Answer: B

Explanation: CHECK constraints are simpler, easier to maintain, and generally more efficient than triggers for straightforward validation rules.


Question 9

Which statement correctly describes nested triggers?

A. They occur only with DDL triggers.

B. They allow a trigger to execute dynamic SQL.

C. They occur when one trigger causes another trigger to fire.

D. They are required whenever inserted and deleted tables are referenced.

Answer: C

Explanation: Nested triggers occur when the actions performed by one trigger cause another trigger to execute.


Question 10

How can triggers support AI-enabled database solutions?

A. They automatically generate embeddings by calling AI models directly.

B. They replace vector indexes.

C. They eliminate the need for application code.

D. They automatically detect data changes and populate work queues, audit tables, or status records that downstream AI processes use to generate embeddings, update indexes, or prepare RAG data.

Answer: D

Explanation: Triggers are well suited for detecting data changes and initiating downstream workflows by recording changes or updating processing queues. External applications or services can then consume these queues to perform AI-related tasks such as embedding generation or intelligent indexing.


Go to the DP-800 Exam Prep Hub main page