A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-database-transact-sql-set-options below:

ALTER DATABASE SET Options (Transact-SQL) - SQL Server

Sets database options in Microsoft SQL Server, Azure SQL Database, and Azure Synapse Analytics. For other ALTER DATABASE options, see ALTER DATABASE.

Note

Setting some options with ALTER DATABASE might require exclusive database access. If the ALTER DATABASE statement doesn't complete in a timely manner, check to see if other sessions within the database are blocking the ALTER DATABASE session.

For more information about the syntax conventions, see Transact-SQL syntax conventions.

Select a product

In the following row, select whichever product name you're interested in. Doing that displays different content here on this webpage, appropriate for whichever product you select.

* SQL Server *  

SQL Database

SQL Managed Instance

Azure Synapse
Analytics

Microsoft Fabric

SQL Server

Database mirroring, Always On availability groups, and compatibility levels are SET options but are described in separate articles because of their length. For more information, see ALTER DATABASE Database Mirroring, ALTER DATABASE SET HADR, and ALTER DATABASE compatibility level.

Database scoped configurations are used to set several database configurations at the individual database level. For more information, see ALTER DATABASE SCOPED CONFIGURATION.

Note

Many database set options can be configured for the current session by using SET statements and are often configured by applications when they connect. Session-level set options override the ALTER DATABASE SET values. The database options described in the following sections are values that you can set for sessions that don't explicitly provide other set option values.

Syntax
ALTER DATABASE { database_name | CURRENT }
SET
{
    <option_spec> [ ,...n ] [ WITH <termination> ]
}

<option_spec> ::=
{
    <accelerated_database_recovery>
  | <auto_option>
  | <automatic_tuning_option>
  | <change_tracking_option>
  | <containment_option>
  | <cursor_option>
  | <data_retention_policy>
  | <database_mirroring_option>
  | <date_correlation_optimization_option>
  | <db_encryption_option>
  | <db_state_option>
  | <db_update_option>
  | <db_user_access_option>
  | <delayed_durability_option>
  | <external_access_option>
  | FILESTREAM ( <FILESTREAM_option> )
  | <HADR_options>
  | <mixed_page_allocation_option>
  | <optimized_locking>
  | <parameterization_option>
  | <query_store_options>
  | <recovery_option>
  | <remote_data_archive_option>
  | <persistent_log_buffer_option>
  | <service_broker_option>
  | <snapshot_option>
  | <sql_option>
  | <suspend_for_snapshot_backup>
  | <target_recovery_time_option>
  | <termination>
  | <temporal_history_retention>
}
;

<accelerated_database_recovery> ::=
{
    ACCELERATED_DATABASE_RECOVERY = { ON | OFF }
     [ ( PERSISTENT_VERSION_STORE_FILEGROUP = { filegroup name } ) ]
}

<auto_option> ::=
{
    AUTO_CLOSE { ON | OFF }
  | AUTO_CREATE_STATISTICS { OFF | ON [ ( INCREMENTAL = { ON | OFF } ) ] }
  | AUTO_SHRINK { ON | OFF }
  | AUTO_UPDATE_STATISTICS { ON | OFF }
  | AUTO_UPDATE_STATISTICS_ASYNC { ON | OFF }
}

<automatic_tuning_option> ::=
{
    AUTOMATIC_TUNING ( FORCE_LAST_GOOD_PLAN = { DEFAULT | ON | OFF } )
}

<change_tracking_option> ::=
{
    CHANGE_TRACKING
   {
       = OFF
     | = ON [ ( <change_tracking_option_list > [,...n] ) ]
     | ( <change_tracking_option_list> [,...n] )
   }
}

<change_tracking_option_list> ::=
{
   AUTO_CLEANUP = { ON | OFF }
 | CHANGE_RETENTION = retention_period { DAYS | HOURS | MINUTES }
}

<containment_option> ::=
   CONTAINMENT = { NONE | PARTIAL }

<cursor_option> ::=
{
    CURSOR_CLOSE_ON_COMMIT { ON | OFF }
  | CURSOR_DEFAULT { LOCAL | GLOBAL }
}

<database_mirroring_option>
  ALTER DATABASE Database Mirroring

<date_correlation_optimization_option> ::=
    DATE_CORRELATION_OPTIMIZATION { ON | OFF }

<db_encryption_option> ::=
    ENCRYPTION { ON | OFF | SUSPEND | RESUME }

<db_state_option> ::=
    { ONLINE | OFFLINE | EMERGENCY }

<db_update_option> ::=
    { READ_ONLY | READ_WRITE }

<db_user_access_option> ::=
    { SINGLE_USER | RESTRICTED_USER | MULTI_USER }

<delayed_durability_option> ::=
    DELAYED_DURABILITY = { DISABLED | ALLOWED | FORCED }

<external_access_option> ::=
{
    DB_CHAINING { ON | OFF }
  | TRUSTWORTHY { ON | OFF }
  | DEFAULT_FULLTEXT_LANGUAGE = { <lcid> | <language name> | <language alias> }
  | DEFAULT_LANGUAGE = { <lcid> | <language name> | <language alias> }
  | NESTED_TRIGGERS = { OFF | ON }
  | TRANSFORM_NOISE_WORDS = { OFF | ON }
  | TWO_DIGIT_YEAR_CUTOFF = { 1753, ..., 2049, ..., 9999 }
}

<FILESTREAM_option> ::=
{
    NON_TRANSACTED_ACCESS = { OFF | READ_ONLY | FULL
  | DIRECTORY_NAME = <directory_name>
}

<HADR_options> ::=
    ALTER DATABASE SET HADR

<mixed_page_allocation_option> ::=
    MIXED_PAGE_ALLOCATION { OFF | ON }

<parameterization_option> ::=
    PARAMETERIZATION { SIMPLE | FORCED }

<query_store_options> ::=
{
    QUERY_STORE
    {
          = OFF [ ( FORCED ) ]
        | = ON [ ( <query_store_option_list> [,...n] ) ]
        | ( < query_store_option_list> [,...n] )
        | CLEAR [ ALL ]
    }
}

<query_store_option_list> ::=
{
      OPERATION_MODE = { READ_WRITE | READ_ONLY }
    | CLEANUP_POLICY = ( STALE_QUERY_THRESHOLD_DAYS = number )
    | DATA_FLUSH_INTERVAL_SECONDS = number
    | MAX_STORAGE_SIZE_MB = number
    | INTERVAL_LENGTH_MINUTES = number
    | SIZE_BASED_CLEANUP_MODE = { AUTO | OFF }
    | QUERY_CAPTURE_MODE = { ALL | AUTO | CUSTOM | NONE }
    | MAX_PLANS_PER_QUERY = number
    | WAIT_STATS_CAPTURE_MODE = { ON | OFF }
    | QUERY_CAPTURE_POLICY = ( <query_capture_policy_option_list> [,...n] )
}

<query_capture_policy_option_list> :: =
{
      STALE_CAPTURE_POLICY_THRESHOLD = number { DAYS | HOURS }
    | EXECUTION_COUNT = number
    | TOTAL_COMPILE_CPU_TIME_MS = number
    | TOTAL_EXECUTION_CPU_TIME_MS = number
}

<recovery_option> ::=
{
    RECOVERY { FULL | BULK_LOGGED | SIMPLE }
  | TORN_PAGE_DETECTION { ON | OFF }
  | PAGE_VERIFY { CHECKSUM | TORN_PAGE_DETECTION | NONE }
}

<remote_data_archive_option> ::=
{
    REMOTE_DATA_ARCHIVE =
    {
        ON ( SERVER = <server_name>,
             {
                  CREDENTIAL = <db_scoped_credential_name>
                  | FEDERATED_SERVICE_ACCOUNT = ON | OFF
             }
        )
        | OFF
    }
}

<persistent_log_buffer_option> ::=
{
    PERSISTENT_LOG_BUFFER 
    {
          = ON (DIRECTORY_NAME= 'path-to-directory-on-a-DAX-volume')
        | = OFF
    }
}

<service_broker_option> ::=
{
    ENABLE_BROKER
  | DISABLE_BROKER
  | NEW_BROKER
  | ERROR_BROKER_CONVERSATIONS
  | HONOR_BROKER_PRIORITY { ON | OFF }
}

<snapshot_option> ::=
{
    ALLOW_SNAPSHOT_ISOLATION { ON | OFF }
  | READ_COMMITTED_SNAPSHOT { ON | OFF }
  | MEMORY_OPTIMIZED_ELEVATE_TO_SNAPSHOT = { ON | OFF }
}

<sql_option> ::=
{
    ANSI_NULL_DEFAULT { ON | OFF }
  | ANSI_NULLS { ON | OFF }
  | ANSI_PADDING { ON | OFF }
  | ANSI_WARNINGS { ON | OFF }
  | ARITHABORT { ON | OFF }
  | COMPATIBILITY_LEVEL = { 160 | 150 | 140 | 130 | 120 | 110 | 100 }
  | CONCAT_NULL_YIELDS_NULL { ON | OFF }
  | NUMERIC_ROUNDABORT { ON | OFF }
  | QUOTED_IDENTIFIER { ON | OFF }
  | RECURSIVE_TRIGGERS { ON | OFF }
}

<suspend_for_snapshot_backup> ::=
    SET SUSPEND_FOR_SNAPSHOT_BACKUP = { ON | OFF } [ ( MODE = COPY_ONLY ) ]

<target_recovery_time_option> ::=
    TARGET_RECOVERY_TIME = target_recovery_time { SECONDS | MINUTES }

<termination>::=
{
    ROLLBACK AFTER number [ SECONDS ]
  | ROLLBACK IMMEDIATE
  | NO_WAIT
}

<temporal_history_retention> ::=
    TEMPORAL_HISTORY_RETENTION { ON | OFF }

<data_retention_policy> ::=
    DATA_RETENTION { ON | OFF }

<optimized_locking> ::=
{
    OPTIMIZED_LOCKING = { ON | OFF }
}
Arguments database_name

The name of the database to be modified.

CURRENT

Applies to: SQL Server (Starting with SQL Server 2012 (11.x))

Runs the action in the current database. CURRENT isn't supported for all options in all contexts. If CURRENT fails, provide the database name.

<accelerated_database_recovery> ::=

Applies to: SQL Server (Starting with SQL Server 2019 (15.x))

Enables accelerated database recovery (ADR). ADR is set to OFF by default in SQL Server 2019 (15.x) and later. By using this syntax, you can designate a specific filegroup for the Persistent Version Store (PVS) data. If no filegroup is specified, PVS uses the PRIMARY filegroup. For more information, see Manage accelerated database recovery.

To set ACCELERATED_DATABASE_RECOVERY ON or OFF, there must be no active connections to the database except for the connection running the ALTER DATABASE command. However, the database doesn't have to be in single-user mode. You can't change the state of this option unless the database is ONLINE.

<auto_option> ::=

Controls automatic options.

AUTO_CLOSE { ON | OFF }

Note

The AUTO_CLOSE option isn't available in a contained database or on SQL Database. You can determine this option's status by examining the is_auto_close_on column in the sys.databases catalog view or the IsAutoClose property of the DATABASEPROPERTYEX function.

When AUTO_CLOSE is set to ON, some columns in the sys.databases catalog view and the DATABASEPROPERTYEX function returns NULL because the database is unavailable to retrieve the data. To resolve this issue, run a USE statement to open the database.

Database mirroring requires AUTO_CLOSE set to OFF.

When the database is set to AUTOCLOSE = ON, an operation that initiates an automatic database shutdown clears the plan cache for the instance of SQL Server. Clearing the plan cache causes a recompilation of all subsequent execution plans and can cause a sudden, temporary decrease in query performance. Starting with SQL Server 2005 (9.x) Service Pack 2, for each cleared cache store in the plan cache, the SQL Server error log contains the following informational message: SQL Server has encountered %d occurrence(s) of cachestore flush for the '%s' cachestore (part of plan cache) due to some database maintenance or reconfigure operations. This message is logged every five minutes as long as the cache is flushed within that time interval.

The AUTO_CLOSE setting can be a useful feature in some rare situations, for example, in a SQL Server instance without enough memory to operate stably with a large number of databases, or for a legacy 32-bit SQL Server instance with a large number of databases. In such scenarios, it might be useful to enable AUTO_CLOSE and conserve the memory resources required to keep a database open when there's no application using the database. When the database is open, some default memory allocations are required (for example, internal structures to represent various database metadata objects and transaction log buffers).

AUTO_CREATE_STATISTICS { ON | OFF }

You can determine this option's status by examining the is_auto_create_stats_on column in the sys.databases catalog view. You can also determine the status by examining the IsAutoCreateStatistics property of the DATABASEPROPERTYEX function.

For more information, see the section "Using the Database-wide statistics options" in Statistics.

INCREMENTAL = ON | OFF

Applies to: SQL Server (Starting with SQL Server 2014 (12.x)) and Azure SQL Database

Set AUTO_CREATE_STATISTICS to ON, and set INCREMENTAL to ON. This sets automatically created stats as incremental whenever incremental stats are supported. The default value is OFF. For more information, see CREATE STATISTICS.

AUTO_SHRINK { ON | OFF }

You can determine this option's status by examining the is_auto_shrink_on column in the sys.databases catalog view. You can also determine the status by examining the IsAutoShrink property of the DATABASEPROPERTYEX function.

Note

The AUTO_SHRINK option isn't available in a Contained Database.

AUTO_UPDATE_STATISTICS { ON | OFF }

You can determine this option's status by examining the is_auto_update_stats_on column in the sys.databases catalog view. You can also determine the status by examining the IsAutoUpdateStatistics property of the DATABASEPROPERTYEX function.

For more information, see the section "Using the Database-wide statistics options" in Statistics.

AUTO_UPDATE_STATISTICS_ASYNC { ON | OFF }

You can determine this option's status by examining the is_auto_update_stats_async_on column in the sys.databases catalog view.

For more information that describes when to use synchronous or asynchronous statistics updates, see the "Statistics options" section in Statistics.

<automatic_tuning_option> ::=

Applies to: SQL Server (Starting with SQL Server 2017 (14.x))

Enables or disables FORCE_LAST_GOOD_PLAN Automatic tuning option. You can view the status of this option in the view sys.database_automatic_tuning_options.

FORCE_LAST_GOOD_PLAN = { DEFAULT | ON | OFF } <change_tracking_option> ::=

Applies to: SQL Server and Azure SQL Database

Controls change tracking options. You can enable change tracking, set options, change options, and disable change tracking. For examples, see the Examples section later in this article.

<containment_option> ::=

Applies to: SQL Server (Starting with SQL Server 2012 (11.x))

Controls database containment options.

CONTAINMENT = { NONE | PARTIAL} <cursor_option> ::=

Controls cursor options.

CURSOR_CLOSE_ON_COMMIT { ON | OFF }

Connection-level settings that are set by using the SET statement override the default database setting for CURSOR_CLOSE_ON_COMMIT. ODBC and OLE DB clients issue a connection-level SET statement setting CURSOR_CLOSE_ON_COMMIT to OFF for the session, by default. The clients run the statement when you connect to an instance of SQL Server. For more information, see SET CURSOR_CLOSE_ON_COMMIT.

You can determine this option's status by examining the is_cursor_close_on_commit_on column in the sys.databases catalog view or the IsCloseCursorsOnCommitEnabled property of the DATABASEPROPERTYEX function.

CURSOR_DEFAULT { LOCAL | GLOBAL }

Applies to: SQL Server

Controls whether cursor scope uses LOCAL or GLOBAL.

You can determine this option's status by examining the is_local_cursor_default column in the sys.databases catalog view. You can also determine the status by examining the IsLocalCursorsDefault property of the DATABASEPROPERTYEX function.

<temporal_history_retention> ::= TEMPORAL_HISTORY_RETENTION { ON | OFF }

ON by default but also automatically set to OFF after point in time restore operation. For more information including how to enable this setting, see How to configure retention policy.

<data_retention_policy> ::=

Applies to: Azure SQL Edge only.

DATA_RETENTION { ON | OFF } <database_mirroring>

Applies to: SQL Server

For the argument descriptions, see ALTER DATABASE Database Mirroring.

<date_correlation_optimization_option> ::=

Applies to: SQL Server

Controls the date_correlation_optimization option.

DATE_CORRELATION_OPTIMIZATION { ON | OFF }

To set DATE_CORRELATION_OPTIMIZATION to ON, there must be no active connections to the database except for the connection that's executing the ALTER DATABASE statement. Afterwards, multiple connections are supported.

The current setting of this option can be determined by examining the is_date_correlation_on column in the sys.databases catalog view.

<db_encryption_option> ::=

Controls the database encryption state.

ENCRYPTION { ON | OFF | SUSPEND | RESUME }

For more information about database encryption, see Transparent data encryption (TDE), and Transparent data encryption for Azure SQL Database, Azure SQL Managed Instance, and Azure Synapse Analytics.

When encryption is enabled at the database level, all file groups are encrypted. Any new file groups inherit the encrypted property. If any file groups in the database are set to READ ONLY, the database encryption operation fails.

You can see the encryption state of the database and the state of the encryption scan by using the sys.dm_database_encryption_keys dynamic management view.

<db_state_option> ::=

Applies to: SQL Server

Controls the state of the database.

Requires the ALTER DATABASE permission for the subject database, to change a database to the offline or emergency state, and the server level ALTER ANY DATABASE permission to move a database from offline to online.

You can determine this option's status by examining the state and state_desc columns in the sys.databases catalog view. You can also determine the status by examining the Status property of the DATABASEPROPERTYEX function. For more information, see Database States.

A database marked as RESTORING can't be set to OFFLINE, ONLINE, or EMERGENCY. A database could be in the RESTORING state during an active restore operation or when a restore operation of a database or log file fails because of a corrupted backup file.

<db_update_option> ::=

Controls whether updates are allowed on the database.

To change this state, you must have exclusive access to the database. For more information, see the SINGLE_USER clause.

Note

On Azure SQL Database federated databases, SET { READ_ONLY | READ_WRITE } is disabled.

<db_user_access_option> ::=

Controls user access to the database.

SINGLE_USER

Applies to: SQL Server

Specifies that only one user at a time can access the database. If you specify SINGLE_USER and another user connects to the database, the ALTER DATABASE statement is blocked until all users disconnect from the specified database. To override this behavior, see the WITH <termination> clause.

The database remains in SINGLE_USER mode even if the user that set the option signs out. At that point, a different user, but only one, can connect to the database.

Before you set the database to SINGLE_USER, verify the AUTO_UPDATE_STATISTICS_ASYNC option is set to OFF. When set to ON, the background thread used to update statistics takes a connection against the database, and you can't access the database in single-user mode. To view the status of this option, query the is_auto_update_stats_async_on column in the sys.databases catalog view. If the option is set to ON, perform the following tasks:

  1. Set AUTO_UPDATE_STATISTICS_ASYNC to OFF.

  2. Check for active asynchronous statistics jobs by querying the sys.dm_exec_background_job_queue dynamic management view.

If there are active jobs, either allow the jobs to complete or manually terminate them by using KILL STATS JOB.

RESTRICTED_USER

Allows for only members of the db_owner fixed database role and dbcreator and sysadmin fixed server roles to connect to the database. RESTRICTED_USER doesn't limit their number. Disconnect all connections to the database using the timeframe specified by the ALTER DATABASE statement's termination clause. After the database has transitioned to the RESTRICTED_USER state, connection attempts by unqualified users are refused.

MULTI_USER

All users that have the appropriate permissions to connect to the database are allowed. You can determine this option's status by examining the user_access column in the sys.databases catalog view. You can also determine the status by examining the UserAccess property of the DATABASEPROPERTYEX function.

<delayed_durability_option> ::=

Applies to: SQL Server (Starting with SQL Server 2014 (12.x))

Controls whether transactions commit fully durable or delayed durable.

<external_access_option> ::=

Applies to: SQL Server

Controls whether the database can be accessed by external resources, such as objects from another database.

DB_CHAINING { ON | OFF }

Important

The instance of SQL Server recognizes this setting when the cross db ownership chaining server option is 0 (OFF). When cross db ownership chaining is 1 (ON), all user databases can participate in cross-database ownership chains, regardless of the value of this option. This option is set by using sp_configure.

To set this option, requires CONTROL SERVER permission on the database.

The DB_CHAINING option can't be set on the master, model, and tempdb system databases.

You can determine this option's status by examining the is_db_chaining_on column in the sys.databases catalog view.

TRUSTWORTHY { ON | OFF }

By default, all system databases except the msdb database have TRUSTWORTHY set to OFF. The value can't be changed for the model and tempdb databases. We recommend that you never set the TRUSTWORTHY option to ON for the master database.

To set this option, requires CONTROL SERVER permission on the database.

You can determine this option's status by examining the is_trustworthy_on column in the sys.databases catalog view.

DEFAULT_FULLTEXT_LANGUAGE

Applies to: SQL Server (Starting with SQL Server 2012 (11.x))

Specifies the default language value for full-text indexed columns.

Important

This option is allowable only when CONTAINMENT has been set to PARTIAL. If CONTAINMENT is set to NONE, errors occur.

DEFAULT_LANGUAGE

Applies to: SQL Server (Starting with SQL Server 2012 (11.x))

Specifies the default language for all newly created logins. Language can be specified by providing the local ID (lcid), the language name, or the language alias. For a list of acceptable language names and aliases, see sys.syslanguages. This option is allowable only when CONTAINMENT has been set to PARTIAL. If CONTAINMENT is set to NONE, errors occur.

NESTED_TRIGGERS

Applies to: SQL Server (Starting with SQL Server 2012 (11.x))

Specifies whether an AFTER trigger can cascade; that is, perform an action that initiates another trigger, which initiates another trigger, and so on. This option is allowable only when CONTAINMENT has been set to PARTIAL. If CONTAINMENT is set to NONE, errors occur.

TRANSFORM_NOISE_WORDS

Applies to: SQL Server (Starting with SQL Server 2012 (11.x))

Used to suppress an error message if noise words, or stopwords, cause a Boolean operation on a full-text query to fail. This option is allowable only when CONTAINMENT has been set to PARTIAL. If CONTAINMENT is set to NONE, errors occur.

TWO_DIGIT_YEAR_CUTOFF

Applies to: SQL Server (Starting with SQL Server 2012 (11.x))

Specifies an integer from 1753 to 9999 that represents the cutoff year for interpreting two-digit years as four-digit years. This option is allowable only when CONTAINMENT has been set to PARTIAL. If CONTAINMENT is set to NONE, errors occur.

<FILESTREAM_option> ::=

Applies to: SQL Server (Starting with SQL Server 2012 (11.x))

Controls the settings for FileTables.

NON_TRANSACTED_ACCESS = { OFF | READ_ONLY | FULL } DIRECTORY_NAME = <directory_name>

A Windows-compatible directory name. This name should be unique among all the database-level directory names in the SQL Server instance. Uniqueness comparison is case-insensitive, regardless of collation settings. This option must be set before creating a FileTable in this database.

<HADR_options> ::=

Applies to: SQL Server

See ALTER DATABASE SET HADR.

<mixed_page_allocation_option> ::=

Applies to: SQL Server (Starting with SQL Server 2016 (13.x))

Controls whether the database can create initial pages using a mixed extent for the first eight pages of a table or index.

MIXED_PAGE_ALLOCATION { OFF | ON }

This setting is always ON for all system databases except tempdb where it is always OFF. The setting can't be changed for system databases.

<PARAMETERIZATION_option> ::=

Controls the parameterization option. For more information on parameterization, see the Query Processing Architecture Guide.

PARAMETERIZATION { SIMPLE | FORCED }

The current setting of this option can be determined by examining the is_parameterization_forced column in the sys.databases catalog view.

<query_store_options> ::=

Applies to: SQL Server (Starting with SQL Server 2016 (13.x))

ON | OFF [ ( FORCED ) ] | CLEAR [ ALL ]

Controls whether the Query Store is enabled in this database, and also controls removing the contents of the Query Store. For more information, see Query Store Usage Scenarios.

OPERATION_MODE { READ_ONLY | READ_WRITE }

Describes the operation mode of the Query Store.

READ_WRITE

The Query Store collects and persists query plan and runtime execution statistics information.

READ_ONLY

Information can be read from the Query Store, but new information isn't added. If the maximum issued space of the Query Store has been exhausted, the Query Store changes its operation mode to READ_ONLY.

CLEANUP_POLICY

Describes the data retention policy of the Query Store. STALE_QUERY_THRESHOLD_DAYS determines the number of days for which the information for a query is kept in the Query Store. STALE_QUERY_THRESHOLD_DAYS is type bigint. The default value is 30.

DATA_FLUSH_INTERVAL_SECONDS

Determines the frequency at which data written to the Query Store is persisted to disk. To optimize for performance, data collected by the Query Store is asynchronously written to the disk. The frequency at which this asynchronous transfer occurs is configured by using the DATA_FLUSH_INTERVAL_SECONDS argument. DATA_FLUSH_INTERVAL_SECONDS is type bigint. The default value is 900 (15 min).

MAX_STORAGE_SIZE_MB

Determines the space issued to the Query Store. MAX_STORAGE_SIZE_MB is type bigint. The default value is 100 MB for SQL Server (SQL Server 2016 (13.x) through SQL Server 2017 (14.x)). Starting with SQL Server 2019 (15.x), the default value is 1000 MB.

MAX_STORAGE_SIZE_MB limit isn't strictly enforced. Storage size is checked only when Query Store writes data to disk. This interval is set by the DATA_FLUSH_INTERVAL_SECONDS option or the Management Studio Query Store dialog option Data Flush Interval. The interval default value is 900 seconds (or 15 minutes).

If the Query Store has breached the MAX_STORAGE_SIZE_MB limit between storage size checks, it transitions to read-only mode. If SIZE_BASED_CLEANUP_MODE is enabled, the cleanup mechanism to enforce the MAX_STORAGE_SIZE_MB limit is also triggered.

Once enough space has been cleared, the Query Store mode automatically switches back to read-write.

Important

If you think that your workload capture needs more than 10 GB of disk space, you should probably rethink and optimize your workload to reuse query plans (for example using forced parameterization, or adjust the Query Store configurations. Starting with SQL Server 2019 (15.x) and in Azure SQL Database, you can set QUERY_CAPTURE_MODE to CUSTOM for additional control over the query capture policy.

INTERVAL_LENGTH_MINUTES

Determines the time interval at which runtime execution statistics data is aggregated into the Query Store. To optimize for space usage, the runtime execution statistics in the runtime stats store are aggregated over a fixed time window. This fixed time window is configured by using the INTERVAL_LENGTH_MINUTES argument. INTERVAL_LENGTH_MINUTES is type bigint. The default value is 60.

SIZE_BASED_CLEANUP_MODE { AUTO | OFF }

Controls whether cleanup automatically activates when the total amount of data gets close to maximum size.

SIZE_BASED_CLEANUP_MODE is type nvarchar.

QUERY_CAPTURE_MODE { ALL | AUTO | CUSTOM | NONE }

Designates the currently active query capture mode. Each mode defines specific query capture policies. QUERY_CAPTURE_MODE is type nvarchar.

Note

Cursors, queries inside Stored Procedures, and Natively compiled queries are always captured when the query capture mode is set to ALL, AUTO, or CUSTOM.

MAX_PLANS_PER_QUERY

Defines the maximum number of plans maintained for each query. MAX_PLANS_PER_QUERY is type int. The default value is 200.

WAIT_STATS_CAPTURE_MODE { ON | OFF }

Applies to: SQL Server (Starting with SQL Server 2017 (14.x)))

Controls whether wait statistics are captured per query.

<query_capture_policy_option_list> :: =

Applies to: SQL Server (Starting with SQL Server 2019 (15.x))

Controls the Query Store capture policy options. Except for STALE_CAPTURE_POLICY_THRESHOLD, these options define the OR conditions that need to happen for queries to be captured in the defined Stale Capture Policy Threshold value.

Starting with SQL Server 2019 (15.x), the QUERY_CAPTURE_MODE = AUTO setting captures Query Store details when any of the following thresholds are hit:

For example:

EXECUTION_COUNT = 30,
TOTAL_COMPILE_CPU_TIME_MS = 1000,
TOTAL_EXECUTION_CPU_TIME_MS = 100

You can customize these options with QUERY_CAPTURE_MODE = CUSTOM:

<recovery_option> ::=

Applies to: SQL Server

Controls database recovery options and disk I/O error checking.

The default recovery model is determined by the recovery model of the model system database. For more information about selecting the appropriate recovery model, see Recovery models.

You can determine this option's status by examining the recovery_model and recovery_model_desc columns in the sys.databases catalog view. You can also determine the status by examining the Recovery property of the DATABASEPROPERTYEX function.

TORN_PAGE_DETECTION { ON | OFF }

Important

The syntax structure TORN_PAGE_DETECTION ON | OFF will be removed in a future version of SQL Server. Avoid using this syntax structure in new development work, and plan to modify applications that currently use the syntax structure. Use the PAGE_VERIFY option instead.

PAGE_VERIFY { CHECKSUM | TORN_PAGE_DETECTION | NONE }

Discovers damaged database pages caused by disk I/O path errors. Disk I/O path errors can be the cause of database corruption problems. These errors are most often caused by power failures or disk hardware failures that occur at the time the page is written to disk.

Consider the following important points when you use the PAGE_VERIFY option:

When a torn page or checksum failure is detected, you can recover by restoring the data or potentially rebuilding the index if the failure is limited only to index pages. If you encounter a checksum failure, to determine the type of database page or pages affected, run DBCC CHECKDB. For more information about restore options, see RESTORE Arguments. Although restoring the data resolves the data corruption problem, the root cause (for example, disk hardware failure) should be diagnosed and corrected as soon as possible to prevent continuing errors.

SQL Server retries any read that fails with a checksum, torn page, or other I/O error four times. If the read is successful in any one of the retry attempts, a message is written to the error log. The command that triggered the read continues. The command fails with error message 824 if the retry attempts fail.

For more information about error messages 823, 824 and 825, see:

The current setting of this option can be determined by examining the page_verify_option column in the sys.databases catalog view or the IsTornPageDetectionEnabled property of the DATABASEPROPERTYEX function.

<remote_data_archive_option> ::=

Applies to: SQL Server (Starting with SQL Server 2016 (13.x))

Enables or disables Stretch Database for the database. For more info, see Stretch Database.

Important

Stretch Database is deprecated in SQL Server 2022 (16.x) and Azure SQL Database. This feature will be removed in a future version of the Database Engine. Avoid using this feature in new development work, and plan to modify applications that currently use this feature.

REMOTE_DATA_ARCHIVE = { ON ( SERVER = <server_name>, { CREDENTIAL = <db_scoped_credential_name> | FEDERATED_SERVICE_ACCOUNT = ON | OFF } ) | OFF PERSISTENT_LOG_BUFFER

Applies to: SQL Server 2017 (14.x) and later.

When this option is specified, the transaction log buffer is created on a volume that is located on a disk device backed by Storage Class Memory (NVDIMM-N nonvolatile storage), also known as a persistent log buffer. For more information, see Transaction Commit latency acceleration using Storage Class Memory and Add persistent log buffer to a database.

<service_broker_option> ::=

Applies to: SQL Server

Controls the following Service Broker options: enables or disables message delivery, sets a new Service Broker identifier, or sets conversation priorities to ON or OFF.

ENABLE_BROKER

Specifies that Service Broker is enabled for the specified database. Message delivery is started, and the is_broker_enabled flag is set to true in the sys.databases catalog view. The database keeps the existing Service Broker identifier. Service broker can't be enabled while the database is the principal in a database mirroring configuration.

Note

ENABLE_BROKER requires an exclusive database lock. If other sessions have locked resources in the database, ENABLE_BROKER waits until the other sessions release their locks. To enable Service Broker in a user database, ensure that no other sessions are using the database before you run the ALTER DATABASE SET ENABLE_BROKER statement, such as by putting the database in single user mode. To enable Service Broker in the msdb database, first stop SQL Server Agent so that Service Broker can obtain the necessary lock.

DISABLE_BROKER

Specifies that Service Broker is disabled for the specified database. Message delivery is stopped, and the is_broker_enabled flag is set to false in the sys.databases catalog view. The database keeps the existing Service Broker identifier.

NEW_BROKER

Specifies that the database should receive a new broker identifier. The database acts as a new service broker. As such, all existing conversations in the database are immediately removed without producing end dialog messages. Any route that references the old Service Broker identifier must be re-created with the new identifier.

ERROR_BROKER_CONVERSATIONS

Specifies that Service Broker message delivery is enabled. This setting preserves the existing Service Broker identifier for the database. Service Broker ends all conversations in the database with an error. This setting enables applications to run regular cleanup for existing conversations.

HONOR_BROKER_PRIORITY { ON | OFF }

Changes to the HONOR_BROKER_PRIORITY option take effect immediately for new dialogs or dialogs that have no messages waiting to be sent. Dialogs with messages to be sent when ALTER DATABASE is run don't pick up the new setting until some of the messages for the dialog are sent. The amount of time before all dialogs start using the new setting can vary considerably.

The current setting of this property is reported in the is_broker_priority_honored column in the sys.databases catalog view.

<snapshot_option> ::=

Calculates the transaction isolation level.

ALLOW_SNAPSHOT_ISOLATION { ON | OFF }

When you set ALLOW_SNAPSHOT_ISOLATION to a new state (from ON to OFF, or from OFF to ON), ALTER DATABASE doesn't return control to the caller until all existing transactions in the database are committed. If the database is already in the state specified in the ALTER DATABASE statement, control is returned to the caller immediately. If the ALTER DATABASE statement doesn't return quickly, use sys.dm_tran_active_snapshot_database_transactions to determine whether there are long-running transactions. If the ALTER DATABASE statement is canceled, the database remains in the state it was in when ALTER DATABASE was started. The sys.databases catalog view indicates the state of snapshot-isolation transactions in the database. If snapshot_isolation_state_desc = IN_TRANSITION_TO_ON, the command ALTER DATABASE ... ALLOW_SNAPSHOT_ISOLATION OFF pauses six seconds and retries the operation.

You can't change the state of ALLOW_SNAPSHOT_ISOLATION if the database is OFFLINE.

If you set ALLOW_SNAPSHOT_ISOLATION in a READ_ONLY database, the setting is kept if the database is later set to READ_WRITE.

You can change the ALLOW_SNAPSHOT_ISOLATION settings for the master, model, msdb, and tempdb databases. The setting is kept every time the instance of the Database Engine is stopped and restarted if you change the setting for tempdb. If you change the setting for model, that setting becomes the default for any new databases that are created, except for tempdb.

The option is ON by default for the master and msdb databases.

The current setting of this option can be determined by examining the snapshot_isolation_state column in the sys.databases catalog view.

READ_COMMITTED_SNAPSHOT { ON | OFF }

To set READ_COMMITTED_SNAPSHOT ON or OFF, there must be no active connections to the database except for the connection running the ALTER DATABASE command. However, the database doesn't have to be in single-user mode. You can't change the state of this option when the database is OFFLINE.

If you set READ_COMMITTED_SNAPSHOT in a READ_ONLY database, the setting is kept when the database is later set to READ_WRITE.

READ_COMMITTED_SNAPSHOT can't be turned ON for the master, tempdb, or msdb system databases. If you change the setting for model, that setting becomes the default for any new databases created, except for tempdb.

The current setting of this option can be determined by examining the is_read_committed_snapshot_on column in the sys.databases catalog view.

Warning

When a table is created with DURABILITY = SCHEMA_ONLY, and READ_COMMITTED_SNAPSHOT is subsequently changed using ALTER DATABASE, data in the table is lost.

MEMORY_OPTIMIZED_ELEVATE_TO_SNAPSHOT { ON | OFF }

Applies to: SQL Server (Starting with SQL Server 2014 (12.x))

You can't change the state of MEMORY_OPTIMIZED_ELEVATE_TO_SNAPSHOT if the database is OFFLINE.

The default option is OFF.

The current setting of this option can be determined by examining the is_memory_optimized_elevate_to_snapshot_on column in the sys.databases catalog view.

<sql_option> ::=

Controls the ANSI compliance options at the database level.

ANSI_NULL_DEFAULT { ON | OFF }

Determines the default value, NULL or NOT NULL, of a column or CLR user-defined type for which the nullability isn't explicitly defined in CREATE TABLE or ALTER TABLE statements. Columns that are defined with constraints follow constraint rules whatever this setting might be.

Connection-level settings that are set by using the SET statement override the default database-level setting for ANSI_NULL_DEFAULT. ODBC and OLE DB clients issue a connection-level SET statement setting ANSI_NULL_DEFAULT to ON for the session, by default. The clients run the statement when you connect to an instance of SQL Server. For more information, see SET ANSI_NULL_DFLT_ON.

For ANSI compatibility, setting the database option ANSI_NULL_DEFAULT to ON changes the database default to NULL.

You can determine this option's status by examining the is_ansi_null_default_on column in the sys.databases catalog view. You can also determine the status by examining the IsAnsiNullDefault property of the DATABASEPROPERTYEX function.

ANSI_NULLS { ON | OFF }

Important

In a future version of SQL Server, ANSI_NULLS will always be ON and any applications that explicitly set the option to OFF will produce an error. Avoid using this feature in new development work, and plan to modify applications that currently use this feature.

Connection-level settings that are set by using the SET statement override the default database setting for ANSI_NULLS. ODBC and OLE DB clients issue a connection-level SET statement setting ANSI_NULLS to ON for the session, by default. The clients run the statement when you connect to an instance of SQL Server. For more information, see SET ANSI_NULLS.

Important

SET ANSI_NULLS also must be set to ON when you create or make changes to indexes on computed columns or indexed views.

You can determine this option's status by examining the is_ansi_nulls_on column in the sys.databases catalog view. You can also determine the status by examining the IsAnsiNullsEnabled property of the DATABASEPROPERTYEX function.

ANSI_PADDING { ON | OFF }

Important

In a future version of SQL Server, ANSI_PADDING will always be ON and any applications that explicitly set the option to OFF will produce an error. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. We recommend that you always set ANSI_PADDING to ON. ANSI_PADDING must be ON when you create or manipulate indexes on computed columns or indexed views.

char(n) and binary(n) columns that allow for nulls are padded to the column length when ANSI_PADDING is set to ON. Trailing blanks and zeros are trimmed when ANSI_PADDING is OFF. char(n) and binary(n) columns that don't allow nulls are always padded to the length of the column.

Connection-level settings that are set by using the SET statement override the default database-level setting for ANSI_PADDING. ODBC and OLE DB clients issue a connection-level SET statement setting ANSI_PADDING to ON for the session, by default. The clients run the statement when you connect to an instance of SQL Server. For more information, see SET ANSI_PADDING.

You can determine this option's status by examining the is_ansi_padding_on column in the sys.databases catalog view. You can also determine the status by examining the IsAnsiPaddingEnabled property of the DATABASEPROPERTYEX function.

ANSI_WARNINGS { ON | OFF }

Important

SET ANSI_WARNINGS must be set to ON when you create or make changes to indexes on computed columns or indexed views.

Connection-level settings that are set by using the SET statement override the default database setting for ANSI_WARNINGS. ODBC and OLE DB clients issue a connection-level SET statement setting ANSI_WARNINGS to ON for the session, by default. The clients run the statement when you connect to an instance of SQL Server. For more information, see SET ANSI_WARNINGS.

You can determine this option's status by examining the is_ansi_warnings_on column in the sys.databases catalog view. You can also determine the status by examining the IsAnsiWarningsEnabled property of the DATABASEPROPERTYEX function.

ARITHABORT { ON | OFF }

Important

SET ARITHABORT must be set to ON when you create or make changes to indexes on computed columns or indexed views.

You can determine this option's status by examining the is_arithabort_on column in the sys.databases catalog view. You can also determine the status by examining the IsArithmeticAbortEnabled property of the DATABASEPROPERTYEX function.

COMPATIBILITY_LEVEL = { 160 | 150 | 140 | 130 | 120 | 110 | 100 }

For more information, see ALTER DATABASE compatibility level.

CONCAT_NULL_YIELDS_NULL { ON | OFF }

Important

CONCAT_NULL_YIELDS_NULL must be set to ON when you create or make changes to indexes on computed columns or indexed views.

In upcoming versions of SQL Server, CONCAT_NULL_YIELDS_NULL will always be ON, and any applications that explicitly set the option to OFF will trigger an error. Avoid using this feature in new development work, and plan to modify applications that currently use this feature.

Connection-level settings that are set by using the SET statement override the default database setting for CONCAT_NULL_YIELDS_NULL. By default, ODBC and OLE DB clients issue a connection-level SET statement setting CONCAT_NULL_YIELDS_NULL to ON for the session when connecting to an instance of SQL Server. For more information, see SET CONCAT_NULL_YIELDS_NULL.

You can determine this option's status by examining the is_concat_null_yields_null_on column in the sys.databases catalog view. You can also determine the status by examining the IsNullConcat property of the DATABASEPROPERTYEX function.

NUMERIC_ROUNDABORT { ON | OFF }

You can determine the status of this option in the is_numeric_roundabort_on column in the sys.databases catalog view. You can also determine the status by examining the IsNumericRoundAbortEnabled property of the DATABASEPROPERTYEX function.

QUOTED_IDENTIFIER { ON | OFF }

SQL Server also allows for identifiers to be delimited by square brackets ([ and ]). Bracketed identifiers can always be used, whatever the QUOTED_IDENTIFIER setting is. For more information, see Database identifiers.

When a table is created, the QUOTED IDENTIFIER option is always stored as ON in the metadata of the table. The option is stored even if the option is set to OFF when the table is created.

Connection-level settings that are set by using the SET statement override the default database setting for QUOTED_IDENTIFIER. ODBC and OLE DB clients issue a connection-level SET statement setting QUOTED_IDENTIFIER to ON, by default. The clients run the statement when you connect to an instance of SQL Server. For more information, see SET QUOTED_IDENTIFIER.

You can determine this option's status by examining the is_quoted_identifier_on column in the sys.databases catalog view. You can also determine the status by examining the IsQuotedIdentifiersEnabled property of the DATABASEPROPERTYEX function.

RECURSIVE_TRIGGERS { ON | OFF }

Note

Only direct recursion is prevented when RECURSIVE_TRIGGERS is set to OFF. To disable indirect recursion, you must also set the nested triggers server option to 0.

You can determine this option's status by examining the is_recursive_triggers_on column in the sys.databases catalog view or the IsRecursiveTriggersEnabled property of the DATABASEPROPERTYEX function.

<suspend_for_snapshot_backup> ::=

Applies to: SQL Server (Starting with SQL Server 2022 (16.x))

Suspends databases for snapshot backup. Can define a group of one or more databases. Can designate copy only mode.

SET SUSPEND_FOR_SNAPSHOT_BACKUP = { ON | OFF }

Suspends, or un-suspends databases. Default OFF.

MODE = COPY_ONLY

Optional. Uses COPY_ONLY mode.

<target_recovery_time_option> ::=

Applies to: SQL Server (Starting with SQL Server 2012 (11.x))

Specifies the frequency of indirect checkpoints on a per-database basis. Starting with SQL Server 2016 (13.x) the default value for new databases is 1 minute, which indicates the database uses indirect checkpoints. For older versions the default is 0, which indicates that the database uses automatic checkpoints, whose frequency depends on the recovery interval setting of the server instance. Microsoft recommends 1 minute for most systems.

TARGET_RECOVERY_TIME = target_recovery_time { SECONDS | MINUTES }

For more information about indirect checkpoints, see Database checkpoints.

OPTIMIZED_LOCKING { ON | OFF }

Applies to: SQL Server (Starting with SQL Server 2025 (17.x) Preview)

Enables optimized locking. Optimized locking is set to OFF by default.

To set OPTIMIZED_LOCKING ON or OFF, there must be no active connections to the database except for the connection running the ALTER DATABASE command. However, the database doesn't have to be in single-user mode. You can't change the state of this option unless the database is ONLINE.

WITH <termination> ::=

Specifies when to roll back incomplete transactions when the database is transitioned from one state to another. If the termination clause is omitted, the ALTER DATABASE statement waits indefinitely if there's any lock on the database. Only one termination clause can be specified, and it follows the SET clauses.

Note

Not all database options use the WITH <termination> clause. For more information, see the table under Setting options of the "Remarks" section of this article.

Set options

To retrieve current settings for database options, use the sys.databases catalog view or DATABASEPROPERTYEX

After you set a database option, the new setting takes effect immediately.

You can change the default values for any one of the database options for all newly created databases. To do so, change the appropriate database option in the model database.

Not all database options use the WITH <termination> clause or can be specified in combination with other options. The following table lists these options and their option and termination status.

Options category Can be specified with other options Can use the WITH <termination> clause <db_state_option> Yes Yes <db_user_access_option> Yes Yes <db_update_option> Yes Yes <delayed_durability_option> Yes Yes <external_access_option> Yes No <cursor_option> Yes No <auto_option> Yes No <sql_option> Yes No <recovery_option> Yes No <target_recovery_time_option> No Yes <database_mirroring_option> No No ALLOW_SNAPSHOT_ISOLATION No No READ_COMMITTED_SNAPSHOT No Yes MEMORY_OPTIMIZED_ELEVATE_TO_SNAPSHOT Yes Yes <service_broker_option> Yes No DATE_CORRELATION_OPTIMIZATION Yes Yes <parameterization_option> Yes Yes <change_tracking_option> Yes Yes <db_encryption_option> Yes No <accelerated_database_recovery> No Yes <optimized_locking> No Yes

The plan cache for the instance of SQL Server is cleared by setting one of the following options:

OFFLINE

ONLINE

MODIFY_NAME

COLLATE

READ_ONLY

READ_WRITE

MODIFY FILEGROUP DEFAULT

MODIFY FILEGROUP READ_WRITE

MODIFY FILEGROUP READ_ONLY

The plan cache is also flushed in the following scenarios.

Clearing the plan cache causes a recompilation of all subsequent execution plans and can cause a sudden, temporary decrease in query performance. For each cleared cache store in the plan cache, the SQL Server error log contains the following informational message: SQL Server has encountered %d occurrence(s) of cachestore flush for the '%s' cachestore (part of plan cache) due to some database maintenance or reconfigure operations. This message is logged every five minutes as long as the cache is flushed within that time interval.

Examples A. Set options on a database

The following example sets the recovery model and data page verification options for the AdventureWorks2022 sample database.

USE master;
GO
ALTER DATABASE [database_name]
SET RECOVERY FULL PAGE_VERIFY CHECKSUM;
GO
B. Set the database to READ_ONLY

Changing the state of a database or file group to READ_ONLY or READ_WRITE requires exclusive access to the database. The following example sets the database to SINGLE_USER mode to obtain exclusive access. The example then sets the state of the AdventureWorks2022 database to READ_ONLY and returns access to the database to all users.

Note

This example uses the termination option WITH ROLLBACK IMMEDIATE in the first ALTER DATABASE statement. All incomplete transactions are rolled back, and any other connections to the AdventureWorks2022 database are immediately disconnected.

USE master;
GO
ALTER DATABASE [database_name]
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;
GO
ALTER DATABASE [database_name]
SET READ_ONLY
GO
ALTER DATABASE [database_name]
SET MULTI_USER;
GO
C. Enable snapshot isolation on a database

The following example enables the snapshot isolation framework option for the AdventureWorks2022 database.

USE [database_name];
USE master;
GO
ALTER DATABASE [database_name]
SET ALLOW_SNAPSHOT_ISOLATION ON;
GO
-- Check the state of the snapshot_isolation_framework
-- in the database.
SELECT name, snapshot_isolation_state,
    snapshot_isolation_state_desc AS description
FROM sys.databases
WHERE name = N'[database_name]';
GO

The result set shows that the snapshot isolation framework is enabled.

name snapshot_isolation_state description [database_name] 1 ON D. Enable, modify, or disable change tracking

The following example enables change tracking for the AdventureWorks2022 database and sets the retention period to 2 days.

ALTER DATABASE [database_name]
SET CHANGE_TRACKING = ON
(AUTO_CLEANUP = ON, CHANGE_RETENTION = 2 DAYS);

The following example shows how to change the retention period to 3 days.

ALTER DATABASE [database_name]
SET CHANGE_TRACKING (CHANGE_RETENTION = 3 DAYS);

The following example shows how to disable change tracking for the AdventureWorks2022 database.

ALTER DATABASE [database_name]
SET CHANGE_TRACKING = OFF;
E. Enable the Query Store

Applies to: SQL Server (Starting with SQL Server 2016 (13.x))

The following example enables the Query Store and configures its parameters.

ALTER DATABASE [database_name]
SET QUERY_STORE = ON
    (
      OPERATION_MODE = READ_WRITE,
      CLEANUP_POLICY = ( STALE_QUERY_THRESHOLD_DAYS = 90 ),
      DATA_FLUSH_INTERVAL_SECONDS = 900,
      QUERY_CAPTURE_MODE = AUTO,
      MAX_STORAGE_SIZE_MB = 1024,
      INTERVAL_LENGTH_MINUTES = 60
    );
F. Enable the Query Store with wait statistics

Applies to: SQL Server (Starting with SQL Server 2017 (14.x))

The following example enables the Query Store and configures its parameters.

ALTER DATABASE [database_name]
SET QUERY_STORE = ON
    (
      OPERATION_MODE = READ_WRITE,
      CLEANUP_POLICY = ( STALE_QUERY_THRESHOLD_DAYS = 90 ),
      DATA_FLUSH_INTERVAL_SECONDS = 900,
      MAX_STORAGE_SIZE_MB = 1024,
      INTERVAL_LENGTH_MINUTES = 60,
      SIZE_BASED_CLEANUP_MODE = AUTO,
      MAX_PLANS_PER_QUERY = 200,
      WAIT_STATS_CAPTURE_MODE = ON,
    );
G. Enable the Query Store with custom capture policy options

Applies to: SQL Server (Starting with SQL Server 2019 (15.x))

The following example enables the Query Store and configures its parameters.

ALTER DATABASE [database_name]
SET QUERY_STORE = ON
    (
      OPERATION_MODE = READ_WRITE,
      CLEANUP_POLICY = ( STALE_QUERY_THRESHOLD_DAYS = 90 ),
      DATA_FLUSH_INTERVAL_SECONDS = 900,
      MAX_STORAGE_SIZE_MB = 1024,
      INTERVAL_LENGTH_MINUTES = 60,
      SIZE_BASED_CLEANUP_MODE = AUTO,
      MAX_PLANS_PER_QUERY = 200,
      WAIT_STATS_CAPTURE_MODE = ON,
      QUERY_CAPTURE_MODE = CUSTOM,
      QUERY_CAPTURE_POLICY = (
        STALE_CAPTURE_POLICY_THRESHOLD = 24 HOURS,
        EXECUTION_COUNT = 30,
        TOTAL_COMPILE_CPU_TIME_MS = 1000,
        TOTAL_EXECUTION_CPU_TIME_MS = 100
      )
    );

SQL Server

* SQL Database *  

SQL Managed Instance

Azure Synapse
Analytics

Microsoft Fabric

SQL Database

Compatibility levels are SET options but are described in ALTER DATABASE compatibility level.

Note

Many database set options can be configured for the current session by using SET Statements and are often configured by applications when they connect. Session-level set options override the ALTER DATABASE SET values. The database options described in the following sections are values that can be set for sessions that don't explicitly provide other set option values.

Syntax
ALTER DATABASE { database_name | Current }
SET
{
    <option_spec> [ ,...n ] [ WITH <termination> ]
}
;

<option_spec> ::=
{
    <auto_option>
  | <automatic_tuning_option>
  | <change_tracking_option>
  | <cursor_option>
  | <db_encryption_option>
  | <db_update_option>
  | <db_user_access_option>
  | <delayed_durability_option>
  | <parameterization_option>
  | <query_store_options>
  | <snapshot_option>
  | <sql_option>
  | <target_recovery_time_option>
  | <termination>
  | <temporal_history_retention>
}
;

<auto_option> ::=
{
    AUTO_CREATE_STATISTICS { OFF | ON [ ( INCREMENTAL = { ON | OFF } ) ] }
  | AUTO_SHRINK { ON | OFF }
  | AUTO_UPDATE_STATISTICS { ON | OFF }
  | AUTO_UPDATE_STATISTICS_ASYNC { ON | OFF }
}

<automatic_tuning_option> ::=
{
    AUTOMATIC_TUNING = { AUTO | INHERIT | CUSTOM }
  | AUTOMATIC_TUNING ( CREATE_INDEX = { DEFAULT | ON | OFF } )
  | AUTOMATIC_TUNING ( DROP_INDEX = { DEFAULT | ON | OFF } )
  | AUTOMATIC_TUNING ( FORCE_LAST_GOOD_PLAN = { DEFAULT | ON | OFF } )
}

<change_tracking_option> ::=
{
    CHANGE_TRACKING
    {
        = OFF
      | = ON [ ( <change_tracking_option_list > [,...n] ) ]
      | ( <change_tracking_option_list> [,...n] )
    }
}

<change_tracking_option_list> ::=
   {
       AUTO_CLEANUP = { ON | OFF }
     | CHANGE_RETENTION = retention_period { DAYS | HOURS | MINUTES }
   }

<cursor_option> ::=
{
    CURSOR_CLOSE_ON_COMMIT { ON | OFF }
}

<db_encryption_option> ::=
  ENCRYPTION { ON | OFF }

<db_update_option> ::=
  { READ_ONLY | READ_WRITE }

<db_user_access_option> ::=
  { RESTRICTED_USER | MULTI_USER }

<delayed_durability_option> ::= DELAYED_DURABILITY = { DISABLED | ALLOWED | FORCED }

<parameterization_option> ::=
  PARAMETERIZATION { SIMPLE | FORCED }

<query_store_options> ::=
{
  QUERY_STORE
  {
      = OFF
    | = ON [ ( <query_store_option_list> [,... n] ) ]
    | ( < query_store_option_list> [,... n] )
    | CLEAR [ ALL ]
  }
}

<query_store_option_list> ::=
{
  OPERATION_MODE = { READ_WRITE | READ_ONLY }
  | CLEANUP_POLICY = ( STALE_QUERY_THRESHOLD_DAYS = number )
  | DATA_FLUSH_INTERVAL_SECONDS = number
  | MAX_STORAGE_SIZE_MB = number
  | INTERVAL_LENGTH_MINUTES = number
  | SIZE_BASED_CLEANUP_MODE = { AUTO | OFF }
  | QUERY_CAPTURE_MODE = { ALL | AUTO | CUSTOM | NONE }
  | MAX_PLANS_PER_QUERY = number
  | WAIT_STATS_CAPTURE_MODE = { ON | OFF }
  | QUERY_CAPTURE_POLICY = ( <query_capture_policy_option_list> [,...n] )
}

<query_capture_policy_option_list> :: =
{
    STALE_CAPTURE_POLICY_THRESHOLD = number { DAYS | HOURS }
    | EXECUTION_COUNT = number
    | TOTAL_COMPILE_CPU_TIME_MS = number
    | TOTAL_EXECUTION_CPU_TIME_MS = number
}

<snapshot_option> ::=
{
    ALLOW_SNAPSHOT_ISOLATION { ON | OFF }
  | READ_COMMITTED_SNAPSHOT { ON | OFF }
  | MEMORY_OPTIMIZED_ELEVATE_TO_SNAPSHOT { ON | OFF }
}
<sql_option> ::=
{
    ANSI_NULL_DEFAULT { ON | OFF }
  | ANSI_NULLS { ON | OFF }
  | ANSI_PADDING { ON | OFF }
  | ANSI_WARNINGS { ON | OFF }
  | ARITHABORT { ON | OFF }
  | COMPATIBILITY_LEVEL = { 160 | 150 | 140 | 130 | 120 | 110 | 100 }
  | CONCAT_NULL_YIELDS_NULL { ON | OFF }
  | NUMERIC_ROUNDABORT { ON | OFF }
  | QUOTED_IDENTIFIER { ON | OFF }
  | RECURSIVE_TRIGGERS { ON | OFF }
}

<termination>::=
{
    ROLLBACK AFTER integer [ SECONDS ]
  | ROLLBACK IMMEDIATE
  | NO_WAIT
}

<temporal_history_retention>::=TEMPORAL_HISTORY_RETENTION { ON | OFF }
Arguments database_name

The name of the database to be modified.

<auto_option> ::=

Controls automatic options.

AUTO_CREATE_STATISTICS { ON | OFF }

You can determine this option's status by examining the is_auto_create_stats_on column in the sys.databases catalog view. You can also determine the status by examining the IsAutoCreateStatistics property of the DATABASEPROPERTYEX function.

For more information, see the "Statistics options" section in Statistics.

INCREMENTAL = ON | OFF

Set AUTO_CREATE_STATISTICS to ON, and set INCREMENTAL to ON. This setting creates automatically created stats as incremental whenever incremental stats are supported. The default value is OFF. For more information, see CREATE STATISTICS.

AUTO_SHRINK { ON | OFF }

Both data file and log files can be automatically shrunk. AUTO_SHRINK reduces the size of the transaction log only if you set the database to SIMPLE recovery model or if you back up the log. When set to OFF, the database files aren't automatically shrunk during periodic checks for unused space.

The AUTO_SHRINK option causes files to be shrunk when more than 25 percent of the file contains unused space. The option causes the file to shrink to one of two sizes. It shrinks to whichever is larger:

You can't shrink a read-only database.

You can determine this option's status by examining the is_auto_shrink_on column in the sys.databases catalog view. You can also determine the status by examining the IsAutoShrink property of the DATABASEPROPERTYEX function.

Note

The AUTO_SHRINK option isn't available in a contained database.

AUTO_UPDATE_STATISTICS { ON | OFF } AUTO_UPDATE_STATISTICS_ASYNC { ON | OFF }

You can determine this option's status by examining the is_auto_update_stats_async_on column in the sys.databases catalog view.

For more information that describes when to use synchronous or asynchronous statistics updates, see the "Statistics options" section in Statistics.

<automatic_tuning_option> ::=

Controls automatic options for Automatic tuning. You can view the options for the following settings in the Azure portal or via T-SQL in the view sys.database_automatic_tuning_options.

AUTOMATIC_TUNING = { AUTO | INHERIT | CUSTOM } CREATE_INDEX = { DEFAULT | ON | OFF }

Enables or disables automatic index management CREATE_INDEX option of Automatic tuning. You can view the status for this option in the Azure portal or via T-SQL in the view sys.database_automatic_tuning_options.

DROP_INDEX = { DEFAULT | ON | OFF }

Enables or disables automatic index management DROP_INDEX option of Automatic tuning. You can view the status for this option in the Azure portal or via T-SQL in the view sys.database_automatic_tuning_options.

FORCE_LAST_GOOD_PLAN = { DEFAULT | ON | OFF }

Enables or disables automatic plan correction FORCE_LAST_GOOD_PLAN option of Automatic tuning. You can view the status for this option in the Azure portal or via T-SQL in the view sys.database_automatic_tuning_options.

<change_tracking_option> ::=

Controls change tracking options. You can enable change tracking, set options, change options, and disable change tracking. For examples, see the Examples section later in this article.

<cursor_option> ::=

Controls cursor options.

CURSOR_CLOSE_ON_COMMIT { ON | OFF }

Connection-level settings that are set by using the SET statement override the default database setting for CURSOR_CLOSE_ON_COMMIT. ODBC and OLE DB clients issue a connection-level SET statement setting CURSOR_CLOSE_ON_COMMIT to OFF for the session, by default. The clients run the statement when you connect to an instance of SQL Server. For more information, see SET CURSOR_CLOSE_ON_COMMIT.

You can determine this option's status by examining the is_cursor_close_on_commit_on column in the sys.databases catalog view or the IsCloseCursorsOnCommitEnabled property of the DATABASEPROPERTYEX function. The cursor is implicitly deallocated only at disconnect. For more information, see DECLARE CURSOR.

<db_encryption_option> ::=

Controls the database encryption state.

ENCRYPTION { ON | OFF }

Sets the database to be encrypted (ON) or not encrypted (OFF). For more information about database encryption, see Transparent data encryption (TDE), and Transparent data encryption for Azure SQL Database, Azure SQL Managed Instance, and Azure Synapse Analytics.

When encryption is enabled at the database level, all file groups are encrypted. Any new file groups inherit the encrypted property. If any file groups in the database are set to READ ONLY, the database encryption operation fails.

You can see the encryption state of the database by using the sys.dm_database_encryption_keys dynamic management view.

<db_update_option> ::=

Controls whether updates are allowed on the database.

To change this state, you must have exclusive access to the database. For more information, see the SINGLE_USER clause.

Note

On Azure SQL Database federated databases, SET { READ_ONLY | READ_WRITE } is disabled.

<db_user_access_option> ::=

Controls user access to the database.

<delayed_durability_option> ::=

Controls whether transactions commit fully durable or delayed durable.

<PARAMETERIZATION_option> ::=

Controls the parameterization option.

PARAMETERIZATION { SIMPLE | FORCED }

The current setting of this option can be determined by examining the is_parameterization_forced column in the sys.databases catalog view.

<query_store_options> ::= OPERATION_MODE

Describes the operation mode of the Query Store. Valid values are READ_ONLY and READ_WRITE. In READ_WRITE mode, the Query Store collects and persists query plan and runtime execution statistics information. In READ_ONLY mode, information can be read from the Query Store, but new information isn't added. If the maximum allocated space of the Query Store has been exhausted, the Query Store changes its operation mode to READ_ONLY.

CLEANUP_POLICY

Describes the data retention policy of the Query Store. STALE_QUERY_THRESHOLD_DAYS determines the number of days for which the information for a query is kept in the Query Store. STALE_QUERY_THRESHOLD_DAYS is type bigint. The default value is 30. For SQL Database Basic edition, default is 7 days.

DATA_FLUSH_INTERVAL_SECONDS

Determines the frequency at which data written to the Query Store is persisted to disk. To optimize for performance, data collected by the Query Store is asynchronously written to the disk. The frequency at which this asynchronous transfer occurs is configured by using the DATA_FLUSH_INTERVAL_SECONDS argument. DATA_FLUSH_INTERVAL_SECONDS is type bigint. The default value is 900 (15 min).

MAX_STORAGE_SIZE_MB

Determines the space allocated to the Query Store. MAX_STORAGE_SIZE_MB is type bigint.

Note

In Azure SQL Database, the default MAX_STORAGE_SIZE_MB value differs by service tier, as follows: Premium, Business Critical, and Hyperscale: 1,024 MB; Standard and General Purpose: 100 MB; Basic: 10 MB The maximum allowed MAX_STORAGE_SIZE_MB value is 10,240 MB.

Note

MAX_STORAGE_SIZE_MB limit isn't strictly enforced. Storage size is checked only when Query Store writes data to disk. This interval is set by the DATA_FLUSH_INTERVAL_SECONDS option or the Management Studio Query Store dialog option Data Flush Interval. The interval default value is 900 seconds (or 15 minutes). If the Query Store has breached the MAX_STORAGE_SIZE_MB limit between storage size checks, it transitions to read-only mode. If SIZE_BASED_CLEANUP_MODE is enabled, the cleanup mechanism to enforce the MAX_STORAGE_SIZE_MB limit is also triggered. Once enough space has been cleared, the Query Store mode automatically switches back to read-write.

Important

If you think that your workload capture needs more than 10 GB of disk space, you should probably rethink and optimize your workload to reuse query plans (for example using forced parameterization, or adjust the Query Store configurations. Starting with SQL Server 2019 (15.x) and in Azure SQL Database, you can set QUERY_CAPTURE_MODE to CUSTOM for additional control over the query capture policy.

INTERVAL_LENGTH_MINUTES

Determines the time interval at which runtime execution statistics data is aggregated into the Query Store. To optimize for space usage, the runtime execution statistics in the runtime stats store are aggregated over a fixed time window. This fixed time window is configured by using the INTERVAL_LENGTH_MINUTES argument. INTERVAL_LENGTH_MINUTES is type bigint. The default value is 60.

SIZE_BASED_CLEANUP_MODE = { AUTO | OFF }

Controls whether cleanup is automatically activated when the total amount of data gets close to maximum size.

SIZE_BASED_CLEANUP_MODE is type nvarchar.

QUERY_CAPTURE_MODE { ALL | AUTO | CUSTOM | NONE }

Designates the currently active query capture mode. Each mode defines specific query capture policies.

Note

Cursors, queries inside Stored Procedures, and Natively compiled queries are always captured when the query capture mode is set to ALL, AUTO, or CUSTOM.

QUERY_CAPTURE_MODE is type nvarchar.

MAX_PLANS_PER_QUERY

Defines the maximum number of plans maintained for each query. MAX_PLANS_PER_QUERY is type int. The default value is 200.

WAIT_STATS_CAPTURE_MODE { ON | OFF }

Controls whether wait statistics are captured per query.

<query_capture_policy_option_list> :: =

Controls the Query Store capture policy options. Except for STALE_CAPTURE_POLICY_THRESHOLD, these options define the OR conditions that need to happen for queries to be captured in the defined Stale Capture Policy Threshold value.

STALE_CAPTURE_POLICY_THRESHOLD = integer { DAYS | HOURS }

Defines the evaluation interval period to determine if a query should be captured. The default is 1 day, and it can be set from 1 hour to seven days. number is type int.

EXECUTION_COUNT = integer

Defines the number of times a query is executed over the evaluation period. The default is 30, which means that for the default Stale Capture Policy Threshold, a query must execute at least 30 times in one day to be persisted in the Query Store. EXECUTION_COUNT is type int.

TOTAL_COMPILE_CPU_TIME_MS = integer

Defines total elapsed compile CPU time used by a query over the evaluation period. The default is 1000, which means that for the default Stale Capture Policy Threshold, a query must have a total of at least one second of CPU time spent during query compilation in one day to be persisted in the Query Store. TOTAL_COMPILE_CPU_TIME_MS is type int.

TOTAL_EXECUTION_CPU_TIME_MS = integer

Defines total elapsed execution CPU time used by a query over the evaluation period. The default is 100 which means that for the default Stale Capture Policy Threshold, a query must have a total of at least 100 ms of CPU time spent during execution in one day to be persisted in the Query Store. TOTAL_EXECUTION_CPU_TIME_MS is type int.

<snapshot_option> ::=

Determines the transaction isolation level.

ALLOW_SNAPSHOT_ISOLATION { ON | OFF }

When you set ALLOW_SNAPSHOT_ISOLATION to a new state (from ON to OFF, or from OFF to ON), ALTER DATABASE doesn't return control to the caller until all existing transactions in the database are committed. If the database is already in the state specified in the ALTER DATABASE statement, control is returned to the caller immediately. If the ALTER DATABASE statement doesn't return quickly, use sys.dm_tran_active_snapshot_database_transactions to determine whether there are long-running transactions. If the ALTER DATABASE statement is canceled, the database remains in the state it was in when ALTER DATABASE was started. The sys.databases catalog view indicates the state of snapshot-isolation transactions in the database. If snapshot_isolation_state_desc = IN_TRANSITION_TO_ON, the statement ALTER DATABASE .... ALLOW_SNAPSHOT_ISOLATION OFF pauses six seconds and retries the operation.

You can't change the state of ALLOW_SNAPSHOT_ISOLATION if the database is OFFLINE.

If you set ALLOW_SNAPSHOT_ISOLATION in a READ_ONLY database, the setting is kept if the database is later set to READ_WRITE.

The current setting of this option can be determined by examining the snapshot_isolation_state column in the sys.databases catalog view.

READ_COMMITTED_SNAPSHOT { ON | OFF }

To set READ_COMMITTED_SNAPSHOT ON or OFF, there must be no active connections to the database except for the connection running the ALTER DATABASE command. However, the database doesn't have to be in single-user mode. You can't change the state of this option when the database is OFFLINE.

If you set READ_COMMITTED_SNAPSHOT in a READ_ONLY database, the setting is kept when the database is later set to READ_WRITE.

READ_COMMITTED_SNAPSHOT can't be turned ON for the master, tempdb, or msdb system databases. If you change the setting for model, that setting becomes the default for any new databases created, except for tempdb.

The current setting of this option can be determined by examining the is_read_committed_snapshot_on column in the sys.databases catalog view.

Warning

When a table is created with DURABILITY = SCHEMA_ONLY, and READ_COMMITTED_SNAPSHOT is subsequently changed using ALTER DATABASE, data in the table is lost.

Tip

In Azure SQL Database, the ALTER DATABASE command to set READ_COMMITTED_SNAPSHOT ON or OFF for a database must be executed in the master database.

MEMORY_OPTIMIZED_ELEVATE_TO_SNAPSHOT { ON | OFF }

You can't change the state of MEMORY_OPTIMIZED_ELEVATE_TO_SNAPSHOT if the database is OFFLINE.

The default value is OFF.

The current setting of this option can be determined by examining the is_memory_optimized_elevate_to_snapshot_on column in the sys.databases catalog view.

<sql_option> ::=

Controls the ANSI compliance options at the database level.

ANSI_NULL_DEFAULT { ON | OFF }

Determines the default value, NULL or NOT NULL, of a column or CLR user-defined type for which the nullability isn't explicitly defined in CREATE TABLE or ALTER TABLE statements. Columns that are defined with constraints follow constraint rules whatever this setting might be.

Connection-level settings that are set by using the SET statement override the default database-level setting for ANSI_NULL_DEFAULT. ODBC and OLE DB clients issue a connection-level SET statement setting ANSI_NULL_DEFAULT to ON for the session, by default. The clients run the statement when you connect to an instance of SQL Server. For more information, see SET ANSI_NULL_DFLT_ON.

For ANSI compatibility, setting the database option ANSI_NULL_DEFAULT to ON changes the database default to NULL.

You can determine this option's status by examining the is_ansi_null_default_on column in the sys.databases catalog view. You can also determine the status by examining the IsAnsiNullDefault property of the DATABASEPROPERTYEX function.

ANSI_NULLS { ON | OFF }

Important

In a future version of SQL Server, ANSI_NULLS will always be ON and any applications that explicitly set the option to OFF will produce an error. Avoid using this feature in new development work, and plan to modify applications that currently use this feature.

Connection-level settings that are set by using the SET statement override the default database setting for ANSI_NULLS. ODBC and OLE DB clients issue a connection-level SET statement setting ANSI_NULLS to ON for the session, by default. The clients run the statement when you connect to an instance of SQL Server. For more information, see SET ANSI_NULLS.

Note

SET ANSI_NULLS also must be set to ON when you create or make changes to indexes on computed columns or indexed views.

You can determine this option's status by examining the is_ansi_nulls_on column in the sys.databases catalog view. You can also determine the status by examining the IsAnsiNullsEnabled property of the DATABASEPROPERTYEX function.

ANSI_PADDING { ON | OFF }

Important

In a future version of SQL Server, ANSI_PADDING will always be ON and any applications that explicitly set the option to OFF will produce an error. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. We recommend that you always set ANSI_PADDING to ON. ANSI_PADDING must be ON when you create or manipulate indexes on computed columns or indexed views.

char(n) and binary(n) columns that allow for nulls are padded to the column length when ANSI_PADDING is set to ON. Trailing blanks and zeros are trimmed when ANSI_PADDING is OFF. char(n) and binary(n) columns that don't allow nulls are always padded to the length of the column.

Connection-level settings that are set by using the SET statement override the default database-level setting for ANSI_PADDING. ODBC and OLE DB clients issue a connection-level SET statement setting ANSI_PADDING to ON for the session, by default. The clients run the statement when you connect to an instance of SQL Server. For more information, see SET ANSI_PADDING.

You can determine this option's status by examining the is_ansi_padding_on column in the sys.databases catalog view. You can also determine the status by examining the IsAnsiPaddingEnabled property of the DATABASEPROPERTYEX function.

ANSI_WARNINGS { ON | OFF }

Note

SET ANSI_WARNINGS must be set to ON when you create or make changes to indexes on computed columns or indexed views.

Connection-level settings that are set by using the SET statement override the default database setting for ANSI_WARNINGS. ODBC and OLE DB clients issue a connection-level SET statement setting ANSI_WARNINGS to ON for the session, by default. The clients run the statement when you connect to an instance of SQL Server. For more information, see SET ANSI_WARNINGS.

You can determine this option's status by examining the is_ansi_warnings_on column in the sys.databases catalog view. You can also determine the status by examining the IsAnsiWarningsEnabled property of the DATABASEPROPERTYEX function.

ARITHABORT { ON | OFF }

Note

SET ARITHABORT must be set to ON when you create or make changes to indexes on computed columns or indexed views.

You can determine this option's status by examining the is_arithabort_on column in the sys.databases catalog view. You can also determine the status by examining the IsArithmeticAbortEnabled property of the DATABASEPROPERTYEX function.

COMPATIBILITY_LEVEL = { 160 | 150 | 140 | 130 | 120 | 110 | 100 }

For more information, see ALTER DATABASE compatibility level.

CONCAT_NULL_YIELDS_NULL { ON | OFF }

Note

CONCAT_NULL_YIELDS_NULL must be set to ON when you create or make changes to indexes on computed columns or indexed views.

In a future version of SQL Server, CONCAT_NULL_YIELDS_NULL will always be ON and any applications that explicitly set the option to OFF will produce an error. Avoid using this feature in new development work, and plan to modify applications that currently use this feature.

Connection-level settings that are set by using the SET statement override the default database setting for CONCAT_NULL_YIELDS_NULL. By default, ODBC and OLE DB clients issue a connection-level SET statement setting CONCAT_NULL_YIELDS_NULL to ON for the session when connecting to an instance of SQL Server. For more information, see SET CONCAT_NULL_YIELDS_NULL.

You can determine this option's status by examining the is_concat_null_yields_null_on column in the sys.databases catalog view. You can also determine the status by examining the IsNullConcat property of the DATABASEPROPERTYEX function.

NUMERIC_ROUNDABORT { ON | OFF }

Important

NUMERIC_ROUNDABORT must be set to OFF when you create or make changes to indexes on computed columns or indexed views.

You can determine the status for this option in the is_numeric_roundabort_on column in the sys.databases catalog view. You can also determine the status by examining the IsNumericRoundAbortEnabled property of the DATABASEPROPERTYEX function.

QUOTED_IDENTIFIER { ON | OFF }

SQL Server also allows for identifiers to be delimited by square brackets ([ and ]). Bracketed identifiers can always be used, whatever the QUOTED_IDENTIFIER setting is. For more information, see Database identifiers.

When a table is created, the QUOTED IDENTIFIER option is always stored as ON in the metadata of the table. The option is stored even if the option is set to OFF when the table is created.

Connection-level settings that are set by using the SET statement override the default database setting for QUOTED_IDENTIFIER. ODBC and OLE DB clients issue a connection-level SET statement setting QUOTED_IDENTIFIER to ON, by default. The clients run the statement when you connect to an instance of SQL Server. For more information, see SET QUOTED_IDENTIFIER.

You can determine this option's status by examining the is_quoted_identifier_on column in the sys.databases catalog view. You can also determine the status by examining the IsQuotedIdentifiersEnabled property of the DATABASEPROPERTYEX function.

RECURSIVE_TRIGGERS { ON | OFF }

Note

Only direct recursion is prevented when RECURSIVE_TRIGGERS is set to OFF. To disable indirect recursion, you must also set the nested triggers server option to 0.

You can determine this option's status by examining the is_recursive_triggers_on column in the sys.databases catalog view or the IsRecursiveTriggersEnabled property of the DATABASEPROPERTYEX function.

<target_recovery_time_option> ::=

Specifies the frequency of indirect checkpoints on a per-database basis. Starting with SQL Server 2016 (13.x) the default value for new databases is 1 minute, which indicates the database uses indirect checkpoints. For older versions the default is 0, which indicates that the database uses automatic checkpoints, whose frequency depends on the recovery interval setting of the server instance. Microsoft recommends 1 minute for most systems.

TARGET_RECOVERY_TIME = target_recovery_time { SECONDS | MINUTES }

For more information about indirect checkpoints, see Database checkpoints.

WITH <termination> ::=

Specifies when to roll back incomplete transactions when the database is transitioned from one state to another. If the termination clause is omitted, the ALTER DATABASE statement waits indefinitely if there's any lock on the database. Only one termination clause can be specified, and it follows the SET clauses.

Note

Not all database options use the WITH <termination> clause. For more information, see the table under Setting options of the "Remarks" section of this article.

<temporal_history_retention> ::= Set options

To retrieve current settings for database options, use the sys.databases catalog view or DATABASEPROPERTYEX

After you set a database option, the new setting takes effect immediately.

You can change the default values for any one of the database options for all newly created databases. To do so, change the appropriate database option in the model database.

Not all database options use the WITH <termination> clause or can be specified in combination with other options. The following table lists these options and their option and termination status.

Options category Can be specified with other options Can use the WITH <termination> clause <auto_option> Yes No <change_tracking_option> Yes Yes <cursor_option> Yes No <db_encryption_option> Yes No <db_update_option> Yes Yes <db_user_access_option> Yes Yes <delayed_durability_option> Yes Yes <parameterization_option> Yes Yes ALLOW_SNAPSHOT_ISOLATION No No READ_COMMITTED_SNAPSHOT No Yes MEMORY_OPTIMIZED_ELEVATE_TO_SNAPSHOT Yes Yes DATE_CORRELATION_OPTIMIZATION Yes Yes <sql_option> Yes No <target_recovery_time_option> No Yes Examples A. Set the database to READ_ONLY

Changing the state of a database or file group to READ_ONLY or READ_WRITE requires exclusive access to the database and might take a few seconds to complete. The following example sets the database to RESTRICTED_USER mode to limit access. The example then sets the state of the AdventureWorks2022 database to READ_ONLY and returns access to the database to all users.

--Connect to [database_name];
GO
ALTER DATABASE [database_name]
SET RESTRICTED_USER;
GO
ALTER DATABASE [database_name]
SET READ_ONLY
--`SET READ_ONLY` command might take a few seconds to complete.
GO
ALTER DATABASE [database_name]
SET MULTI_USER;
GO

To set the database back to read-write mode:

--Connect to [database_name];
GO
ALTER DATABASE [database_name]
SET READ_WRITE
GO

To verify:

SELECT [name], user_access_desc, is_read_only FROM sys.databases
WHERE [name] = 'database_name'
GO
B. Enable snapshot isolation on a database

The following example enables the snapshot isolation framework option for the AdventureWorks2022 database.

--Connect to [database_name]
GO
ALTER DATABASE [database_name]
SET ALLOW_SNAPSHOT_ISOLATION ON;
GO

Verify the state of the snapshot_isolation_framework in the database.

--Connect to [database_name]
SELECT name, snapshot_isolation_state,
    snapshot_isolation_state_desc AS description
FROM sys.databases
WHERE name = N'database_name';
GO

The result set shows that the snapshot isolation framework is enabled.

name snapshot_isolation_state description [database_name] 1 ON C. Enable, modify, or disable change tracking

The following example enables change tracking for the AdventureWorks2022 database and sets the retention period to 2 days.

--Connect to [database_name]
ALTER DATABASE [database_name]
SET CHANGE_TRACKING = ON
(AUTO_CLEANUP = ON, CHANGE_RETENTION = 2 DAYS);

The following example shows how to change the retention period to 3 days.

--Connect to [database_name]
ALTER DATABASE [database_name]
SET CHANGE_TRACKING (CHANGE_RETENTION = 3 DAYS);

The following example shows how to disable change tracking for the AdventureWorks2022 database.

--Connect to [database_name]
ALTER DATABASE [database_name]
SET CHANGE_TRACKING = OFF;
D. Enable the Query Store

The following example enables the Query Store and configures Query Store parameters.

--Connect to [database_name]
ALTER DATABASE [database_name]
SET QUERY_STORE = ON
    (
      OPERATION_MODE = READ_WRITE,
      CLEANUP_POLICY = ( STALE_QUERY_THRESHOLD_DAYS = 90 ),
      DATA_FLUSH_INTERVAL_SECONDS = 900,
      QUERY_CAPTURE_MODE = AUTO,
      MAX_STORAGE_SIZE_MB = 1024,
      INTERVAL_LENGTH_MINUTES = 60
    );
E. Enable the Query Store with wait statistics

The following example enables the Query Store and configures its parameters.

--Connect to [database_name]
ALTER DATABASE [database_name]
SET QUERY_STORE = ON
    (
      OPERATION_MODE = READ_WRITE,
      CLEANUP_POLICY = ( STALE_QUERY_THRESHOLD_DAYS = 90 ),
      DATA_FLUSH_INTERVAL_SECONDS = 900,
      MAX_STORAGE_SIZE_MB = 1024,
      INTERVAL_LENGTH_MINUTES = 60,
      SIZE_BASED_CLEANUP_MODE = AUTO,
      MAX_PLANS_PER_QUERY = 200,
      WAIT_STATS_CAPTURE_MODE = ON
    );
F. Enable the Query Store with custom capture policy options

The following example enables the Query Store and configures its parameters.

--Connect to [database_name]
ALTER DATABASE [database_name]
SET QUERY_STORE = ON
    (
      OPERATION_MODE = READ_WRITE,
      CLEANUP_POLICY = ( STALE_QUERY_THRESHOLD_DAYS = 90 ),
      DATA_FLUSH_INTERVAL_SECONDS = 900,
      MAX_STORAGE_SIZE_MB = 1024,
      INTERVAL_LENGTH_MINUTES = 60,
      SIZE_BASED_CLEANUP_MODE = AUTO,
      MAX_PLANS_PER_QUERY = 200,
      WAIT_STATS_CAPTURE_MODE = ON,
      QUERY_CAPTURE_MODE = CUSTOM,
      QUERY_CAPTURE_POLICY = (
        STALE_CAPTURE_POLICY_THRESHOLD = 24 HOURS,
        EXECUTION_COUNT = 30,
        TOTAL_COMPILE_CPU_TIME_MS = 1000,
        TOTAL_EXECUTION_CPU_TIME_MS = 100
      )
    );

SQL Server

SQL Database

* SQL Managed Instance *  

Azure Synapse
Analytics

Microsoft Fabric

Azure SQL Managed Instance

Compatibility levels are SET options but are described in ALTER DATABASE compatibility level.

Note

Many database set options can be configured for the current session by using SET Statements and are often configured by applications when they connect. Session-level set options override the ALTER DATABASE SET values. The database options described in the following sections are values that can be set for sessions that don't explicitly provide other set option values.

Syntax
ALTER DATABASE { database_name | Current }
SET
{
    <optionspec> [ ,...n ]
}
;

<optionspec> ::=
{
    <auto_option>
  | <change_tracking_option>
  | <cursor_option>
  | <db_encryption_option>
  | <delayed_durability_option>
  | <parameterization_option>
  | <query_store_options>
  | <snapshot_option>
  | <sql_option>
  | <target_recovery_time_option>
  | <termination>
  | <temporal_history_retention>
}
;
<auto_option> ::=
{
    AUTO_CREATE_STATISTICS { OFF | ON [ ( INCREMENTAL = { ON | OFF } ) ] }
  | AUTO_SHRINK { ON | OFF }
  | AUTO_UPDATE_STATISTICS { ON | OFF }
  | AUTO_UPDATE_STATISTICS_ASYNC { ON | OFF }
}

<automatic_tuning_option> ::=
{
    AUTOMATIC_TUNING ( FORCE_LAST_GOOD_PLAN = { DEFAULT | ON | OFF } )
}

<change_tracking_option> ::=
{
    CHANGE_TRACKING
    {
       = OFF
     | = ON [ ( <change_tracking_option_list > [,...n] ) ]
     | ( <change_tracking_option_list> [,...n] )
    }
}

<change_tracking_option_list> ::=
   {
       AUTO_CLEANUP = { ON | OFF }
     | CHANGE_RETENTION = retention_period { DAYS | HOURS | MINUTES }
   }

<cursor_option> ::=
{
    CURSOR_CLOSE_ON_COMMIT { ON | OFF }
}

<db_encryption_option> ::=
  ENCRYPTION { ON | OFF }

<delayed_durability_option> ::=DELAYED_DURABILITY = { DISABLED | ALLOWED | FORCED }

<parameterization_option> ::=
  PARAMETERIZATION { SIMPLE | FORCED }

<query_store_options> ::=
{
  QUERY_STORE
  {
    = OFF
    | = ON [ ( <query_store_option_list> [,... n] ) ]
    | ( < query_store_option_list> [,... n] )
    | CLEAR [ ALL ]
  }
}

<query_store_option_list> ::=
{
  OPERATION_MODE = { READ_WRITE | READ_ONLY }
  | CLEANUP_POLICY = ( STALE_QUERY_THRESHOLD_DAYS = number )
  | DATA_FLUSH_INTERVAL_SECONDS = number
  | MAX_STORAGE_SIZE_MB = number
  | INTERVAL_LENGTH_MINUTES = number
  | SIZE_BASED_CLEANUP_MODE = { AUTO | OFF }
  | QUERY_CAPTURE_MODE = { ALL | AUTO | CUSTOM | NONE }
  | MAX_PLANS_PER_QUERY = number
  | WAIT_STATS_CAPTURE_MODE = { ON | OFF }
  | QUERY_CAPTURE_POLICY = ( <query_capture_policy_option_list> [,...n] )
}

<query_capture_policy_option_list> :: =
{
    STALE_CAPTURE_POLICY_THRESHOLD = number { DAYS | HOURS }
    | EXECUTION_COUNT = number
    | TOTAL_COMPILE_CPU_TIME_MS = number
    | TOTAL_EXECUTION_CPU_TIME_MS = number
}

<snapshot_option> ::=
{
    ALLOW_SNAPSHOT_ISOLATION { ON | OFF }
  | READ_COMMITTED_SNAPSHOT { ON | OFF }
  | MEMORY_OPTIMIZED_ELEVATE_TO_SNAPSHOT { ON | OFF }
}
<sql_option> ::=
{
    ANSI_NULL_DEFAULT { ON | OFF }
  | ANSI_NULLS { ON | OFF }
  | ANSI_PADDING { ON | OFF }
  | ANSI_WARNINGS { ON | OFF }
  | ARITHABORT { ON | OFF }
  | COMPATIBILITY_LEVEL = { 160 | 150 | 140 | 130 | 120 | 110 | 100 }
  | CONCAT_NULL_YIELDS_NULL { ON | OFF }
  | NUMERIC_ROUNDABORT { ON | OFF }
  | QUOTED_IDENTIFIER { ON | OFF }
  | RECURSIVE_TRIGGERS { ON | OFF }
}

<temporal_history_retention>::= TEMPORAL_HISTORY_RETENTION { ON | OFF }
Arguments database_name

The name of the database to be modified.

CURRENT

CURRENT runs the action in the current database. CURRENT isn't supported for all options in all contexts. If CURRENT fails, provide the database name.

<auto_option> ::=

Controls automatic options.

AUTO_CREATE_STATISTICS { ON | OFF } INCREMENTAL = ON | OFF

Set AUTO_CREATE_STATISTICS to ON, and set INCREMENTAL to ON. This setting creates automatically created stats as incremental whenever incremental stats are supported. The default value is OFF. For more information, see CREATE STATISTICS.

AUTO_SHRINK { ON | OFF }

You can determine this option's status by examining the is_auto_shrink_on column in the sys.databases catalog view. You can also determine the status by examining the IsAutoShrink property of the DATABASEPROPERTYEX function.

Note

The AUTO_SHRINK option isn't available in a Contained Database.

AUTO_UPDATE_STATISTICS { ON | OFF }

You can determine this option's status by examining the is_auto_update_stats_on column in the sys.databases catalog view. You can also determine the status by examining the IsAutoUpdateStatistics property of the DATABASEPROPERTYEX function.

For more information, see the section "Using the database-wide statistics options" in Statistics.

AUTO_UPDATE_STATISTICS_ASYNC { ON | OFF }

You can determine this option's status by examining the is_auto_update_stats_async_on column in the sys.databases catalog view.

For more information that describes when to use synchronous or asynchronous statistics updates, see the section "Using the database-wide statistics options" in Statistics.

<automatic_tuning_option> ::=

Controls automatic options for Automatic tuning.

FORCE_LAST_GOOD_PLAN = { DEFAULT | ON | OFF }

Enables or disables FORCE_LAST_GOOD_PLAN Automatic tuning option.

<change_tracking_option> ::=

Controls change tracking options. You can enable change tracking, set options, change options, and disable change tracking. For examples, see the Examples section later in this article.

AUTO_CLEANUP = { ON | OFF } CHANGE_RETENTION = retention_period { DAYS | HOURS | MINUTES }

Specifies the minimum period for keeping change tracking information in the database. Data is removed only when the AUTO_CLEANUP value is ON.

retention_period is an integer that specifies the numerical component of the retention period.

The default retention period is 2 days. The minimum retention period is 1 minute. The default retention type is DAYS.

<cursor_option> ::=

Controls cursor options.

CURSOR_CLOSE_ON_COMMIT { ON | OFF }

Connection-level settings that are set by using the SET statement override the default database setting for CURSOR_CLOSE_ON_COMMIT. ODBC and OLE DB clients issue a connection-level SET statement setting CURSOR_CLOSE_ON_COMMIT to OFF for the session, by default. The clients run the statement when you connect to an instance of SQL Server. For more information, see SET CURSOR_CLOSE_ON_COMMIT.

You can determine this option's status by examining the is_cursor_close_on_commit_on column in the sys.databases catalog view or the IsCloseCursorsOnCommitEnabled property of the DATABASEPROPERTYEX function. The cursor is implicitly deallocated only at disconnect. For more information, see DECLARE CURSOR.

<db_encryption_option> ::=

Controls the database encryption state.

ENCRYPTION { ON | OFF }

Sets the database to be encrypted (ON) or not encrypted (OFF). For more information about database encryption, see Transparent data encryption (TDE), and Transparent data encryption for Azure SQL Database, Azure SQL Managed Instance, and Azure Synapse Analytics.

When encryption is enabled at the database level, all file groups are encrypted. Any new file groups inherit the encrypted property. If any file groups in the database are set to READ ONLY, the database encryption operation fails.

You can see the encryption state of the database by using the sys.dm_database_encryption_keys dynamic management view.

<delayed_durability_option> ::=

Controls whether transactions commit fully durable or delayed durable.

<PARAMETERIZATION_option> ::=

Controls the parameterization option.

PARAMETERIZATION { SIMPLE | FORCED }

SQL Server parameterizes all queries in the database.

The current setting of this option can be determined by examining the is_parameterization_forced column in the sys.databases catalog view.

<query_store_options> ::= OPERATION_MODE

Describes the operation mode of the Query Store. Valid values are READ_ONLY and READ_WRITE. In READ_WRITE mode, the Query Store collects and persists query plan and runtime execution statistics information. In READ_ONLY mode, information can be read from the Query Store, but new information isn't added. If the maximum allocated space of the Query Store has been exhausted, the Query Store changes its operation mode to READ_ONLY.

CLEANUP_POLICY

Describes the data retention policy of the Query Store. STALE_QUERY_THRESHOLD_DAYS determines the number of days for which the information for a query is kept in the Query Store. STALE_QUERY_THRESHOLD_DAYS is type bigint. The default value is 30. For SQL Database Basic edition, default is 7 days.

DATA_FLUSH_INTERVAL_SECONDS

Determines the frequency at which data written to the Query Store is persisted to disk. To optimize for performance, data collected by the Query Store is asynchronously written to the disk. The frequency at which this asynchronous transfer occurs is configured by using the DATA_FLUSH_INTERVAL_SECONDS argument. DATA_FLUSH_INTERVAL_SECONDS is type bigint. The default value is 900 (15 min).

MAX_STORAGE_SIZE_MB

Determines the space allocated to the Query Store. MAX_STORAGE_SIZE_MB is type bigint. The default value is 100 MB.

MAX_STORAGE_SIZE_MB limit isn't strictly enforced. Storage size is checked only when Query Store writes data to disk. This interval is set by the DATA_FLUSH_INTERVAL_SECONDS option or the Management Studio Query Store dialog option Data Flush Interval. The interval default value is 900 seconds (or 15 minutes).

If the Query Store has breached the MAX_STORAGE_SIZE_MB limit between storage size checks, it transitions to read-only mode. If SIZE_BASED_CLEANUP_MODE is enabled, the cleanup mechanism to enforce the MAX_STORAGE_SIZE_MB limit is also triggered.

Once enough space has been cleared, the Query Store mode automatically switches back to read-write.

Important

INTERVAL_LENGTH_MINUTES

Determines the time interval at which runtime execution statistics data is aggregated into the Query Store. To optimize for space usage, the runtime execution statistics in the runtime stats store are aggregated over a fixed time window. This fixed time window is configured by using the INTERVAL_LENGTH_MINUTES argument. INTERVAL_LENGTH_MINUTES is type bigint. The default value is 60.

SIZE_BASED_CLEANUP_MODE = { AUTO | OFF }

Controls whether cleanup is automatically activated when the total amount of data gets close to maximum size.

SIZE_BASED_CLEANUP_MODE is type nvarchar.

QUERY_CAPTURE_MODE { ALL | AUTO | CUSTOM | NONE }

Designates the currently active query capture mode.

QUERY_CAPTURE_MODE is type nvarchar.

MAX_PLANS_PER_QUERY

An integer representing the maximum number of plans maintained for each query. MAX_PLANS_PER_QUERY is type int. The default value is 200.

WAIT_STATS_CAPTURE_MODE { ON | OFF }

Controls whether wait statistics are captured per query.

<query_capture_policy_option_list> :: =

Controls the Query Store capture policy options. Except for STALE_CAPTURE_POLICY_THRESHOLD, these options define the OR conditions that need to happen for queries to be captured in the defined Stale Capture Policy Threshold value.

STALE_CAPTURE_POLICY_THRESHOLD = integer { DAYS | HOURS }

Defines the evaluation interval period to determine if a query should be captured. The default is 1 day, and it can be set from 1 hour to seven days.

EXECUTION_COUNT = integer

Defines the number of times a query is executed over the evaluation period. The default is 30, which means that for the default Stale Capture Policy Threshold, a query must execute at least 30 times in one day to be persisted in the Query Store. EXECUTION_COUNT is type int.

TOTAL_COMPILE_CPU_TIME_MS = integer

Defines total elapsed compile CPU time used by a query over the evaluation period. The default is 1000, which means that for the default Stale Capture Policy Threshold, a query must have a total of at least one second of CPU time spent during query compilation in one day to be persisted in the Query Store. TOTAL_COMPILE_CPU_TIME_MS is type int.

TOTAL_EXECUTION_CPU_TIME_MS = integer

Defines total elapsed execution CPU time used by a query over the evaluation period. The default is 100, which means that for the default Stale Capture Policy Threshold, a query must have a total of at least 100 ms of CPU time spent during execution in one day to be persisted in the Query Store. TOTAL_EXECUTION_CPU_TIME_MS is type int.

<snapshot_option> ::=

Determines the transaction isolation level.

ALLOW_SNAPSHOT_ISOLATION { ON | OFF }

When you set ALLOW_SNAPSHOT_ISOLATION to a new state (from ON to OFF, or from OFF to ON), ALTER DATABASE doesn't return control to the caller until all existing transactions in the database are committed. If the database is already in the state specified in the ALTER DATABASE statement, control is returned to the caller immediately. If the ALTER DATABASE statement doesn't return quickly, use sys.dm_tran_active_snapshot_database_transactions to determine whether there are long-running transactions. If the ALTER DATABASE statement is canceled, the database remains in the state it was in when ALTER DATABASE was started. The sys.databases catalog view indicates the state of snapshot-isolation transactions in the database. If snapshot_isolation_state_desc = IN_TRANSITION_TO_ON, the statement ALTER DATABASE ... ALLOW_SNAPSHOT_ISOLATION OFF pauses six seconds and retry the operation.

You can't change the state of ALLOW_SNAPSHOT_ISOLATION if the database is OFFLINE.

You can change the ALLOW_SNAPSHOT_ISOLATION settings for the master, model, msdb, and tempdb databases. The setting is kept every time the instance of the Database Engine is stopped and restarted if you change the setting for tempdb. If you change the setting for the model system database, that setting becomes the default for any new databases that are created, except for tempdb.

The option is ON, by default, for the master and msdb databases.

The current setting of this option can be determined by examining the snapshot_isolation_state column in the sys.databases catalog view.

READ_COMMITTED_SNAPSHOT { ON | OFF }

To set READ_COMMITTED_SNAPSHOT to ON or OFF, there must be no active connections to the database except for the connection running the ALTER DATABASE command. However, the database doesn't have to be in single-user mode. You can't change the state of this option when the database is OFFLINE.

READ_COMMITTED_SNAPSHOT can't be turned ON for the master, tempdb, or msdb system databases. If you change the setting for the model system database, that setting becomes the default for any new databases created, except for tempdb.

The current setting of this option can be determined by examining the is_read_committed_snapshot_on column in the sys.databases catalog view.

Warning

When a table is created with DURABILITY = SCHEMA_ONLY, and READ_COMMITTED_SNAPSHOT is subsequently changed using ALTER DATABASE, data in the table is lost.

MEMORY_OPTIMIZED_ELEVATE_TO_SNAPSHOT { ON | OFF }

You can't change the state of MEMORY_OPTIMIZED_ELEVATE_TO_SNAPSHOT if the database is OFFLINE.

The default value is OFF.

The current setting of this option can be determined by examining the is_memory_optimized_elevate_to_snapshot_on column in the sys.databases catalog view.

<sql_option> ::=

Controls the ANSI compliance options at the database level.

ANSI_NULL_DEFAULT { ON | OFF }

Determines the default value, NULL or NOT NULL, of a column or CLR user-defined type for which the nullability isn't explicitly defined in CREATE TABLE or ALTER TABLE statements. Columns that are defined with constraints follow constraint rules whatever this setting might be.

Connection-level settings that are set by using the SET statement override the default database-level setting for ANSI_NULL_DEFAULT. ODBC and OLE DB clients issue a connection-level SET statement setting ANSI_NULL_DEFAULT to ON for the session, by default. The clients run the statement when you connect to an instance of SQL Server. For more information, see SET ANSI_NULL_DFLT_ON.

For ANSI compatibility, setting the database option ANSI_NULL_DEFAULT to ON changes the database default to NULL.

You can determine this option's status by examining the is_ansi_null_default_on column in the sys.databases catalog view. You can also determine the status by examining the IsAnsiNullDefault property of the DATABASEPROPERTYEX function.

ANSI_NULLS { ON | OFF }

Important

In a future version of SQL Server, ANSI_NULLS will always be ON and any applications that explicitly set the option to OFF will produce an error. Avoid using this feature in new development work, and plan to modify applications that currently use this feature.

Connection-level settings that are set by using the SET statement override the default database setting for ANSI_NULLS. ODBC and OLE DB clients issue a connection-level SET statement setting ANSI_NULLS to ON for the session, by default. The clients run the statement when you connect to an instance of SQL Server. For more information, see SET ANSI_NULLS.

Important

SET ANSI_NULLS also must be set to ON when you create or make changes to indexes on computed columns or indexed views.

You can determine this option's status by examining the is_ansi_nulls_on column in the sys.databases catalog view. You can also determine the status by examining the IsAnsiNullsEnabled property of the DATABASEPROPERTYEX function.

ANSI_PADDING { ON | OFF }

Important

In a future version of SQL Server, ANSI_PADDING will always be ON and any applications that explicitly set the option to OFF will produce an error. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. We recommend that you always set ANSI_PADDING to ON. ANSI_PADDING must be ON when you create or manipulate indexes on computed columns or indexed views.

char(n) and binary(n) columns that allow for nulls are padded to the column length when ANSI_PADDING is set to ON. Trailing blanks and zeros are trimmed when ANSI_PADDING is OFF. char(n) and binary(n) columns that don't allow nulls are always padded to the length of the column.

Connection-level settings that are set by using the SET statement override the default database-level setting for ANSI_PADDING. ODBC and OLE DB clients issue a connection-level SET statement setting ANSI_PADDING to ON for the session, by default. The clients run the statement when you connect to an instance of SQL Server. For more information, see SET ANSI_PADDING.

You can determine this option's status by examining the is_ansi_padding_on column in the sys.databases catalog view. You can also determine the status by examining the IsAnsiPaddingEnabled property of the DATABASEPROPERTYEX function.

ANSI_WARNINGS { ON | OFF }

Important

SET ANSI_WARNINGS must be set to ON when you create or make changes to indexes on computed columns or indexed views.

Connection-level settings that are set by using the SET statement override the default database setting for ANSI_WARNINGS. ODBC and OLE DB clients issue a connection-level SET statement setting ANSI_WARNINGS to ON for the session, by default. The clients run the statement when you connect to an instance of SQL Server. For more information, see SET ANSI_WARNINGS.

You can determine this option's status by examining the is_ansi_warnings_on column in the sys.databases catalog view. You can also determine the status by examining the IsAnsiWarningsEnabled property of the DATABASEPROPERTYEX function.

ARITHABORT { ON | OFF }

Important

SET ARITHABORT must be set to ON when you create or make changes to indexes on computed columns or indexed views.

You can determine this option's status by examining the is_arithabort_on column in the sys.databases catalog view. You can also determine the status by examining the IsArithmeticAbortEnabled property of the DATABASEPROPERTYEX function.

COMPATIBILITY_LEVEL = { 160 | 150 | 140 | 130 | 120 | 110 | 100 }

For more information, see ALTER DATABASE compatibility level.

CONCAT_NULL_YIELDS_NULL { ON | OFF }

Important

CONCAT_NULL_YIELDS_NULL must be set to ON when you create or make changes to indexes on computed columns or indexed views.

In a future version of SQL Server, CONCAT_NULL_YIELDS_NULL will always be ON and any applications that explicitly set the option to OFF will produce an error. Avoid using this feature in new development work, and plan to modify applications that currently use this feature.

Connection-level settings that are set by using the SET statement override the default database setting for CONCAT_NULL_YIELDS_NULL. By default, ODBC and OLE DB clients issue a connection-level SET statement setting CONCAT_NULL_YIELDS_NULL to ON for the session when connecting to an instance of SQL Server. For more information, see SET CONCAT_NULL_YIELDS_NULL.

You can determine this option's status by examining the is_concat_null_yields_null_on column in the sys.databases catalog view. You can also determine the status by examining the IsNullConcat property of the DATABASEPROPERTYEX function.

NUMERIC_ROUNDABORT { ON | OFF }

Important

NUMERIC_ROUNDABORT must be set to OFF when you create or make changes to indexes on computed columns or indexed views.

You can determine the status of this option in the is_numeric_roundabort_on column in the sys.databases catalog view. You can also determine the status by examining the IsNumericRoundAbortEnabled property of the DATABASEPROPERTYEX function.

QUOTED_IDENTIFIER { ON | OFF }

SQL Server also allows for identifiers to be delimited by square brackets ([ and ]). Bracketed identifiers can always be used, whatever the QUOTED_IDENTIFIER setting is. For more information, see Database identifiers.

When a table is created, the QUOTED IDENTIFIER option is always stored as ON in the metadata of the table. The option is stored even if the option is set to OFF when the table is created.

Connection-level settings that are set by using the SET statement override the default database setting for QUOTED_IDENTIFIER. ODBC and OLE DB clients issue a connection-level SET statement setting QUOTED_IDENTIFIER to ON, by default. The clients run the statement when you connect to an instance of SQL Server. For more information, see SET QUOTED_IDENTIFIER.

You can determine this option's status by examining the is_quoted_identifier_on column in the sys.databases catalog view. You can also determine the status by examining the IsQuotedIdentifiersEnabled property of the DATABASEPROPERTYEX function.

RECURSIVE_TRIGGERS { ON | OFF }

You can determine this option's status by examining the is_recursive_triggers_on column in the sys.databases catalog view or the IsRecursiveTriggersEnabled property of the DATABASEPROPERTYEX function.

<target_recovery_time_option> ::=

target_recovery_time_option isn't supported on Azure SQL Managed Instance.

Specifies the frequency of indirect checkpoints on a per-database basis. Starting with SQL Server 2016 (13.x) the default value for new databases is 1 minute, which indicates database uses indirect checkpoints. For older versions the default is 0, which indicates that the database uses automatic checkpoints, whose frequency depends on the recovery interval setting of the server instance. Microsoft recommends 1 minute for most systems.

WITH <termination> ::=

Specifies when to roll back incomplete transactions when the database is transitioned from one state to another. If the termination clause is omitted, the ALTER DATABASE statement waits indefinitely if there's any lock on the database. Only one termination clause can be specified, and it follows the SET clauses.

Note

Not all database options use the WITH <termination> clause. For more information, see the table under Setting options of the "Remarks" section of this article.

<temporal_history_retention> ::= Set options

To retrieve current settings for database options, use the sys.databases catalog view or DATABASEPROPERTYEX

After you set a database option, the new setting takes effect immediately.

You can change the default values for any one of the database options for all newly created databases. To do so, change the appropriate database option in the model system database.

Examples A. Enable snapshot isolation on a database

The following example enables the snapshot isolation framework option for the AdventureWorks2022 database.

USE master;
GO
ALTER DATABASE [database_name]
SET ALLOW_SNAPSHOT_ISOLATION ON;
GO
-- Check the state of the snapshot_isolation_framework
-- in the database.
SELECT name, snapshot_isolation_state,
    snapshot_isolation_state_desc AS description
FROM sys.databases
WHERE name = N'[database_name]';
GO

The result set shows that the snapshot isolation framework is enabled.

name snapshot_isolation_state description [database_name] 1 ON B. Enable, modify, or disable change tracking

The following example enables change tracking for the AdventureWorks2022 database and sets the retention period to 2 days.

ALTER DATABASE [database_name]
SET CHANGE_TRACKING = ON
(AUTO_CLEANUP = ON, CHANGE_RETENTION = 2 DAYS);

The following example shows how to change the retention period to 3 days.

ALTER DATABASE [database_name]
SET CHANGE_TRACKING (CHANGE_RETENTION = 3 DAYS);

The following example shows how to disable change tracking for the AdventureWorks2022 database.

ALTER DATABASE [database_name]
SET CHANGE_TRACKING = OFF;
C. Enable the Query Store

The following example enables the Query Store and configures Query Store parameters.

ALTER DATABASE [database_name]
SET QUERY_STORE = ON
    (
      OPERATION_MODE = READ_WRITE,
      CLEANUP_POLICY = ( STALE_QUERY_THRESHOLD_DAYS = 90 ),
      DATA_FLUSH_INTERVAL_SECONDS = 900,
      QUERY_CAPTURE_MODE = AUTO,
      MAX_STORAGE_SIZE_MB = 1024,
      INTERVAL_LENGTH_MINUTES = 60
    );
D. Enable the Query Store with wait statistics

The following example enables the Query Store and configures its parameters.

ALTER DATABASE [database_name]
SET QUERY_STORE = ON
    (
      OPERATION_MODE = READ_WRITE,
      CLEANUP_POLICY = ( STALE_QUERY_THRESHOLD_DAYS = 90 ),
      DATA_FLUSH_INTERVAL_SECONDS = 900,
      MAX_STORAGE_SIZE_MB = 1024,
      INTERVAL_LENGTH_MINUTES = 60,
      SIZE_BASED_CLEANUP_MODE = AUTO,
      MAX_PLANS_PER_QUERY = 200,
      WAIT_STATS_CAPTURE_MODE = ON
    );
E. Enable the Query Store with custom capture policy options

The following example enables the Query Store and configures its parameters.

ALTER DATABASE [database_name]
SET QUERY_STORE = ON
    (
      OPERATION_MODE = READ_WRITE,
      CLEANUP_POLICY = ( STALE_QUERY_THRESHOLD_DAYS = 90 ),
      DATA_FLUSH_INTERVAL_SECONDS = 900,
      MAX_STORAGE_SIZE_MB = 1024,
      INTERVAL_LENGTH_MINUTES = 60,
      SIZE_BASED_CLEANUP_MODE = AUTO,
      MAX_PLANS_PER_QUERY = 200,
      WAIT_STATS_CAPTURE_MODE = ON,
      QUERY_CAPTURE_MODE = CUSTOM,
      QUERY_CAPTURE_POLICY = (
        STALE_CAPTURE_POLICY_THRESHOLD = 24 HOURS,
        EXECUTION_COUNT = 30,
        TOTAL_COMPILE_CPU_TIME_MS = 1000,
        TOTAL_EXECUTION_CPU_TIME_MS = 100
      )
    );

SQL Server

SQL Database

SQL Managed Instance

* Azure Synapse
Analytics *
 

Microsoft Fabric

Azure Synapse Analytics Syntax
ALTER DATABASE { database_name }
SET
{
    <optionspec> [ ,...n ]
}
;

<option_spec>::=
{
    <auto_option>
  | <db_encryption_option>
  | <query_store_options>
  | <result_set_caching>
  | <snapshot_option>
}
;

<auto_option> ::=
{
    AUTO_CREATE_STATISTICS { OFF | ON }
}

<db_encryption_option> ::=
{
    ENCRYPTION { ON | OFF }
}

<query_store_option> ::=
{
    QUERY_STORE { OFF | ON }
}

<result_set_caching_option> ::=
{
    RESULT_SET_CACHING { ON | OFF }
}

<snapshot_option> ::=
{
    READ_COMMITTED_SNAPSHOT { ON | OFF }
}
Arguments database_name

The name of the database to be modified.

<auto_option> ::=

Controls automatic options.

AUTO_CREATE_STATISTICS { ON | OFF }

This command must be run while connected to the user database.

You can determine this option's status by examining the is_auto_create_stats_on column in the sys.databases catalog view. You can also determine the status by examining the IsAutoCreateStatistics property of the DATABASEPROPERTYEX function.

For more information, see the section "Using the database-wide statistics options" in Statistics.

<db_encryption_option> ::=

Controls the database encryption state.

ENCRYPTION { ON | OFF }

For more information about database encryption, see Transparent data encryption (TDE), and Transparent data encryption for Azure SQL Database, Azure SQL Managed Instance, and Azure Synapse Analytics.

When encryption is enabled at the database level, all file groups are encrypted. Any new file groups inherit the encrypted property. If any file groups in the database are set to READ ONLY, the database encryption operation fails.

You can see the encryption state of the database and the state of the encryption scan by using the sys.dm_database_encryption_keys dynamic management view.

<query_store_option> ::=

Controls whether the Query Store is enabled in this data warehouse.

QUERY_STORE { ON | OFF }

Note

For Azure Synapse Analytics, you must execute ALTER DATABASE SET QUERY_STORE from the user database. Executing the statement from another data warehouse instance isn't supported.

Note

For Azure Synapse Analytics, the Query Store can be enabled as on other platforms but additional configuration options aren't supported.

<result_set_caching_option> ::=

Applies to: Azure Synapse Analytics

Controls whether query result is cached in the database.

RESULT_SET_CACHING { ON | OFF }

This command must be run while connected to the master database. Change to this database setting takes effect immediately. Storage costs are incurred by caching query result sets. After disabling result caching for a database, the previously persisted result cache is immediately deleted from Azure Synapse storage.

Run this command to check a database's result set caching configuration. If result set caching is turned ON, is_result_set_caching_on returns 1.

SELECT name, is_result_set_caching_on FROM sys.databases
WHERE name = <'Your_Database_Name'>

Run this command to check if a query was executed using cached result. The result_cache_hit column returns 1 for cache hit, 0 for cache miss, and negative values for reasons why result set caching wasn't used. Check sys.dm_pdw_exec_requests for details.

SELECT request_id, command, result_cache_hit FROM sys.dm_pdw_exec_requests
WHERE request_id = <'Your_Query_Request_ID'>

Note

Result set caching should not be used in conjunction with DECRYPTBYKEY. If this cryptographic function must be used, ensure you have result set caching disabled (either at session-level or database-level) at the time of execution.

Important

The operations to create result set cache and retrieve data from the cache happen on the control node of a data warehouse instance. When result set caching is turned ON, running queries that return large result set (for example, >1 million rows) can cause high CPU usage on the control node and slow down the overall query response on the instance. Those queries are commonly used during data exploration or ETL operations. To avoid stressing the control node and cause performance issue, users should turn OFF result set caching on the database before running those types of queries.

For details on performance tuning with result set caching, check Performance tuning guidance.

Permissions

To set the RESULT_SET_CACHING option, a user needs server-level principal login (the one created by the provisioning process) or be a member of the dbmanager database role.

<snapshot_option> ::=

Applies to: Azure Synapse Analytics

Controls the transaction isolation level of a database.

READ_COMMITTED_SNAPSHOT { ON | OFF }

This command must be run while connected to the master database. Turning READ_COMMITTED_SNAPSHOT ON or OFF for a user database kills all open connections to this database. You should make this change during a database maintenance window or wait until there's no active connection to the database except for the connection running the ALTER DATABASE command. The database doesn't have to be in single-user mode. Changing READ_COMMITTED_SNAPSHOT setting at session level isn't supported. To verify this setting for a database, check the is_read_committed_snapshot_on column in sys.databases.

In a database with READ_COMMITTED_SNAPSHOT enabled, queries can experience slower performance due to the scan of versions if multiple data versions are present. Long-open transactions can also cause an increase in the size of the database. This issue occurs if there are data changes by these transactions that block version cleanup.

Permissions

To set the READ_COMMITTED_SNAPSHOT option, a user needs ALTER permission on the database.

Examples Check statistics setting for a database
SELECT name, is_auto_create_stats_on FROM sys.databases
Enable Query Store for a database
ALTER DATABASE [database_name]
SET QUERY_STORE = ON;
Enable result set caching for a database
-- Run this command when connecting to the MASTER database

ALTER DATABASE [database_name]
SET RESULT_SET_CACHING ON;
Check result set caching setting for a database
SELECT name, is_result_set_caching_on
FROM sys.databases;
Enable the Read_Committed_Snapshot option for a database

Run this command when connecting to the master database.

ALTER DATABASE MyDatabase
SET READ_COMMITTED_SNAPSHOT ON;

SQL Server

SQL Database

SQL Managed Instance

Azure Synapse
Analytics

Microsoft Fabric

Microsoft Fabric

Use ALTER DATABASE ... SET to manage a Microsoft Fabric Warehouse.

Syntax
-- Microsoft Fabric Data Warehouse

ALTER DATABASE { warehouse_name | CURRENT }
SET
{
    <option_spec> [ ,...n ] 
}

<option_spec> ::=
{
    <data_lake_log_publishing>
  | <vorder>
  | <timestamp>
  | <result_set_caching>
}
;

<data_lake_log_publishing> ::=
{
    DATA_LAKE_LOG_PUBLISHING { PAUSED | AUTO }
}

<vorder> ::=
{
    VORDER = OFF
}

<timestamp> ::=
{
    TIMESTAMP = {CURRENT_TIMESTAMP | 'YYYY-MM-DDTHH:MM:SS.SS' }  
}


<result_set_caching> ::=
{    
    RESULT_SET_CACHING { ON | OFF } 
}
Arguments DATA_LAKE_LOG_PUBLISHING

Pauses or resumes Delta Lake log publishing. For more information, see Delta Lake log publishing.

VORDER

Can disable V-Order behavior. For more information, see disabling V-Order behavior in a warehouse.

TIMESTAMP

Updates the timestamp for an existing warehouse snapshot in Fabric Data Warehouse. The timestamp must be provided in UTC time zone. For more information, see Warehouse snapshots.

RESULT_SET_CACHING

Enables or disables result set caching (preview) for the current item. For more information, see Result set caching.

Permissions

The user needs to be a member of the Admin, Member, or Contributor roles in the Fabric workspace.

Examples A. Pausing the publishing of Delta Lake Logs

The following T-SQL command pauses Delta Lake Log publishing in the current warehouse context.

ALTER DATABASE CURRENT SET DATA_LAKE_LOG_PUBLISHING = PAUSED;

To check the current status of Delta Lake Log publishing on all warehouses, of your workspace, use the following T-SQL code to query sys.databases in a new query window:

SELECT [name], [DATA_LAKE_LOG_PUBLISHING_DESC] FROM sys.databases;
B. Set and check result set caching (preview)

The following T-SQL command will enable the item MyDataWarehouse to begin creating and applying result set cache (preview) to applicable SELECT queries. For more information, see Result set caching.

ALTER DATABASE [MyDataWarehouse] SET RESULT_SET_CACHING ON;

The column is_result_set_caching_on from sys.databases can then be checked to confirm that result set caching (preview) has been enabled.

SELECT [name], [is_result_set_caching_on] FROM sys.databases;

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4