## 1. Project Overview & Quickstart (pingcap/TEMPLATE)

# TEMPLATE

Open-source repository pingcap/TEMPLATE

### Repository Details
- **Repository:** [pingcap/TEMPLATE](https://github.com/pingcap/TEMPLATE)
- **Primary Language:** Code

*Note: High-volume repository documentation is actively indexed and synchronized by YakaAI.*

## 2. Official Technical Reference & Guides (pingcap/docs)

## File: README.md

# TiDB Documentation

Welcome to TiDB documentation!

This repository stores all the source files of [TiDB Docs at the PingCAP website](https://docs.pingcap.com/tidb/stable), while the [pingcap/docs-cn](https://github.com/pingcap/docs-cn) repository stores all the source files of [TiDB Documentation in Chinese](https://docs.pingcap.com/zh/tidb/stable).

If you find documentation issues, feel free to [create an Issue](https://github.com/pingcap/docs/issues/new/choose) to let us know or directly [create a Pull Request](/CONTRIBUTING.md#how-to-contribute) to help fix or update it.

If you want to locally customize and output TiDB documentation in PDF format to meet the needs of specific scenarios, such as freely sorting or deleting certain contents in TiDB documentation, please refer to [TiDB Documentation PDF Generation Tutorial](/resources/tidb-pdf-generation-tutorial.md).

Currently, the official documentation supports two languages:

- `en`: [documentation in English](https://docs.pingcap.com/tidb/stable)
- `zh`: [documentation in Chinese](https://docs.pingcap.com/zh/tidb/stable)

You can use Google Translate to view the documentation in different languages. For example:

- `fr`: [documentation in French](https://docs-pingcap-com.translate.goog/tidb/stable?_x_tr_sl=auto&_x_tr_tl=fr&_x_tr_hl=en&_x_tr_pto=wapp&_x_tr_hist=true)
- `ja`: [documentation in Japanese](https://docs-pingcap-com.translate.goog/tidb/stable?_x_tr_sl=auto&_x_tr_tl=ja&_x_tr_hl=en&_x_tr_pto=wapp&_x_tr_hist=true)
- `ko`: [documentation in Korean](https://docs-pingcap-com.translate.goog/tidb/stable?_x_tr_sl=auto&_x_tr_tl=ko&_x_tr_hl=en&_x_tr_pto=wapp&_x_tr_hist=true)
- `de`: [documentation in German](https://docs-pingcap-com.translate.goog/tidb/stable?_x_tr_sl=auto&_x_tr_tl=de&_x_tr_hl=en&_x_tr_pto=wapp&_x_tr_hist=true)
- `es`: [documentation in Spanish](https://docs-pingcap-com.translate.goog/tidb/stable?_x_tr_sl=auto&_x_tr_tl=es&_x_tr_hl=en&_x_tr_pto=wapp&_x_tr_hist=true)

## Documentation versions

Currently, we maintain the following versions of TiDB documentation in different branches:

| Branch name | TiDB docs version |
| :---------|:----------|
| [`master`](https://github.com/pingcap/docs/tree/master) | The latest development version |
| [`release-8.5`](https://github.com/pingcap/docs/tree/release-8.5) | 8.5 LTS (Long-Term Support) |
| [`release-8.4`](https://github.com/pingcap/docs/tree/release-8.4) | 8.4 Development Milestone Release (Archived documentation, no longer updated) |
| [`release-8.3`](https://github.com/pingcap/docs/tree/release-8.3) | 8.3 Development Milestone Release (Archived documentation, no longer updated) |
| [`release-8.2`](https://github.com/pingcap/docs/tree/release-8.2) | 8.2 Development Milestone Release (Archived documentation, no longer updated) |
| [`release-8.1`](https://github.com/pingcap/docs/tree/release-8.1) | 8.1 LTS (Long-Term Support) |
| [`release-8.0`](https://github.com/pingcap/docs/tree/release-8.0) | 8.0 Development Milestone Release (Archived documentation, no longer updated) |
| [`release-7.6`](https://github.com/pingcap/docs/tree/release-7.6) | 7.6 Development Milestone Release (Archived documentation, no longer updated) |
| [`release-7.5`](https://github.com/pingcap/docs/tree/release-7.5) | 7.5 LTS (Long-Term Support) |
| [`release-7.4`](https://github.com/pingcap/docs/tree/release-7.4) | 7.4 Development Milestone Release (Archived documentation, no longer updated) |
| [`release-7.3`](https://github.com/pingcap/docs/tree/release-7.3) | 7.3 Development Milestone Release (Archived documentation, no longer updated) |
| [`release-7.2`](https://github.com/pingcap/docs/tree/release-7.2) | 7.2 Development Milestone Release (Archived documentation, no longer updated) |
| [`release-7.1`](https://github.com/pingcap/docs/tree/release-7.1) | 7.1 LTS (Long-Term Support) version |
| [`release-7.0`](https://github.com/pingcap/docs/tree/release-7.0) | 7.0 Development Milestone Release (Archived documentation, no longer updated) |
| [`release-6.6`](https://github.com/pingcap/docs/tree/release-6.6) | 6.6 Development Milestone Release (Archived documentation, no longer updated) |
| [`release-6.5`](https://github.com/pingcap/docs/tree/release-6.5) | 6.5 LTS (Long-Term Support) version |
| [`release-6.4`](https://github.com/pingcap/docs/tree/release-6.4) | 6.4 Development Milestone Release (Archived documentation, no longer updated) |
| [`release-6.3`](https://github.com/pingcap/docs/tree/release-6.3) | 6.3 Development Milestone Release (Archived documentation, no longer updated) |
| [`release-6.2`](https://github.com/pingcap/docs/tree/release-6.2) | 6.2 Development Milestone Release (Archived documentation, no longer updated) |
| [`release-6.1`](https://github.com/pingcap/docs/tree/release-6.1) | 6.1 LTS (Long-Term Support) version (Archived documentation, no longer updated) |
| [`release-6.0`](https://github.com/pingcap/docs/tree/release-6.0) | 6.0 Development Milestone Release (Archived documentation, no longer updated) |
| [`release-5.4`](https://github.com/pingcap/docs/tree/release-5.4) | 5.4 stable version (Archived documentation, no longer updated) |
| [`release-5.3`](https://github.com/pingcap/docs/tree/release-5.3) | 5.3 stable version (Archived documentation, no longer updated) |
| [`release-5.2`](https://github.com/pingcap/docs/tree/release-5.2) | 5.2 stable version (Archived documentation, no longer updated) |
| [`release-5.1`](https://github.com/pingcap/docs/tree/release-5.1) | 5.1 stable version (Archived documentation, no longer updated) |
| [`release-5.0`](https://github.com/pingcap/docs/tree/release-5.0) | 5.0 stable version (Archived documentation, no longer updated) |
| [`release-4.0`](https://github.com/pingcap/docs/tree/release-4.0) | 4.0 stable version (Archived documentation, no longer updated) |
| [`release-3.1`](https://github.com/pingcap/docs/tree/release-3.1) | 3.1 stable version (Archived documentation, no longer updated) |
| [`release-3.0`](https://github.com/pingcap/docs/tree/release-3.0) | 3.0 stable version (Archived documentation, no longer updated) |
| [`release-2.1`](https://github.com/pingcap/docs/tree/release-2.1) | 2.1 stable version (Archived documentation, no longer updated) |

## Contributing

[](https://github.com/pingcap/docs/blob/master/credits.md)

See [TiDB Documentation Contributing Guide](/CONTRIBUTING.md) to become a contributor! 🤓

<a href="https://next.ossinsight.io/widgets/official/compose-recent-active-contributors?repo_id=63995402&limit=30" target="_blank" style="display: block;" align="center">
  
    
    
  
</a>

## License

All documentation starting from TiDB v7.0 is available under the terms of [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/).

---

## File: _docHome.md

---
title: Home
hide_sidebar: true
hide_commit: true
hide_leftNav: true
summary: TiDB Documentation provides how-to guides and references for using TiDB Cloud and TiDB Self-Managed, including data migration and application building. TiDB Cloud is a fully-managed Database-as-a-Service, offering easy access to the power of a cloud-native, distributed SQL database. TiDB is an open-source distributed SQL database with MySQL compatibility, horizontal scalability, and high availability. Developers can access documentation for application development and explore additional resources such as TiDB Playground, PingCAP Education, and community engagement opportunities.
---

<DocHomeContainer title="TiDB Documentation" subTitle="Explore how-to guides and references to get started with TiDB Cloud and TiDB Self-Managed, migrate data smoothly, and build applications with ease." ctaLabel="Start TiDB Cloud for Free" ctaLink="https://tidbcloud.com/free-trial">

<DocHomeSection label="TiDB Cloud" anchor="tidb-cloud" id="tidb-cloud">

TiDB Cloud is a fully-managed Database-as-a-Service (DBaaS) that brings everything great about TiDB to your cloud, letting you focus on your applications instead of the complexities of your database.

<DocHomeCardContainer>

<DocHomeCard href="/tidbcloud/tidb-cloud-intro" label="What is TiDB Cloud" icon="cloud-product-mauve">

Learn what TiDB Cloud is as an easy-to-use database and its key features.

</DocHomeCard>

<DocHomeCard href="/tidbcloud/tidb-cloud-quickstart" label="Get started with TiDB Cloud" icon="cloud-getstarted-mauve">

Guide for an easy way to get started with TiDB Cloud.

</DocHomeCard>

<DocHomeCard href="/developer/" label="Developer Guide" icon="cloud-developer-mauve">

Connect your application with the languages and frameworks you prefer.

</DocHomeCard>

<DocHomeCard href="/ai/vector-search-overview" label="Vector Search (Beta)" icon="cloud-vector-mauve">

Explore native support of Vector Search in TiDB Cloud to build your AI application.

</DocHomeCard>

</DocHomeCardContainer>

</DocHomeSection>

<DocHomeSection label="TiDB Self-Managed" anchor="tidb-self-managed" id="tidb-self-managed">



TiDB is an open-source distributed SQL database that supports Hybrid Transactional and Analytical Processing (HTAP) workloads. It is MySQL compatible and features horizontal scalability, strong consistency, and high availability. You can deploy TiDB in a self-hosted environment or on the cloud.

<DocHomeCardContainer>

<DocHomeCard href="/tidb/stable/overview" label="What is TiDB Self-Managed" icon="oss-product-blue">

Learn what is TiDB Self-Managed and its key features.

</DocHomeCard>

<DocHomeCard href="/tidb/stable/quick-start-with-tidb" label="Get started with TiDB Self-Managed" icon="oss-getstarted-blue">

Walks you through the quickest way to get started with TiDB Self-Managed.

</DocHomeCard>

<DocHomeCard href="/tidb/stable/production-deployment-using-tiup" label="Deploy a Local TiDB Cluster" icon="oss-deploy-blue">

Learn how to deploy TiDB locally in a production environment.

</DocHomeCard>

<DocHomeCard href="/developer/" label="Developer Guide" icon="oss-developer-blue">

Connect your application with the languages and frameworks you prefer.

</DocHomeCard>

<DocHomeCard href="/tidb/stable/mysql-compatibility" label="MySQL Compatibility" icon="oss-mysql-blue">

TiDB is highly compatible with the MySQL protocol and the common features and syntax of MySQL 8.x.

</DocHomeCard>

</DocHomeCardContainer>

The open-source TiDB platform is released under the Apache 2.0 license and is supported by the community. [View on GitHub](https://github.com/pingcap/tidb)

</DocHomeSection>

<DocHomeSection label="More Resources" anchor="resources" id="resources">

<DocHomeCardContainer>

<DocHomeCard href="https://www.pingcap.com/education/" label="Learning Center" icon="global-tidb-education">

Learn TiDB Cloud and TiDB Self-Managed through well-designed online courses and instructor-led training.

</DocHomeCard>

<DocHomeCard href="https://www.pingcap.com/blog/" label="Blog" icon="global-tidb-blog">

Read great articles about TiDB Cloud and TiDB Self-Managed.

</DocHomeCard>

<DocHomeCard href="https://www.pingcap.com/event/" label="Events" icon="global-tidb-events">

Learn about events hosted by PingCAP and the community.

</DocHomeCard>

<DocHomeCard href="https://www.pingcap.com/ebook-whitepaper/" label="eBooks & Papers" icon="global-tidb-ebook">

Download eBooks and papers.

</DocHomeCard>

<DocHomeCard href="https://www.pingcap.com/videos/" label="Videos" icon="global-tidb-video">

Watch a compilation of short videos describing TiDB and various use cases.

</DocHomeCard>

<DocHomeCard href="https://ossinsight.io/" label="OSS Insight" icon="global-tidb-ossinsight">

A powerful insight tool that provides in-depth analysis of any GitHub repository, powered by TiDB Cloud.

</DocHomeCard>

<DocHomeCard href="https://play.tidbcloud.com/?utm_source=docs&utm_medium=home_more_resources" label="Playground" icon="global-tidb-playground">

Experience the capabilities of TiDB without registration.

</DocHomeCard>

<DocHomeCard href="https://discord.gg/DQZ2dy3cuc?utm_source=doc" label="Join our community on Discord" icon="global-tidb-discord" colspan="2" actionBtnLabel="Join Community" ctaGraphic="global-iso-hand">

Join us on Discord or become a contributor.

</DocHomeCard>

</DocHomeCardContainer>

</DocHomeSection>

</DocHomeContainer>

---

## File: _index.md

---
title: TiDB Self-Managed
aliases: ['/docs/dev/', '/docs/dev/adopters/', '/tidb/dev/adopters']
hide_sidebar: true
hide_commit: true
summary: TiDB is an open-source distributed SQL database that supports Hybrid Transactional and Analytical Processing (HTAP) workloads. The guide provides information on features, TiFlash, development, deployment, migration, maintenance, monitoring, tuning, tools, and references. It covers everything from quick start to advanced configurations and tools for TiDB.
---

<LearningPathContainer platform="tidb" title="TiDB Self-Managed" subTitle="TiDB is an open-source distributed SQL database that supports Hybrid Transactional and Analytical Processing (HTAP) workloads. Find the guide, samples, and references you need to use TiDB.">



<LearningPath label="Learn" icon="cloud1">

[What is TiDB Self-Managed](https://docs.pingcap.com/tidb/dev/overview)

[Features](https://docs.pingcap.com/tidb/dev/basic-features)

[TiFlash](https://docs.pingcap.com/tidb/dev/tiflash-overview)

</LearningPath>

<LearningPath label="Try" icon="cloud5">

[Try Out TiDB Self-Managed](https://docs.pingcap.com/tidb/dev/quick-start-with-tidb)

[Try Out HTAP](https://docs.pingcap.com/tidb/dev/quick-start-with-htap)

[Import Example Database](https://docs.pingcap.com/tidb/dev/import-example-data)

</LearningPath>

<LearningPath label="Develop" icon="doc8">

[Developer Guide Overview](https://docs.pingcap.com/developer/)

[Quick Start](https://docs.pingcap.com/developer/dev-guide-build-cluster-in-cloud/)

[Connect to TiDB](https://docs.pingcap.com/developer/dev-guide-connect-to-tidb/)

</LearningPath>

<LearningPath label="Deploy" icon="deploy">

[Software and Hardware Requirements](https://docs.pingcap.com/tidb/dev/hardware-and-software-requirements)

[Deploy a TiDB Cluster Using TiUP](https://docs.pingcap.com/tidb/dev/production-deployment-using-tiup)

[Deploy a TiDB Cluster on Kubernetes](https://docs.pingcap.com/tidb-in-kubernetes/stable)

</LearningPath>

<LearningPath label="Migrate" icon="cloud3">

[Migration Overview](https://docs.pingcap.com/tidb/dev/migration-overview)

[Migration Tools](https://docs.pingcap.com/tidb/dev/migration-tools)

[Typical Scenarios](https://docs.pingcap.com/tidb/dev/migrate-aurora-to-tidb)

</LearningPath>

<LearningPath label="Maintain" icon="maintain">

[Upgrade a Cluster](https://docs.pingcap.com/tidb/dev/upgrade-tidb-using-tiup)

[Scale a Cluster](https://docs.pingcap.com/tidb/dev/scale-tidb-using-tiup)

[Back Up and Restore Cluster Data](https://docs.pingcap.com/tidb/dev/backup-and-restore-overview)

[Daily Check](https://docs.pingcap.com/tidb/dev/daily-check)

[Maintain TiDB Using TiUP](https://docs.pingcap.com/tidb/dev/maintain-tidb-using-tiup)

</LearningPath>

<LearningPath label="Monitor" icon="cloud6">

[Use Prometheus, Grafana, and TiDB Dashboard](https://docs.pingcap.com/tidb/dev/tidb-monitoring-framework)

[Monitoring API](https://docs.pingcap.com/tidb/dev/tidb-monitoring-api)

[Alert Rules](https://docs.pingcap.com/tidb/dev/alert-rules)

</LearningPath>

<LearningPath label="Tune" icon="tidb-cloud-tune">

[Tuning Overview](https://docs.pingcap.com/tidb/dev/performance-tuning-overview)

[Tuning Methods](https://docs.pingcap.com/tidb/dev/performance-tuning-methods)

[Tune OLTP Performance](https://docs.pingcap.com/tidb/dev/performance-tuning-practices)

[Tune Operating System](https://docs.pingcap.com/tidb/dev/tune-operating-system)

[Tune Configurations](https://docs.pingcap.com/tidb/dev/configure-memory-usage)

[Tune SQL Performance](https://docs.pingcap.com/tidb/dev/sql-tuning-overview)

</LearningPath>

<LearningPath label="Tools" icon="doc7">

[TiUP](https://docs.pingcap.com/tidb/dev/tiup-overview)

[TiDB Operator](https://docs.pingcap.com/tidb/dev/tidb-operator-overview)

[TiDB Data Migration (DM)](https://docs.pingcap.com/tidb/dev/dm-overview)

[TiDB Lightning](https://docs.pingcap.com/tidb/dev/tidb-lightning-overview)

[Dumpling](https://docs.pingcap.com/tidb/dev/dumpling-overview)

[TiCDC](https://docs.pingcap.com/tidb/dev/ticdc-overview)

[Backup & Restore (BR)](https://docs.pingcap.com/tidb/dev/backup-and-restore-overview)

[PingCAP Clinic](https://docs.pingcap.com/tidb/dev/clinic-introduction)

</LearningPath>

<LearningPath label="Reference" icon="cloud-dev">

[TiDB Configuration File Parameters](https://docs.pingcap.com/tidb/dev/tidb-configuration-file)

[TiDB Command-line Flags](https://docs.pingcap.com/tidb/dev/command-line-flags-for-tidb-configuration)

[TiDB Control](https://docs.pingcap.com/tidb/dev/tidb-control)

[System Variables](https://docs.pingcap.com/tidb/dev/system-variables)

[Release Notes](https://docs.pingcap.com/releases/tidb-self-managed)

[FAQ Summary](https://docs.pingcap.com/tidb/dev/faq-overview)

</LearningPath>

</LearningPathContainer>

---

## File: accelerated-table-creation.md

---
title: TiDB Accelerated Table Creation
summary: Learn the concept, principles, and implementation details of performance optimization for creating tables in TiDB.
aliases: ['/tidb/dev/ddl-v2/']
---

# TiDB Accelerated Table Creation

TiDB v7.6.0 introduces the system variable [`tidb_ddl_version`](https://docs-archive.pingcap.com/tidb/v7.6/system-variables/#tidb_ddl_version-new-in-v760) to support accelerating table creation, which improves the efficiency of bulk table creation. Starting from v8.0.0, this system variable is renamed to [`tidb_enable_fast_create_table`](/system-variables.md#tidb_enable_fast_create_table-new-in-v800).

When accelerated table creation is enabled via [`tidb_enable_fast_create_table`](/system-variables.md#tidb_enable_fast_create_table-new-in-v800), table creation statements with the same schema committed to the same TiDB node at the same time are merged into batch table creation statements to improve table creation performance. Therefore, to improve the table creation performance, try to connect to the same TiDB node, create tables with the same schema concurrently, and increase the concurrency appropriately.

The merged batch table creation statements are executed within the same transaction, so if one statement of them fails, all of them will fail.

## Compatibility with TiDB tools

- Before TiDB v8.3.0, [TiCDC](https://docs.pingcap.com/tidb/stable/ticdc-overview) does not support replicating the tables that are created by `tidb_enable_fast_create_table`. Starting from v8.3.0, TiCDC can properly replicate these tables.

## Limitation

You can now use performance optimization for table creation only in the [`CREATE TABLE`](/sql-statements/sql-statement-create-table.md) statement, and this statement must not include any foreign key constraints.

## Use `tidb_enable_fast_create_table` to accelerate table creation

You can enable or disable performance optimization for creating tables by specifying the value of the system variable [`tidb_enable_fast_create_table`](/system-variables.md#tidb_enable_fast_create_table-new-in-v800).

Starting from TiDB v8.5.0, the accelerated table creation feature is enabled by default for newly created clusters, with `tidb_enable_fast_create_table` set to `ON`. For clusters upgraded from v8.4.0 or earlier versions, the default value of `tidb_enable_fast_create_table` remains unchanged.

To enable performance optimization for creating tables, set the value of this variable to `ON`:

```sql
SET GLOBAL tidb_enable_fast_create_table = ON;
```

To disable performance optimization for creating tables, set the value of this variable to `OFF`:

```sql
SET GLOBAL tidb_enable_fast_create_table = OFF;
```

---

## File: AGENTS.md

# Repository Agents Guide

This repository is the source for the English TiDB documentation maintained in `pingcap/docs`.

Use this file as the entrypoint for agent work in this repository.

## Working approach

Before making changes:

1. Use `.agents/README.md` as the map of the repo-local AI guidance.
2. Read the relevant shared guidance in `.agents/shared/`.
3. Use a matching skill in `.agents/skills/` when the task is workflow-specific.
4. Keep edits minimal and scoped to the requested task.
5. Reuse existing wording, structure, and terminology unless there is a clear reason to change them.

When rules conflict, follow this priority order:

1. Direct user instructions
2. Repository rules in this file
3. Task-specific instructions in the selected skill
4. Shared guidance in `.agents/shared/`
5. General writing preferences

## Start here

Read `.agents/README.md` first when you need the current layout of repo-local AI guidance.

Then read the shared guidance in `.agents/shared/` before making changes:

- `.agents/README.md`
- `.agents/shared/repo-conventions.md`
- `.agents/shared/writing-style.md`
- `.agents/shared/translation-rules.md` when the task involves EN -> ZH translation
- `.agents/shared/translation-terms.md` when the task involves terminology decisions for translation

Use `resources/terms.md` when additional product terminology context is needed.

## Use the repo skills

Use the workflow-specific skills in `.agents/skills/` when they match the task:

- `review-doc-pr`: review Markdown diffs, doc PRs, wording, structure, factual accuracy, and possible cross-file impact
- `create-or-update-zh-translation-pr`: create or update an EN -> ZH translation PR that maps an English docs change or incremental source update to `pingcap/docs-cn`, using the bundled scripts in `.agents/skills/create-or-update-zh-translation-pr/scripts/` when applicable
- `write-update-tidb-docs`: write new TiDB documentation or update existing documentation based on code PRs from `pingcap/tidb` or other TiDB ecosystem repositories, issues, design docs, or feature descriptions
- `docs-pr-metadata-guard`: guard PR template structure when creating or editing pull requests — version checkboxes, required sections, HTML comments, related-link fields, and cherry-pick conventions
- `docs-issue-metadata-guard`: guard issue template structure when creating or editing issues — template selection, required fields, scope boundaries, and label hygiene

If no existing skill matches the task, follow this file plus the shared guidance and keep the change narrowly scoped.

## Repository expectations

- Prefer the existing templates in `resources/doc-templates/` when creating new documents or reshaping existing ones.
- Preserve the repository's Markdown, heading, list, link, and front matter conventions.
- Use lowercase file names and separate words with hyphens, for example, `x-y-z.md`, unless the existing file path already follows a different required pattern.
- Reuse existing approved terminology and phrasing whenever possible.
- Prefer consistency with surrounding documents over stylistic rewrites.
- Respect the repository's version and branch rules, including release branches and TiDB Cloud branch constraints.
- Prefer existing scripts, workflows, and repository patterns over ad hoc reinvention.
- When a selected skill includes bundled scripts, prefer those scripts over rewriting the same workflow inline.

## Content guardrails

- Do not change technical meaning unless the task explicitly requires it.
- Do not silently rewrite commands, code samples, configuration names, API fields, UI strings, or JSON unless they are part of the requested task or are clearly incorrect.
- Do not expand the scope from a local fix into a broad rewrite unless the user asks for that.
- Do not introduce new terminology when an established term already exists in the repository or shared terminology references.
- When editing translated-content workflows, preserve existing English source intent and terminology rather than paraphrasing freely.

## Translation-related guardrails

When the task involves translation or translation review:

- Follow `.agents/shared/translation-rules.md` and `.agents/shared/translation-terms.md`.
- For translation PR creation or update workflows, prefer the script-backed process in `.agents/skills/create-or-update-zh-translation-pr/`.
- Prefer updating the existing translation with the smallest necessary change instead of retranslating entire sections.
- Preserve structure, headings, lists, code blocks, links, and note/admonition semantics.
- Reuse existing translated terminology when it is still correct.
- Flag terminology uncertainty explicitly instead of guessing.

## Validation

When the task changes Markdown, run relevant checks when practical:

- `./scripts/markdownlint <files>`
- `./scripts/verify-links.sh` for link-sensitive changes

If a full-repo check is too expensive for the task, validate only the files you changed.

## Commit and PR boundaries

- Do not commit, push, create branches, or open PRs unless the user explicitly asks for it.
- Before any write action that affects Git history or GitHub state, make sure the requested scope is clear.
- When reporting completed work, summarize changed files, key decisions, and any issues that still need human review.

## Scope discipline

Keep changes scoped to the requested task and avoid mutating unrelated files.

When a requested change might affect other docs, note the possible cross-file impact and only update additional files when the user asks or the selected skill explicitly requires it.

---

## File: agg-distinct-optimization.md

---
title: Distinct Optimization
summary: Introduce the `distinct` optimization in the TiDB query optimizer.
---

# Distinct Optimization

This document introduces the `distinct` optimization in the TiDB query optimizer, including `SELECT DISTINCT` and `DISTINCT` in the aggregate functions.

## `DISTINCT` modifier in `SELECT` statements

The `DISTINCT` modifier specifies removal of duplicate rows from the result set. `SELECT DISTINCT` is transformed to `GROUP BY`, for example:

```sql
mysql> explain SELECT DISTINCT a from t;
+--------------------------+---------+-----------+---------------+-------------------------------------------------------+
| id                       | estRows | task      | access object | operator info                                         |
+--------------------------+---------+-----------+---------------+-------------------------------------------------------+
| HashAgg_6                | 2.40    | root      |               | group by:test.t.a, funcs:firstrow(test.t.a)->test.t.a |
| └─TableReader_11         | 3.00    | root      |               | data:TableFullScan_10                                 |
|   └─TableFullScan_10     | 3.00    | cop[tikv] | table:t       | keep order:false, stats:pseudo                        |
+--------------------------+---------+-----------+---------------+-------------------------------------------------------+
3 rows in set (0.00 sec)
```

## `DISTINCT` option in aggregate functions

Usually, aggregate functions with the `DISTINCT` option is executed in the TiDB layer in a single-threaded execution model.

<CustomContent platform="tidb">

The [`tidb_opt_distinct_agg_push_down`](/system-variables.md#tidb_opt_distinct_agg_push_down) system variable or the [`distinct-agg-push-down`](/tidb-configuration-file.md#distinct-agg-push-down) configuration item in TiDB controls whether to rewrite the distinct aggregate queries and push them to the TiKV or TiFlash Coprocessor.

</CustomContent>

<CustomContent platform="tidb-cloud">

The [`tidb_opt_distinct_agg_push_down`](/system-variables.md#tidb_opt_distinct_agg_push_down) system variable in TiDB controls whether to rewrite the distinct aggregate queries and push them to the TiKV or TiFlash Coprocessor.

</CustomContent>

Take the following queries as an example of this optimization. `tidb_opt_distinct_agg_push_down` is disabled by default, which means the aggregate functions are executed in the TiDB layer. After enabling this optimization by setting its value to `1`, the `distinct a` part of `count(distinct a)` is pushed to TiKV or TiFlash Coprocessor: there is a HashAgg_5 to remove the duplicated values on column a in the TiKV Coprocessor. It might reduce the computation overhead of `HashAgg_8` in the TiDB layer.

```sql
mysql> desc select count(distinct a) from test.t;
+-------------------------+----------+-----------+---------------+------------------------------------------+
| id                      | estRows  | task      | access object | operator info                            |
+-------------------------+----------+-----------+---------------+------------------------------------------+
| StreamAgg_6             | 1.00     | root      |               | funcs:count(distinct test.t.a)->Column#4 |
| └─TableReader_10        | 10000.00 | root      |               | data:TableFullScan_9                     |
|   └─TableFullScan_9     | 10000.00 | cop[tikv] | table:t       | keep order:false, stats:pseudo           |
+-------------------------+----------+-----------+---------------+------------------------------------------+
3 rows in set (0.01 sec)

mysql> set session tidb_opt_distinct_agg_push_down = 1;
Query OK, 0 rows affected (0.00 sec)

mysql> desc select count(distinct a) from test.t;
+---------------------------+----------+-----------+---------------+------------------------------------------+
| id                        | estRows  | task      | access object | operator info                            |
+---------------------------+----------+-----------+---------------+------------------------------------------+
| HashAgg_8                 | 1.00     | root      |               | funcs:count(distinct test.t.a)->Column#3 |
| └─TableReader_9           | 1.00     | root      |               | data:HashAgg_5                           |
|   └─HashAgg_5             | 1.00     | cop[tikv] |               | group by:test.t.a,                       |
|     └─TableFullScan_7     | 10000.00 | cop[tikv] | table:t       | keep order:false, stats:pseudo           |
+---------------------------+----------+-----------+---------------+------------------------------------------+
4 rows in set (0.00 sec)
```

---

## File: alert-rules.md

---
title: TiDB Cluster Alert Rules
summary: Learn the alert rules in a TiDB cluster.
aliases: ['/docs/dev/alert-rules/','/docs/dev/reference/alert-rules/']
---



# TiDB Cluster Alert Rules

This document describes the alert rules for different components in a TiDB cluster, including the rule descriptions and solutions of the alert items in TiDB, TiKV, PD, TiFlash, TiCDC, Node_exporter and Blackbox_exporter.

According to the severity level, alert rules are divided into three categories (from high to low): emergency-level, critical-level, and warning-level. This division of severity levels applies to all alert items of each component below.

|  Severity level |  Description   |
| :-------- | :----- |
|  Emergency-level  |  The highest severity level at which the service is unavailable. Emergency-level alerts are often caused by a service or node failure. **Manual intervention is required immediately**. |
|  Critical-level  |  Decreased service availability. For the critical-level alerts, a close watch on the abnormal metrics is required. |
|  Warning-level  |  Warning-level alerts are a reminder for an issue or error.   |

## TiDB alert rules

This section gives the alert rules for the TiDB component.

### Emergency-level alerts

#### `TiDB_schema_error`

* Alert rule:

    `increase(tidb_session_schema_lease_error_total{type="outdated"}[15m]) > 0`

* Description:

    The latest schema information is not reloaded in TiDB within one lease. When TiDB fails to continue providing services, an alert is triggered.

* Solution:

    It is often caused by an unavailable Region or a TiKV timeout. You need to locate the issue by checking the TiKV monitoring items.

#### `TiDB_tikvclient_region_err_total`

* Alert rule:

    `increase(tidb_tikvclient_region_err_total[10m]) > 6000`

* Description:

    TiDB server accesses the Region leader of TiKV according to its own cache information. If the Region leader has changed or the current TiKV Region information is inconsistent with that in the TiDB cache, a Region cache error occurs. When the error is reported over 6000 times in 10 minutes, an alert is triggered.

* Solution:

    View [**TiKV-Details** > **Cluster** dashboard](/grafana-tikv-dashboard.md#cluster) to see if the leader is balanced.

#### `TiDB_domain_load_schema_total`

* Alert rule:

    `increase(tidb_domain_load_schema_total{type="failed"}[10m]) > 10`

* Description:

    The total number of failures to reload the latest schema information in TiDB. If the reloading failure occurs over 10 times in 10 minutes, an alert is triggered.

* Solution:

    Same as [`TiDB_schema_error`](#tidb_schema_error).

### Critical-level alerts

#### `TiDB_server_panic_total`

* Alert rule:

    `increase(tidb_server_panic_total[10m]) > 0`

* Description:

    The number of panicked TiDB threads. When a panic occurs, an alert is triggered. The thread is often recovered, otherwise, TiDB will frequently restart.

* Solution:

    Collect the panic logs to locate the issue.

### Warning-level alerts

#### `TiDB_memory_abnormal`

* Alert rule:

    `go_memstats_heap_inuse_bytes{job="tidb"} > 1e+10`

* Description:

    The monitoring on the TiDB memory usage. If the usage exceeds 10 G, an alert is triggered.

* Solution:

    Use the HTTP API to troubleshoot the goroutine leak issue.

#### `TiDB_query_duration`

* Alert rule:

    `histogram_quantile(0.99, sum(rate(tidb_server_handle_query_duration_seconds_bucket[1m])) BY (le, instance)) > 1`

* Description:

    The latency of handling a request in TiDB. The response time for 99% of requests should be within 1 second; otherwise, an alert is triggered.

* Solution:

    View TiDB logs and search for the `SLOW_QUERY` and `TIME_COP_PROCESS` keywords to locate the slow SQL queries.

#### `TiDB_server_event_error`

* Alert rule:

    `increase(tidb_server_event_total{type=~"server_start|server_hang"}[15m]) > 0`

* Description:

    The number of events that happen in the TiDB service. An alert is triggered when the following events happen:

    1. start: The TiDB service starts.
    2. hang: When a critical-level event happens, TiDB enters the `hang` mode and waits to be killed manually.

* Solution:

    Restart TiDB to recover the service.

#### `TiDB_tikvclient_backoff_seconds_count`

* Alert rule:

    `increase(tidb_tikvclient_backoff_seconds_count[10m]) > 10`

* Description:

    The number of retries when TiDB fails to access TiKV. When the retry times is over 10 in 10 minutes, an alert is triggered.

* Solution:

    View the monitoring status of TiKV.

#### `TiDB_monitor_time_jump_back_error`

* Alert rule:

    `increase(tidb_monitor_time_jump_back_total[10m]) > 0`

* Description:

    When the time of the machine that holds TiDB rewinds, an alert is triggered.

* Solution:

    Troubleshoot the NTP configurations.

#### `TiDB_ddl_waiting_jobs`

* Alert rule:

    `sum(tidb_ddl_waiting_jobs) > 5`

* Description:

    When the number of DDL tasks pending for execution in TiDB exceeds 5, an alert is triggered.

* Solution:

    Check whether there is any time-consuming `add index` operation that is being executed by running `admin show ddl`.

## PD alert rules

This section gives the alert rules for the PD component.

### Emergency-level alerts

#### `PD_cluster_down_store_nums`

* Alert rule:

    `(sum(pd_cluster_status{type="store_down_count"}) by (instance) > 0) and (sum(etcd_server_is_leader) by (instance) > 0)`

* Description:

    PD has not received a TiKV/TiFlash heartbeat for a long time (the default configuration is 30 minutes).

* Solution:

    * Check whether the TiKV/TiFlash process is normal, the network is isolated or the load is too high, and recover the service as much as possible.
    * If the TiKV/TiFlash instance cannot be recovered, you can make it offline.

### Critical-level alerts

#### `PD_etcd_write_disk_latency`

* Alert rule:

    `histogram_quantile(0.99, sum(rate(etcd_disk_wal_fsync_duration_seconds_bucket[1m])) by (instance, job, le)) > 1`

* Description:

    If the latency of the fsync operation exceeds 1 second, it indicates that etcd writes data to disk at a lower speed than normal. It might lead to PD leader timeout or failure to store TSO on disk in time, which will shut down the service of the entire cluster.

* Solution:

    * Find the cause of slow writes. It might be other services that overload the system. You can check whether PD itself occupies a large amount of CPU or I/O resources.
    * Try to restart PD or manually transfer leader to another PD to recover the service.
    * If the problematic PD instance cannot be recovered due to environmental factors, make it offline and replace it.

#### `PD_miss_peer_region_count`

* Alert rule:

    `(sum(pd_regions_status{type="miss-peer-region-count"}) by (instance) > 100) and (sum(etcd_server_is_leader) by (instance) > 0)`

* Description:

    The number of Region replicas is smaller than the value of `max-replicas`.

* Solution:

    * Find the cause of the issue by checking whether there is any TiKV machine that is down or being made offline.
    * Watch the Region health panel and see whether `miss-peer-region-count` is continuously decreasing.

### Warning-level alerts

#### `PD_cluster_lost_connect_store_nums`

* Alert rule:

    `(sum(pd_cluster_status{type="store_disconnected_count"}) by (instance) > 0) and (sum(etcd_server_is_leader) by (instance) > 0)`

* Description:

    PD does not receive a TiKV/TiFlash heartbeat within 20 seconds. Normally a TiKV/TiFlash heartbeat comes in every 10 seconds.

* Solution:

    * Check whether the TiKV/TiFlash instance is being restarted.
    * Check whether the TiKV/TiFlash process is normal, the network is isolated, and the load is too high, and recover the service as much as possible.
    * If you confirm that the TiKV/TiFlash instance cannot be recovered, you can make it offline.
    * If you confirm that the TiKV/TiFlash instance can be recovered, but not in the short term, you can consider increasing the value of `max-down-time`. It will prevent the TiKV/TiFlash instance from being considered as irrecoverable and the data from being removed from the TiKV/TiFlash.

#### `PD_cluster_unhealthy_tikv_nums`

* Alert rule:

    `(sum(pd_cluster_status{type="store_unhealth_count"}) by (instance) > 0) and (sum(etcd_server_is_leader) by (instance) > 0)`

* Description:

    Indicates that there are unhealthy stores. If the situation persists for some time (configured by [`max-store-down-time`](/pd-configuration-file.md#max-store-down-time), defaults to `30m`), the store is likely to change to `Offline` state, which triggers the [`PD_cluster_down_store_nums`](#pd_cluster_down_store_nums) alert.

* Solution:

    Check the state of the TiKV stores.

#### `PD_cluster_low_space`

* Alert rule:

    `(sum(pd_cluster_status{type="store_low_space_count"}) by (instance) > 0) and (sum(etcd_server_is_leader) by (instance) > 0)`

* Description:

    Indicates that there is no sufficient space on the TiKV/TiFlash node.

* Solution:

    * Check whether the space in the cluster is generally insufficient. If so, increase its capacity.
    * Check whether there is any issue with Region balance scheduling. If so, it will lead to uneven data distribution.
    * Check whether there is any file that occupies a large amount of disk space, such as the log, snapshot, and core dump.
    * Lower the Region weight of the node to reduce the data volume.
    * When it is not possible to release the space, consider proactively making the node offline. This prevents insufficient disk space that leads to downtime.

#### `PD_etcd_network_peer_latency`

* Alert rule:

    `histogram_quantile(0.99, sum(rate(etcd_network_peer_round_trip_time_seconds_bucket[1m])) by (To, instance, job, le)) > 1`

* Description:

    The network latency between PD nodes is high. It might lead to the leader timeout and TSO disk storage timeout, which impacts the service of the cluster.

* Solution:

    * Check the network and system load status.
    * If the problematic PD instance cannot be recovered due to environmental factors, make it offline and replace it.

#### `PD_tidb_handle_requests_duration`

* Alert rule:

    `histogram_quantile(0.99, sum(rate(pd_client_request_handle_requests_duration_seconds_bucket{type="tso"}[1m])) by (instance, job, le)) > 0.1`

* Description:

    It takes a longer time for PD to handle the TSO request. It is often caused by a high load.

* Solution:

    * Check the load status of the server.
    * Use pprof to analyze the CPU profile of PD.
    * Manually switch the PD leader.
    * If the problematic PD instance cannot be recovered due to environmental factors, make it offline and replace it.

#### `PD_down_peer_region_nums`

* Alert rule:

    `(sum(pd_regions_status{type="down-peer-region-count"}) by (instance)  > 0) and (sum(etcd_server_is_leader) by (instance) > 0)`

* Description:

    The number of Regions with an unresponsive peer reported by the Raft leader.

* Solution:

    * Check whether there is any TiKV that is down, or that was just restarted, or that is busy.
    * Watch the Region health panel and see whether `down_peer_region_count` is continuously decreasing.
    * Check the network between TiKV servers.

#### `PD_pending_peer_region_count`

* Alert rule:

    `(sum(pd_regions_status{type="pending-peer-region-count"}) by (instance) > 100) and (sum(etcd_server_is_leader) by (instance) > 0)`

* Description:

    There are too many Regions that have lagged Raft logs. It is normal that scheduling leads to a small number of pending peers, but if the number remains high, there might be an issue.

* Solution:

    * Watch the Region health panel and see whether `pending_peer_region_count` is continuously decreasing.
    * Check the network between TiKV servers, especially whether there is enough bandwidth.

#### `PD_leader_change`

* Alert rule:

    `count(changes(pd_tso_events{type="save"}[10m]) > 0) >= 2`

* Description:

    The PD leader is recently switched.

* Solution:

    * Exclude the human factors, such as restarting PD, manually transferring leader, and adjusting leader priority.
    * Check the network and system load status.
    * If the problematic PD instance cannot be recovered due to environmental factors, make it offline and replace it.

#### `TiKV_space_used_more_than_80%`

* Alert rule:

    `sum(pd_cluster_status{type="storage_size"}) / sum(pd_cluster_status{type="storage_capacity"}) * 100 > 80`

* Description:

    Over 80% of the cluster space is occupied.

* Solution:

    * Check whether it is needed to increase capacity.
    * Check whether there is any file that occupies a large amount of disk space, such as the log, snapshot, and core dump.

#### `PD_system_time_slow`

* Alert rule:

    `changes(pd_tso_events{type="system_time_slow"}[10m]) >= 1`

* Description:

    The system time rewind might happen.

* Solution:

    Check whether the system time is configured correctly.

#### `PD_no_store_for_making_replica`

* Alert rule:

    `increase(pd_checker_event_count{type="replica_checker", name="no_target_store"}[1m]) > 0`

* Description:

    There is no appropriate store for additional replicas.

* Solution:

    * Check whether there is enough space in the store.
    * Check whether there is any store for additional replicas according to the label configuration if it is configured.

#### `PD_cluster_slow_tikv_nums`

* Alert rule:

    `sum(pd_cluster_status{type="store_slow_count"}) by (instance) > 0) and (sum(etcd_server_is_leader) by (instance) > 0`

* Description:

    There is a slow TiKV node. `raftstore.inspect-interval` controls the detection of TiKV slow nodes. For more information, see [`raftstore.inspect-interval`](/tikv-configuration-file.md#inspect-interval).

* Solution:

    * Watch the [**TiKV-Details** > **PD** dashboard](/grafana-tikv-dashboard.md#pd) and view the Store Slow Score metric. Identify the node with a metric value exceeding 80, which is detected as a slow node.
    * Watch the [**TiKV-Details** > **Raft IO** dashboard](/grafana-tikv-dashboard.md#raft-io) and see whether the latency increases. If the latency is high, it means a bottleneck might exist in the disk.
    * Set the [`raftstore.inspect-interval`](/tikv-configuration-file.md#inspect-interval) configuration item to a larger value to increase the timeout limit of latency.
    * For further analysis of performance issues of the alerted TiKV node and tuning methods, see [Performance analysis and tuning](/performance-tuning-methods.md#storage-async-write-duration-store-duration-and-apply-duration).

## TiKV alert rules

This section gives the alert rules for the TiKV component.

### Emergency-level alerts

#### `TiKV_memory_used_too_fast`

* Alert rule:

    `process_resident_memory_bytes{job=~"tikv",instance=~".*"} - (process_resident_memory_bytes{job=~"tikv",instance=~".*"} offset 5m) > 5*1024*1024*1024`

* Description:

    Currently, there are no TiKV monitoring items about memory. You can monitor the memory usage of the machines in the cluster by Node_exporter. The above rule indicates that when the memory usage exceeds 5 GB within 5 minutes (the memory is occupied too fast in TiKV), an alert is triggered.

* Solution:

    Adjust the `block-cache-size` value of both `rocksdb.defaultcf` and `rocksdb.writecf`.

#### `TiKV_GC_can_not_work`

* Alert rule:

    `sum(increase(tikv_gcworker_gc_tasks_vec{task="gc"}[1d])) < 1 and (sum(increase(tikv_gc_compaction_filter_perform[1d])) < 1 and sum(increase(tikv_engine_event_total{db="kv", cf="write", type="compaction"}[1d])) >= 1)`

* Description:

    GC is not performed successfully on a TiKV instance within 24 hours, which indicates that GC is not working properly. If GC does not run in a short term, it will not cause much trouble; but if GC keeps down, more and more versions are retained, which slows down the query.

* Solution:

    1. Perform `SELECT VARIABLE_VALUE FROM mysql.tidb WHERE VARIABLE_NAME = "tikv_gc_leader_desc"` to locate the `tidb-server` corresponding to the GC leader;
    2. View the log of the `tidb-server`, and grep gc_worker tidb.log;
    3. If you find that the GC worker has been resolving locks (the last log is "start resolve locks") or deleting ranges (the last log is "start delete {number} ranges") during this time, it means the GC process is running normally. Otherwise, [get support](/support.md) from PingCAP or the community.

### Critical-level alerts

#### `TiKV_server_report_failure_msg_total`

* Alert rule:

    `sum(rate(tikv_server_report_failure_msg_total{type="unreachable"}[10m])) BY (store_id) > 10`

* Description:

    Indicates that the remote TiKV cannot be connected.

* Solution:

    1. Check whether the network is clear.
    2. Check whether the remote TiKV is down.
    3. If the remote TiKV is not down, check whether the pressure is too high. Refer to the solution in [`TiKV_channel_full_total`](#tikv_channel_full_total).

#### `TiKV_channel_full_total`

* Alert rule:

    `sum(rate(tikv_channel_full_total[10m])) BY (type, instance) > 0`

* Description:

    This issue is often caused by the stuck Raftstore thread and high pressure on TiKV.

* Solution:

    1. Watch the [**TiKV-Details** > **Raft Propose** dashboard](/grafana-tikv-dashboard.md#raft-propose), and see whether the alerted TiKV node has a much higher Raft propose than other TiKV nodes. If so, it means that there are one or more hot spots on this TiKV. You need to check whether the hot spot scheduling can work properly.
    2. Watch the [**TiKV-Details** > **Raft IO** dashboard](/grafana-tikv-dashboard.md#raft-io), and see whether the latency increases. If the latency is high, it means a bottleneck might exist in the disk.
    3. Watch the [**TiKV-Details** > **Raft process** dashboard](/grafana-tikv-dashboard.md#raft-process), and see whether the `tick duration` is high. If so, you need to set [`raftstore.raft-base-tick-interval`](/tikv-configuration-file.md#raft-base-tick-interval) to `"2s"`.

#### `TiKV_write_stall`

* Alert rule:

    `delta(tikv_engine_write_stall[10m]) > 0`

* Description:

    The write pressure on RocksDB is too high, and a stall occurs.

* Solution:

    1. View the disk monitor, and troubleshoot the disk issues;
    2. Check whether there is any write hot spot on the TiKV;
    3. Set `max-sub-compactions` to a larger value under the `[rocksdb]` and `[raftdb]` configurations.

#### `TiKV_raft_log_lag`

* Alert rule:

    `histogram_quantile(0.99, sum(rate(tikv_raftstore_log_lag_bucket[1m])) by (le, instance)) > 5000`

* Description:

    If this value is relatively large, it means Follower has lagged far behind Leader, and Raft cannot be replicated normally. It is possibly because the TiKV machine where Follower is located is stuck or down.

#### `TiKV_async_request_snapshot_duration_seconds`

* Alert rule:

    `histogram_quantile(0.99, sum(rate(tikv_storage_engine_async_request_duration_seconds_bucket{type="snapshot"}[1m])) by (le, instance, type)) > 1`

* Description:

    If this value is relatively large, it means the load pressure on Raftstore is too high, and it might be stuck already.

* Solution:

    Refer to the solution in [`TiKV_channel_full_total`](#tikv_channel_full_total).

#### `TiKV_async_request_write_duration_seconds`

* Alert rule:

    `histogram_quantile(0.99, sum(rate(tikv_storage_engine_async_request_duration_seconds_bucket{type="write"}[1m])) by (le, instance, type)) > 1`

* Description:

    If this value is relatively large, it means the Raft write takes a long time.

* Solution:

    1. Watch the [**TiKV-Details** > **Raft propose** dashboard](/grafana-tikv-dashboard.md#raft-propose) and see whether the **99% Propose wait duration per server** metric of the alerted TiKV node is significantly higher than that of other TiKV nodes. If so, it indicates that hotspots exist on this TiKV node, and you need to check whether the hotspot scheduling works properly.
    2. Watch the [**TiKV-Details** > **Raft IO** dashboard](/grafana-tikv-dashboard.md#raft-io) and see whether the latency increases. If the latency is high, it means a bottleneck might exist in the disk.
    3. For further analysis of performance issues of the alerted TiKV node and tuning methods, see [Performance analysis and tuning](/performance-tuning-methods.md#storage-async-write-duration-store-duration-and-apply-duration).

#### `TiKV_coprocessor_request_wait_seconds`

* Alert rule:

    `histogram_quantile(0.9999, sum(rate(tikv_coprocessor_request_wait_seconds_bucket[1m])) by (le, instance, req)) > 10`

* Description:

    If this value is relatively large, it means the pressure on the Coprocessor worker is high. There might be a slow task that makes the Coprocessor thread stuck.

* Solution:

    1. View the slow query log from the TiDB log to see whether the index or full table scan is used in a query, or see whether it is needed to analyze;
    2. Check whether there is a hot spot;
    3. View the Coprocessor monitor and see whether `total` and `process` in `coprocessor table/index scan` match. If they differ a lot, it indicates too many invalid queries are performed. You can see whether there is `over seek bound`. If so, there are too many versions that GC does not handle in time. Then you need to increase the number of parallel GC threads.

#### `TiKV_raftstore_thread_cpu_seconds_total`

* Alert rule:

    `sum(rate(tikv_thread_cpu_seconds_total{name=~"raftstore_.*"}[1m])) by (instance) > 1.6`

* Description:

    This rule monitors CPU usage by Raftstore. If the value is high, it indicates pressure on Raftstore threads is heavy.

    The alert threshold is 80% of the [`raftstore.store-pool-size`](/tikv-configuration-file.md#store-pool-size) value. `raftstore.store-pool-size` is 2 by default, so the alert threshold is 1.6.

* Solution:

    Refer to the solution in [`TiKV_channel_full_total`](#tikv_channel_full_total).

#### `TiKV_raft_append_log_duration_secs`

* Alert rule:

    `histogram_quantile(0.99, sum(rate(tikv_raftstore_append_log_duration_seconds_bucket[1m])) by (le, instance)) > 1`

* Description:

    Indicates the time cost of appending Raft log. If it is high, it usually means I/O is too busy.

#### `TiKV_raft_apply_log_duration_secs`

* Alert rule:

    `histogram_quantile(0.99, sum(rate(tikv_raftstore_apply_log_duration_seconds_bucket[1m])) by (le, instance)) > 1`

* Description:

    Indicates the time cost of applying Raft log. If it is high, it usually means I/O is too busy.

#### `TiKV_scheduler_latch_wait_duration_seconds`

* Alert rule:

    `histogram_quantile(0.99, sum(rate(tikv_scheduler_latch_wait_duration_seconds_bucket[1m])) by (le, instance, type)) > 1`

* Description:

    The waiting time for the write operations to obtain the memory lock in Scheduler. If it is high, there might be many write conflicts, or that some operations that lead to conflicts take a long time to finish and block other operations that wait for the same lock.

* Solution:

    1. Identify the most time-consuming command by viewing the scheduler command duration in the `Scheduler` and `Scheduler-${cmd}` (`${cmd}` is the write command to query) monitors;
    2. Check the `total` and `process` values in the scheduler scan details of the `Scheduler` and `Scheduler-${cmd}` monitors and see whether `total` and `process` match.
    3. View the storage async snapshot/write duration in the Storage monitor and see whether the Raft operation is performed in time.

#### `TiKV_thread_apply_worker_cpu_seconds`

* Alert rule:

    `max(rate(tikv_thread_cpu_seconds_total{name=~"apply_.*"}[1m])) by (instance) > 0.9`

* Description:

    The apply Raft log thread is under great pressure and is approaching or has exceeded its limit. This is often caused by a burst of writes.

### Warning-level alerts

#### `TiKV_leader_drops`

* Alert rule:

    `delta(tikv_pd_heartbeat_tick_total{type="leader"}[30s]) < -10`

* Description:

    It is often caused by a stuck Raftstore thread.

* Solution:

    1. Refer to [`TiKV_channel_full_total`](#tikv_channel_full_total).
    2. It there is low pressure on TiKV, consider whether the PD scheduling is too frequent. You can view the Operator Create panel on the PD page, and check the types and number of the PD scheduling.

#### `TiKV_raft_process_ready_duration_secs`

* Alert rule:

    `histogram_quantile(0.999, sum(rate(tikv_raftstore_raft_process_duration_secs_bucket{type='ready'}[1m])) by (le, instance, type)) > 2`

* Description:

    Indicates the time cost of handling Raft ready. If this value is large, it is often caused by the stuck appending log task.

#### `TiKV_raft_process_tick_duration_secs`

* Alert rule:

    `histogram_quantile(0.999, sum(rate(tikv_raftstore_raft_process_duration_secs_bucket{type='tick'}[1m])) by (le, instance, type)) > 2`

* Description:

    Indicates the time cost of handling Raft tick. If this value is large, it is often caused by too many Regions.

* Solution:

    1. Consider using a higher-level log such as `warn` or `error`.
    2. Add `raft-base-tick-interval = "2s"` under the `[raftstore]` configuration.

#### `TiKV_scheduler_context_total`

* Alert rule:

    `abs(delta( tikv_scheduler_context_total[5m])) > 1000`

* Description:

    The number of write commands that are being executed by Scheduler. If this value is large, it means the task is not finished timely.

* Solution:

    Refer to [`TiKV_scheduler_latch_wait_duration_seconds`](#tikv_scheduler_latch_wait_duration_seconds).

#### `TiKV_scheduler_command_duration_seconds`

* Alert rule:

    `histogram_quantile(0.99, sum(rate(tikv_scheduler_command_duration_seconds_bucket[1m])) by (le, instance, type)) > 1`

* Description:

    Indicates the time cost of executing the Scheduler command.

* Solution:

    Refer to [`TiKV_scheduler_latch_wait_duration_seconds`](#tikv_scheduler_latch_wait_duration_seconds).

#### `TiKV_coprocessor_outdated_request_wait_seconds`

* Alert rule:

    `delta(tikv_coprocessor_outdated_request_wait_seconds_count[10m]) > 0`

* Description:

    The waiting time of the expired requests by Coprocessor. If this value is large, it means there is high pressure on Coprocessor.

* Solution:

    Refer to [`TiKV_coprocessor_request_wait_seconds`](#tikv_coprocessor_request_wait_seconds).

#### `TiKV_coprocessor_pending_request`

* Alert rule:

    `delta(tikv_coprocessor_pending_request[10m]) > 5000`

* Description:

    The queuing requests of Coprocessor.

* Solution:

    Refer to [`TiKV_coprocessor_request_wait_seconds`](#tikv_coprocessor_request_wait_seconds).

#### `TiKV_batch_request_snapshot_nums`

* Alert rule:

    `sum(rate(tikv_thread_cpu_seconds_total{name=~"cop_.*"}[1m])) by (instance) / (count(tikv_thread_cpu_seconds_total{name=~"cop_.*"}) * 0.9) / count(count(tikv_thread_cpu_seconds_total) by (instance)) > 0`

* Description:

    The Coprocessor CPU usage of a TiKV machine exceeds 90%.

#### `TiKV_pending_task`

* Alert rule:

    `sum(tikv_worker_pending_task_total) BY (instance,name)  > 1000`

* Description:

    The number of pending tasks of TiKV.

* Solution:

    Check which kind of tasks has a higher value from the `Worker pending tasks` metric in the [**TiKV-Details** > **Task** dashboard](/grafana-tikv-dashboard.md#task).

#### `TiKV_low_space`

* Alert rule:

    `sum(tikv_store_size_bytes{type="available"}) by (instance) / sum(tikv_store_size_bytes{type="capacity"}) by (instance) < 0.2`

* Description:

    The data volume of TiKV exceeds 80% of the configured node capacity or the disk capacity of the machine.

* Solution:

    * Check the balance condition of node space.
    * Make a plan to increase the disk capacity or delete some data or increase cluster node depending on different situations.

#### `TiKV_approximate_region_size`

* Alert rule:

    `histogram_quantile(0.99, sum(rate(tikv_raftstore_region_size_bucket[1m])) by (le)) > 1073741824`

* Description:

    The maximum Region approximate size that is scanned by the TiKV split checker is continually larger than 1 GB within one minute.

* Solution:

    The speed of splitting Regions is slower than the write speed. To alleviate this issue, you'd better update TiDB to a version that supports batch-split (>= 2.1.0-rc1). If it is not possible to update temporarily, you can use `pd-ctl operator add split-region <region_id> --policy=approximate` to manually split Regions.

## TiFlash alert rules

For the detailed descriptions of TiFlash alert rules, see [TiFlash Alert Rules](/tiflash/tiflash-alert-rules.md).

## TiCDC Alert rules

For the detailed descriptions of TiCDC alert rules, see [TiCDC Alert Rules](/ticdc/ticdc-alert-rules.md).

## Node_exporter host alert rules

This section gives the alert rules for the Node_exporter host.

### Emergency-level alerts

#### `NODE_disk_used_more_than_80%`

* Alert rule:

    `node_filesystem_avail_bytes{fstype=~"(ext.|xfs)", mountpoint!~"/boot"} / node_filesystem_size_bytes{fstype=~"(ext.|xfs)", mountpoint!~"/boot"} * 100 <= 20`

* Description:

    The disk space usage of the machine exceeds 80%.

* Solution:

    * Log in to the machine, run the `df -h` command to check the disk space usage.
    * Make a plan to increase the disk capacity or delete some data or increase cluster node depending on different situations.

#### `NODE_disk_inode_more_than_80%`

* Alert rule:

    `node_filesystem_files_free{fstype=~"(ext.|xfs)"} / node_filesystem_files{fstype=~"(ext.|xfs)"} * 100 < 20`

* Description:

    The inode usage of the filesystem on the machine exceeds 80%.

* Solution:

    * Log in to the machine and run the `df -i` command to view the node usage of the filesystem.
    * Make a plan to increase the disk capacity or delete some data or increase cluster node depending on different situations.

#### `NODE_disk_readonly`

* Alert rule:

    `node_filesystem_readonly{fstype=~"(ext.|xfs)"} == 1`

* Description:

    The filesystem is read-only and data cannot be written in it. It is often caused by disk failure or filesystem corruption.

* Solution:

    * Log in to the machine and create a file to test whether it is normal.
    * Check whether the disk LED is normal. If not, replace the disk and repair the filesystem of the machine.

### Critical-level alerts

#### `NODE_memory_used_more_than_80%`

* Alert rule:

    `(((node_memory_MemTotal_bytes-node_memory_MemFree_bytes-node_memory_Cached_bytes)/(node_memory_MemTotal_bytes)*100)) >= 80`

* Description:

    The memory usage of the machine exceeds 80%.

* Solution:

    * View the Memory panel of the host in the Grafana Node Exporter dashboard, and see whether Used memory is too high and Available memory is too low.
    * Log in to the machine and run the `free -m` command to view the memory usage. You can run `top` to check whether there is any abnormal process that has an overly high memory usage.

### Warning-level alerts

#### `NODE_node_overload`

* Alert rule:

    `(node_load5 / count without (cpu, mode) (node_cpu_seconds_total{mode="system"})) > 1`

* Description:

    The CPU load on the machine is relatively high.

* Solution:

    * View the CPU Usage and Load Average of the host in the Grafana Node Exporter dashboard to check whether they are too high.
    * Log in to the machine and run `top` to check the load average and the CPU usage, and see whether there is any abnormal process that has an overly high CPU usage.

#### `NODE_cpu_used_more_than_80%`

* Alert rule:

    `avg(irate(node_cpu_seconds_total{mode="idle"}[5m])) by(instance) * 100 <= 20`

* Description:

    The CPU usage of the machine exceeds 80%.

* Solution:

    * View the CPU Usage and Load Average of the host on the Grafana Node Exporter dashboard to check whether they are too high.
    * Log in to the machine and run `top` to check the Load Average and the CPU Usage, and see whether there is any abnormal process that has an overly high CPU usage.

#### `NODE_tcp_estab_num_more_than_50000`

* Alert rule:

    `node_netstat_Tcp_CurrEstab > 50000`

* Description:

    There are more than 50,000 TCP links in the "establish" status on the machine.

* Solution:

    * Log in to the machine and run `ss -s` to check the number of TCP links in the "estab" status in the current system.
    * Run `netstat` to check whether there is any abnormal link.

#### `NODE_disk_read_latency_more_than_32ms`

* Alert rule:

    `((rate(node_disk_read_time_seconds_total{device=~".+"}[5m]) / rate(node_disk_reads_completed_total{device=~".+"}[5m])) or (irate(node_disk_read_time_seconds_total{device=~".+"}[5m]) / irate(node_disk_reads_completed_total{device=~".+"}[5m])) ) * 1000 > 32`

* Description:

    The read latency of the disk exceeds 32 ms.

* Solution:

    * Check the disk status by viewing the Grafana Disk Performance dashboard.
    * Check the read latency of the disk by viewing the Disk Latency panel.
    * Check the I/O usage by viewing the Disk I/O Utilization panel.

#### `NODE_disk_write_latency_more_than_16ms`

* Alert rule:

    `((rate(node_disk_write_time_seconds_total{device=~".+"}[5m]) / rate(node_disk_writes_completed_total{device=~".+"}[5m])) or (irate(node_disk_write_time_seconds_total{device=~".+"}[5m]) / irate(node_disk_writes_completed_total{device=~".+"}[5m])))> 16`

* Description:

    The write latency of the disk exceeds 16ms.

* Solution:

    * Check the disk status by viewing the Grafana Disk Performance dashboard.
    * Check the write latency of the disk by viewing the Disk Latency panel.
    * Check the I/O usage by viewing the Disk I/O Utilization panel.

## Blackbox_exporter TCP, ICMP, and HTTP alert rules

This section gives the alert rules for the Blackbox_exporter TCP, ICMP, and HTTP.

### Emergency-level alerts

#### `TiDB_server_is_down`

* Alert rule:

    `probe_success{group="tidb"} == 0`

* Description:

    Failure to probe the TiDB service port.

* Solution:

    * Check whether the machine that provides the TiDB service is down.
    * Check whether the TiDB process exists.
    * Check whether the network between the monitoring machine and the TiDB machine is normal.

#### `TiFlash_server_is_down`

* Alert rule:

    `probe_success{group="tiflash"} == 0`

* Description:

    Failure to probe the TiFlash service port.

* Solution:

    * Check whether the machine that provides the TiFlash service is down.
    * Check whether the TiFlash process exists.
    * Check whether the network between the monitoring machine and the TiFlash machine is normal.

#### `TiKV_server_is_down`

* Alert rule:

    `probe_success{group="tikv"} == 0`

* Description:

    Failure to probe the TiKV service port.

* Solution:

    * Check whether the machine that provides the TiKV service is down.
    * Check whether the TiKV process exists.
    * Check whether the network between the monitoring machine and the TiKV machine is normal.

#### `PD_server_is_down`

* Alert rule:

    `probe_success{group="pd"} == 0`

* Description:

    Failure to probe the PD service port.

* Solution:

    * Check whether the machine that provides the PD service is down.
    * Check whether the PD process exists.
    * Check whether the network between the monitoring machine and the PD machine is normal.

#### `Node_exporter_server_is_down`

* Alert rule:

    `probe_success{group="node_exporter"} == 0`

* Description:

    Failure to probe the Node_exporter service port.

* Solution:

    * Check whether the machine that provides the Node_exporter service is down.
    * Check whether the Node_exporter process exists.
    * Check whether the network between the monitoring machine and the Node_exporter machine is normal.

#### `Blackbox_exporter_server_is_down`

* Alert rule:

    `probe_success{group="blackbox_exporter"} == 0`

* Description:

    Failure to probe the Blackbox_Exporter service port.

* Solution:

    * Check whether the machine that provides the Blackbox_Exporter service is down.
    * Check whether the Blackbox_Exporter process exists.
    * Check whether the network between the monitoring machine and the Blackbox_Exporter machine is normal.

#### `Grafana_server_is_down`

* Alert rule:

    `probe_success{group="grafana"} == 0`

* Description:

    Failure to probe the Grafana service port.

* Solution:

    * Check whether the machine that provides the Grafana service is down.
    * Check whether the Grafana process exists.
    * Check whether the network between the monitoring machine and the Grafana machine is normal.

#### `Pushgateway_server_is_down`

* Alert rule:

    `probe_success{group="pushgateway"} == 0`

* Description:

    Failure to probe the Pushgateway service port.

* Solution:

    * Check whether the machine that provides the Pushgateway service is down.
    * Check whether the Pushgateway process exists.
    * Check whether the network between the monitoring machine and the Pushgateway machine is normal.

#### `Kafka_exporter_is_down`

* Alert rule:

    `probe_success{group="kafka_exporter"} == 0`

* Description:

    Failure to probe the Kafka_Exporter service port.

* Solution:

    * Check whether the machine that provides the Kafka_Exporter service is down.
    * Check whether the Kafka_Exporter process exists.
    * Check whether the network between the monitoring machine and the Kafka_Exporter machine is normal.

#### `Pushgateway_metrics_interface`

* Alert rule:

    `probe_success{job="blackbox_exporter_http"} == 0`

* Description:

    Failure to probe the Pushgateway service http interface.

* Solution:

    * Check whether the machine that provides the Pushgateway service is down.
    * Check whether the Pushgateway process exists.
    * Check whether the network between the monitoring machine and the Pushgateway machine is normal.

### Warning-level alerts

#### `BLACKER_ping_latency_more_than_1s`

* Alert rule:

    `max_over_time(probe_duration_seconds{job=~"blackbox_exporter.*_icmp"}[1m]) > 1`

* Description:

    The ping latency exceeds 1 second.

* Solution:

    * View the ping latency between the two nodes on the Grafana Blackbox Exporter page to check whether it is too high.
    * Check the TCP panel on the Grafana Node Exporter page to check whether there is any packet loss.

---

## File: analyze-slow-queries.md

---
title: Analyze Slow Queries
summary: Learn how to locate and analyze slow queries.
---

# Analyze Slow Queries

To address the issue of slow queries, you need to take the following two steps:

1. Among many queries, identify which type of queries are slow.
2. Analyze why this type of queries are slow.

You can easily perform step 1 using the [slow query log](/dashboard/dashboard-slow-query.md) and the [statement summary table](/statement-summary-tables.md) features. It is recommended to use [TiDB Dashboard](/dashboard/dashboard-intro.md), which integrates the two features and directly displays the slow queries in your browser.

This document focuses on how to perform step 2 - analyze why this type of queries are slow.

Generally, slow queries have the following major causes:

- Optimizer issues, such as wrong index selected, wrong join type or sequence selected.
- System issues. All issues not caused by the optimizer are system issues. For example, a busy TiKV instance processes requests slowly; outdated Region information causes slow queries.

In actual situations, optimizer issues might cause system issues. For example, for a certain type of queries, the optimizer uses a full table scan instead of the index. As a result, the SQL queries consume many resources, which causes the CPU usage of some TiKV instances to soar. This seems like a system issue, but in essence, it is an optimizer issue.

To identify system issues is relatively simple. To analyze optimizer issues, you need to determine whether the execution plan is reasonable or not. Therefore, it is recommended to analyze slow queries by following these procedures:

1. Identify the performance bottleneck of the query, that is, the time-consuming part of the query process.
2. Analyze the system issues: analyze the possible causes according to the query bottleneck and the monitoring/log information of that time.
3. Analyze the optimizer issues: analyze whether there is a better execution plan.

The procedures above are explained in the following sections.

## Identify the performance bottleneck of the query

First, you need to have a general understanding of the query process. The key stages of the query execution process in TiDB are illustrated in [TiDB performance map](/media/performance-map.png).

You can get the duration information using the following methods:

- [Slow log](/identify-slow-queries.md). It is recommended to view the slow log in [TiDB Dashboard](/dashboard/dashboard-overview.md).
- [`EXPLAIN ANALYZE` statement](/sql-statements/sql-statement-explain-analyze.md).

The methods above are different in the following aspects:

- The slow log records the duration of almost all stages of a SQL execution, from parsing to returning results, and is relatively comprehensive (you can query and analyze the slow log in TiDB Dashboard in an intuitive way).
- By executing `EXPLAIN ANALYZE`, you can learn the time consumption of each operator in an actual SQL execution. The results have more detailed statistics of the execution duration.

In summary, the slow log and `EXPLAIN ANALYZE` statements help you determine the SQL query is slow in which component (TiDB or TiKV) at which stage of the execution. Therefore, you can accurately identify the performance bottleneck of the query.

In addition, since v4.0.3, the `Plan` field in the slow log also includes the SQL execution information, which is the result of `EXPLAIN ANALYZE`. So you can find all information of SQL duration in the slow log.

## Analyze system issues

System issues can be divided into the following types according to different execution stages of a SQL statement:

1. TiKV is slow in data processing. For example, the TiKV coprocessor processes data slowly.
2. TiDB is slow in execution. For example, a `Join` operator processes data slowly.
3. Other key stages are slow. For example, getting the timestamp takes a long time.

For each slow query, first determine to which type the query belongs, and then analyze it in detail.

### TiKV is slow in data processing

If TiKV is slow in data processing, you can easily identify it in the result of `EXPLAIN ANALYZE`. In the following example, `StreamAgg_8` and `TableFullScan_15`, two `tikv-task`s (as indicated by `cop[tikv]` in the `task` column), take `170ms` to execute. After subtracting `170ms`, the execution time of TiDB operators account for a very small proportion of the total execution time. This indicates that the bottleneck is in TiKV.

```sql
+----------------------------+---------+---------+-----------+---------------+------------------------------------------------------------------------------+---------------------------------+-----------+------+
| id                         | estRows | actRows | task      | access object | execution info                                                               | operator info                   | memory    | disk |
+----------------------------+---------+---------+-----------+---------------+------------------------------------------------------------------------------+---------------------------------+-----------+------+
| StreamAgg_16               | 1.00    | 1       | root      |               | time:170.08572ms, loops:2                                                     | funcs:count(Column#5)->Column#3 | 372 Bytes | N/A  |
| └─TableReader_17           | 1.00    | 1       | root      |               | time:170.080369ms, loops:2, rpc num: 1, rpc time:17.023347ms, proc keys:28672 | data:StreamAgg_8                | 202 Bytes | N/A  |
|   └─StreamAgg_8            | 1.00    | 1       | cop[tikv] |               | time:170ms, loops:29                                                          | funcs:count(1)->Column#5        | N/A       | N/A  |
|     └─TableFullScan_15     | 7.00    | 28672   | cop[tikv] | table:t       | time:170ms, loops:29                                                          | keep order:false, stats:pseudo  | N/A       | N/A  |
+----------------------------+---------+---------+-----------+---------------+------------------------------------------------------------------------------+---------------------------------+-----------+------
```

In addition, the `Cop_process` and `Cop_wait` fields in the slow log can also help your analysis. In the following example, the total duration of the query is around `180.85ms`, and the largest `coptask` takes `171ms`. This indicates that the bottleneck of this query is on the TiKV side.

For the description of each field in the slow log, see [fields description](/identify-slow-queries.md#fields-description).

```log
# Query_time: 0.18085
...
# Num_cop_tasks: 1
# Cop_process: Avg_time: 170ms P90_time: 170ms Max_time: 170ms Max_addr: 10.6.131.78
# Cop_wait: Avg_time: 1ms P90_time: 1ms Max_time: 1ms Max_Addr: 10.6.131.78
```

After identifying that TiKV is the bottleneck, you can find out the cause as described in the following sections.

#### TiKV instance is busy

During the execution of a SQL statement, TiDB might fetch data from multiple TiKV instances. If one TiKV instance responds slowly, the overall SQL execution speed is slowed down.

The `Cop_wait` field in the slow log can help you determine this cause.

```log
# Cop_wait: Avg_time: 1ms P90_time: 2ms Max_time: 110ms Max_Addr: 10.6.131.78
```

The log above shows that a `cop-task` sent to the `10.6.131.78` instance waits `110ms` before being executed. It indicates that this instance is busy. You can check the CPU monitoring of that time to confirm the cause.

#### Obsolete MVCC versions and excessive keys

If too many obsolete MVCC versions exist on TiKV, or if the retention time of historical MVCC data for GC is long, excessive MVCC versions can accumulate. Handling these unnecessary MVCC versions can affect scan performance.

Check `Total_keys` and `Processed_keys`. If they are greatly different, the TiKV instance has too many keys of the older versions.

```
...
# Total_keys: 2215187529 Processed_keys: 1108056368
...
```

TiDB v8.5.0 introduces the TiKV MVCC in-memory engine (IME) feature, which can accelerate such slow queries. For more information, see [TiKV MVCC In-Memory Engine](/tikv-in-memory-engine.md).

### Other key stages are slow

#### Slow in getting timestamps

You can compare `Wait_TS` and `Query_time` in the slow log. The timestamps are prefetched, so generally `Wait_TS` should be low.

```
# Query_time: 0.0300000
...
# Wait_TS: 0.02500000
```

#### Outdated Region information

Region information on the TiDB side might be outdated. In this situation, TiKV might return the `regionMiss` error. Then TiDB gets the Region information from PD again, which is reflected in the `Cop_backoff` information. Both the failed times and the total duration are recorded.

```
# Cop_backoff_regionMiss_total_times: 200 Cop_backoff_regionMiss_total_time: 0.2 Cop_backoff_regionMiss_max_time: 0.2 Cop_backoff_regionMiss_max_addr: 127.0.0.1 Cop_backoff_regionMiss_avg_time: 0.2 Cop_backoff_regionMiss_p90_time: 0.2
# Cop_backoff_rpcPD_total_times: 200 Cop_backoff_rpcPD_total_time: 0.2 Cop_backoff_rpcPD_max_time: 0.2 Cop_backoff_rpcPD_max_addr: 127.0.0.1 Cop_backoff_rpcPD_avg_time: 0.2 Cop_backoff_rpcPD_p90_time: 0.2
```

#### Subqueries are executed in advance

For statements with non-correlated subqueries, the subquery part might be executed in advance. For example, in `select * from t1 where a = (select max(a) from t2)`, the `select max(a) from t2` part might be executed in advance in the optimization stage. The result of `EXPLAIN ANALYZE` does not show the duration of this type of subqueries.

```sql
mysql> explain analyze select count(*) from t where a=(select max(t1.a) from t t1, t t2 where t1.a=t2.a);
+------------------------------+----------+---------+-----------+---------------+--------------------------+----------------------------------+-----------+------+
| id                           | estRows  | actRows | task      | access object | execution info           | operator info                    | memory    | disk |
+------------------------------+----------+---------+-----------+---------------+--------------------------+----------------------------------+-----------+------+
| StreamAgg_59                 | 1.00     | 1       | root      |               | time:4.69267ms, loops:2  | funcs:count(Column#10)->Column#8 | 372 Bytes | N/A  |
| └─TableReader_60             | 1.00     | 1       | root      |               | time:4.690428ms, loops:2 | data:StreamAgg_48                | 141 Bytes | N/A  |
|   └─StreamAgg_48             | 1.00     |         | cop[tikv] |               | time:0ns, loops:0        | funcs:count(1)->Column#10        | N/A       | N/A  |
|     └─Selection_58           | 16384.00 |         | cop[tikv] |               | time:0ns, loops:0        | eq(test.t.a, 1)                  | N/A       | N/A  |
|       └─TableFullScan_57     | 16384.00 | -1      | cop[tikv] | table:t       | time:0s, loops:0         | keep order:false                 | N/A       | N/A  |
+------------------------------+----------+---------+-----------+---------------+--------------------------+----------------------------------+-----------+------+
5 rows in set (7.77 sec)
```

But you can identify this type of subquery execution in the slow log:

```
# Query_time: 7.770634843
...
# Rewrite_time: 7.765673663 Preproc_subqueries: 1 Preproc_subqueries_time: 7.765231874
```

From log record above, you can see that a subquery is executed in advance and takes `7.76s`.

### TiDB is slow in execution

Assume that the execution plan in TiDB is correct but the execution is slow. To solve this type of issue, you can adjust parameters or use the hint according to the result of `EXPLAIN ANALYZE` for the SQL statement.

If the execution plan is incorrect, see the [Analyze optimizer issues](#analyze-optimizer-issues) section.

#### Low concurrency

If the bottleneck is in the operator with concurrency, speed up the execution by adjusting the concurrency. For example:

```sql
mysql> explain analyze select sum(t1.a) from t t1, t t2 where t1.a=t2.a;
+----------------------------------+--------------+-----------+-----------+---------------+-------------------------------------------------------------------------------------+------------------------------------------------+------------------+---------+
| id                               | estRows      | actRows   | task      | access object | execution info                                                                      | operator info                                  | memory           | disk    |
+----------------------------------+--------------+-----------+-----------+---------------+-------------------------------------------------------------------------------------+------------------------------------------------+------------------+---------+
| HashAgg_11                       | 1.00         | 1         | root      |               | time:9.666832189s, loops:2, PartialConcurrency:4, FinalConcurrency:4                | funcs:sum(Column#6)->Column#5                  | 322.125 KB       | N/A     |
| └─Projection_24                  | 268435456.00 | 268435456 | root      |               | time:9.098644711s, loops:262145, Concurrency:4                                      | cast(test.t.a, decimal(65,0) BINARY)->Column#6 | 199 KB           | N/A     |
|   └─HashJoin_14                  | 268435456.00 | 268435456 | root      |               | time:6.616773501s, loops:262145, Concurrency:5, probe collision:0, build:881.404µs  | inner join, equal:[eq(test.t.a, test.t.a)]     | 131.75 KB        | 0 Bytes |
|     ├─TableReader_21(Build)      | 16384.00     | 16384     | root      |               | time:6.553717ms, loops:17                                                           | data:Selection_20                              | 33.6318359375 KB | N/A     |
|     │ └─Selection_20             | 16384.00     |           | cop[tikv] |               | time:0ns, loops:0                                                                   | not(isnull(test.t.a))                          | N/A              | N/A     |
|     │   └─TableFullScan_19       | 16384.00     | -1        | cop[tikv] | table:t2      | time:0s, loops:0                                                                    | keep order:false                               | N/A              | N/A     |
|     └─TableReader_18(Probe)      | 16384.00     | 16384     | root      |               | time:6.880923ms, loops:17                                                           | data:Selection_17                              | 33.6318359375 KB | N/A     |
|       └─Selection_17             | 16384.00     |           | cop[tikv] |               | time:0ns, loops:0                                                                   | not(isnull(test.t.a))                          | N/A              | N/A     |
|         └─TableFullScan_16       | 16384.00     | -1        | cop[tikv] | table:t1      | time:0s, loops:0                                                                    | keep order:false                               | N/A              | N/A     |
+----------------------------------+--------------+-----------+-----------+---------------+-------------------------------------------------------------------------------------+------------------------------------------------+------------------+---------+
9 rows in set (9.67 sec)
```

As shown above, `HashJoin_14` and `Projection_24` consume much of the execution time. Consider increasing their concurrency using SQL variables to speed up execution.

All system variables are documented in [system-variables](/system-variables.md). To increase the concurrency of `HashJoin_14`, you can modify the `tidb_hash_join_concurrency` system variable.

#### Data is spilled to disk

Another cause of slow execution is disk spill that occurs during execution if the memory limit is reached. You can find out this cause in the execution plan and the slow log:

```sql
+-------------------------+-----------+---------+-----------+---------------+------------------------------+----------------------+-----------------------+----------------+
| id                      | estRows   | actRows | task      | access object | execution info               | operator info        | memory                | disk           |
+-------------------------+-----------+---------+-----------+---------------+------------------------------+----------------------+-----------------------+----------------+
| Sort_4                  | 462144.00 | 462144  | root      |               | time:2.02848898s, loops:453  | test.t.a             | 149.68795776367188 MB | 219.3203125 MB |
| └─TableReader_8         | 462144.00 | 462144  | root      |               | time:616.211272ms, loops:453 | data:TableFullScan_7 | 197.49601364135742 MB | N/A            |
|   └─TableFullScan_7     | 462144.00 | -1      | cop[tikv] | table:t       | time:0s, loops:0             | keep order:false     | N/A                   | N/A            |
+-------------------------+-----------+---------+-----------+---------------+------------------------------+----------------------+-----------------------+----------------+
```

```
...
# Disk_max: 229974016
...
```

#### Join operations with Cartesian product

Join operations with Cartesian product generate data volume as large as `left child row count * right child row count`. This is inefficient and should be avoided.

This type of join operations is marked `CARTESIAN` in the execution plan. For example:

```sql
mysql> explain select * from t t1, t t2 where t1.a>t2.a;
+------------------------------+-------------+-----------+---------------+---------------------------------------------------------+
| id                           | estRows     | task      | access object | operator info                                           |
+------------------------------+-------------+-----------+---------------+---------------------------------------------------------+
| HashJoin_8                   | 99800100.00 | root      |               | CARTESIAN inner join, other cond:gt(test.t.a, test.t.a) |
| ├─TableReader_15(Build)      | 9990.00     | root      |               | data:Selection_14                                       |
| │ └─Selection_14             | 9990.00     | cop[tikv] |               | not(isnull(test.t.a))                                   |
| │   └─TableFullScan_13       | 10000.00    | cop[tikv] | table:t2      | keep order:false, stats:pseudo                          |
| └─TableReader_12(Probe)      | 9990.00     | root      |               | data:Selection_11                                       |
|   └─Selection_11             | 9990.00     | cop[tikv] |               | not(isnull(test.t.a))                                   |
|     └─TableFullScan_10       | 10000.00    | cop[tikv] | table:t1      | keep order:false, stats:pseudo                          |
+------------------------------+-------------+-----------+---------------+---------------------------------------------------------+
```

## Analyze optimizer issues

To analyze optimizer issues, you need to determine whether the execution plan is reasonable or not. You need to have some understanding of the optimization process and each operator.

For the following examples, assume that the table schema is `create table t (id int, a int, b int, c int, primary key(id), key(a), key(b, c))`.

1. `select * from t`: There is no filter condition and a full table scan is performed. So the `TableFullScan` operator is used to read data.
2. `select a from t where a=2`: There is a filter condition and only the index columns are read, so the `IndexReader` operator is used to read data.
3. `select * from t where a=2`: There is a filter condition for `a` but the `a` index cannot fully cover the data to be read, so the `IndexLookup` operator is used.
4. `select b from t where c=3`: Without the prefix condition, the multi-column index cannot be used. So the `IndexFullScan` is used.
5. ...

The examples above are operators used for data reads. For more operators, see [Understand TiDB Execution Plan](/explain-overview.md).

In addition, reading [SQL Tuning Overview](/sql-tuning-overview.md) helps you better understand the TiDB optimizer and determine whether the execution plan is reasonable or not.

Most optimizer issues are explained in [SQL Tuning Overview](/sql-tuning-overview.md). For the solutions, see the following documents:

1. [Wrong Index Solution](/wrong-index-solution.md)
2. [Wrong join order](/join-reorder.md)
3. [Expressions are not pushed down](/blocklist-control-plan.md)

---

## File: as-of-timestamp.md

---
title: Read Historical Data Using the `AS OF TIMESTAMP` Clause
summary: Learn how to read historical data using the `AS OF TIMESTAMP` statement clause.
---

# Read Historical Data Using the `AS OF TIMESTAMP` Clause

This document describes how to perform the [Stale Read](/stale-read.md) feature using the `AS OF TIMESTAMP` clause to read historical data in TiDB, including specific usage examples and strategies for saving historical data.

TiDB supports reading historical data through a standard SQL interface, which is the `AS OF TIMESTAMP` SQL clause, without the need for special clients or drivers. After data is updated or deleted, you can read the historical data before the update or deletion using this SQL interface.

> **Note:**
>
> When reading historical data, TiDB returns the data with the old table structure even if the current table structure is different.

## Syntax

You can use the `AS OF TIMESTAMP` clause in the following three ways:

- [`SELECT ... FROM ... AS OF TIMESTAMP`](/sql-statements/sql-statement-select.md)
- [`START TRANSACTION READ ONLY AS OF TIMESTAMP`](/sql-statements/sql-statement-start-transaction.md)
- [`SET TRANSACTION READ ONLY AS OF TIMESTAMP`](/sql-statements/sql-statement-set-transaction.md)

If you want to specify an exact point of time, you can set a datetime value or use a time function in the `AS OF TIMESTAMP` clause. The format of datetime is like "2016-10-08 16:45:26.999", with millisecond as the minimum time unit, but for most of the time, the time unit of second is enough for specifying a datetime, such as "2016-10-08 16:45:26". You can also get the current time to the millisecond using the `NOW(3)` function. If you want to read the data of several seconds ago, it is **recommended** to use an expression such as `NOW() - INTERVAL 10 SECOND`.

If you want to specify a time range, you can use the [`TIDB_BOUNDED_STALENESS()`](/functions-and-operators/tidb-functions.md#tidb_bounded_staleness) function in the clause. When this function is used, TiDB selects a suitable timestamp within the specified time range. "Suitable" means there are no transactions that start before this timestamp and have not been committed on the accessed replica, that is, TiDB can perform read operations on the accessed replica and the read operations are not blocked. You need to use `TIDB_BOUNDED_STALENESS(t1, t2)` to call this function. `t1` and `t2` are the two ends of the time range, which can be specified using either datetime values or time functions.

Here are some examples of the `AS OF TIMESTAMP` clause:

- `AS OF TIMESTAMP '2016-10-08 16:45:26'`: Tells TiDB to read the latest data stored at 16:45:26 on October 8, 2016.
- `AS OF TIMESTAMP NOW() - INTERVAL 10 SECOND`: Tells TiDB to read the latest data stored 10 seconds ago.
- `AS OF TIMESTAMP TIDB_BOUNDED_STALENESS('2016-10-08 16:45:26', '2016-10-08 16:45:29')`: Tells TiDB to read the data as new as possible within the time range of 16:45:26 to 16:45:29 on October 8, 2016.
- `AS OF TIMESTAMP TIDB_BOUNDED_STALENESS(NOW() - INTERVAL 20 SECOND, NOW())`: Tells TiDB to read the data as new as possible within the time range of 20 seconds ago to the present.

> **Note:**
>
> In addition to specifying a timestamp, the most common use of the `AS OF TIMESTAMP` clause is to read data that is several seconds old. If this approach is used, it is recommended to read historical data older than 5 seconds.
>
> You need to deploy the NTP service for your TiDB and PD nodes when you use Stale Read. This avoids the situation where the specified timestamp used by TiDB goes ahead of the latest TSO allocating progress (such as a timestamp several seconds ahead), or is later than the GC safe point timestamp. When the specified timestamp goes beyond the service scope, TiDB returns an error.
>
> To reduce the latency and improve the timeliness of the Stale Read data, you can modify the TiKV `advance-ts-interval` configuration item. See [Reduce Stale Read latency](/stale-read.md#reduce-stale-read-latency) for details.

## Usage examples

This section describes different ways to use the `AS OF TIMESTAMP` clause with several examples. It first introduces how to prepare the data for recovery, and then shows how to use `AS OF TIMESTAMP` in `SELECT`, `START TRANSACTION READ ONLY AS OF TIMESTAMP`, and `SET TRANSACTION READ ONLY AS OF TIMESTAMP` respectively.

### Prepare data sample

To prepare data for recovery, create a table first and insert several rows of data:

```sql
create table t (c int);
```

```
Query OK, 0 rows affected (0.01 sec)
```

```sql
insert into t values (1), (2), (3);
```

```
Query OK, 3 rows affected (0.00 sec)
```

View the data in the table:

```sql
select * from t;
```

```
+------+
| c    |
+------+
|    1 |
|    2 |
|    3 |
+------+
3 rows in set (0.00 sec)
```

View the current time:

```sql
select now();
```

```
+---------------------+
| now()               |
+---------------------+
| 2021-05-26 16:45:26 |
+---------------------+
1 row in set (0.00 sec)
```

Update the data in a row:

```sql
update t set c=22 where c=2;
```

```
Query OK, 1 row affected (0.00 sec)
```

Confirm that the data of the row is updated:

```sql
select * from t;
```

```
+------+
| c    |
+------+
|    1 |
|   22 |
|    3 |
+------+
3 rows in set (0.00 sec)
```

### Read historical data using the `SELECT` statement

You can use the [`SELECT ... FROM ... AS OF TIMESTAMP`](/sql-statements/sql-statement-select.md) statement to read data from a time point in the past.

```sql
select * from t as of timestamp '2021-05-26 16:45:26';
```

```
+------+
| c    |
+------+
|    1 |
|    2 |
|    3 |
+------+
3 rows in set (0.00 sec)
```

> **Note:**
>
> When reading multiple tables using one `SELECT` statement, you need to make sure that the format of TIMESTAMP EXPRESSIONs is consistent. For example, `select * from t as of timestamp NOW() - INTERVAL 2 SECOND, c as of timestamp NOW() - INTERVAL 2 SECOND;`. In addition, you must specify the `AS OF` information for the relevant table in the `SELECT` statement; otherwise, the `SELECT` statement reads the latest data by default.

### Read historical data using the `START TRANSACTION READ ONLY AS OF TIMESTAMP` statement

You can use the [`START TRANSACTION READ ONLY AS OF TIMESTAMP`](/sql-statements/sql-statement-start-transaction.md) statement to start a read-only transaction based on a time point in the past. The transaction reads historical data of the given time.

```sql
start transaction read only as of timestamp '2021-05-26 16:45:26';
```

```
Query OK, 0 rows affected (0.00 sec)
```

```sql
select * from t;
```

```
+------+
| c    |
+------+
|    1 |
|    2 |
|    3 |
+------+
3 rows in set (0.00 sec)
```

```sql
commit;
```

```
Query OK, 0 rows affected (0.00 sec)
```

After the transaction is committed, you can read the latest data.

```sql
select * from t;
```

```
+------+
| c    |
+------+
|    1 |
|   22 |
|    3 |
+------+
3 rows in set (0.00 sec)
```

> **Note:**
>
> If you start a transaction with the statement `START TRANSACTION READ ONLY AS OF TIMESTAMP`, it is a read-only transaction. Write operations are rejected in this transaction.

### Read historical data using the `SET TRANSACTION READ ONLY AS OF TIMESTAMP` statement

You can use the [`SET TRANSACTION READ ONLY AS OF TIMESTAMP`](/sql-statements/sql-statement-set-transaction.md) statement to set the next transaction as a read-only transaction based on a specified time point in the past. The transaction reads historical data of the given time.

```sql
set transaction read only as of timestamp '2021-05-26 16:45:26';
```

```
Query OK, 0 rows affected (0.00 sec)
```

```sql
begin;
```

```
Query OK, 0 rows affected (0.00 sec)
```

```sql
select * from t;
```

```
+------+
| c    |
+------+
|    1 |
|    2 |
|    3 |
+------+
3 rows in set (0.00 sec)
```

```sql
commit;
```

```
Query OK, 0 rows affected (0.00 sec)
```

After the transaction is committed, you can read the latest data.

```sql
select * from t;
```

```
+------+
| c    |
+------+
|    1 |
|   22 |
|    3 |
+------+
3 rows in set (0.00 sec)
```

> **Note:**
>
> If you start a transaction with the statement `SET TRANSACTION READ ONLY AS OF TIMESTAMP`, it is a read-only transaction. Write operations are rejected in this transaction.

---

## File: auto-increment.md

---
title: AUTO_INCREMENT
summary: Learn the `AUTO_INCREMENT` column attribute of TiDB.
aliases: ['/docs/dev/auto-increment/']
---

# AUTO_INCREMENT

This document introduces the `AUTO_INCREMENT` column attribute, including its concept, implementation principles, auto-increment related features, and restrictions.

<CustomContent platform="tidb">

> **Note:**
>
> The `AUTO_INCREMENT` attribute might cause hotspot in production environments. See [Troubleshoot HotSpot Issues](/troubleshoot-hot-spot-issues.md) for details. It is recommended to use [`AUTO_RANDOM`](/auto-random.md) instead.

</CustomContent>

<CustomContent platform="tidb-cloud">

> **Note:**
>
> The `AUTO_INCREMENT` attribute might cause hotspot in production environments. See [Troubleshoot HotSpot Issues](https://docs.pingcap.com/tidb/stable/troubleshoot-hot-spot-issues#handle-auto-increment-primary-key-hotspot-tables-using-auto_random) for details. It is recommended to use [`AUTO_RANDOM`](/auto-random.md) instead.

</CustomContent>

You can also use the `AUTO_INCREMENT` parameter in the [`CREATE TABLE`](/sql-statements/sql-statement-create-table.md) statement to specify the initial value of the increment field.

## Concept

`AUTO_INCREMENT` is a column attribute that is used to automatically fill in default column values. When the `INSERT` statement does not specify values for the `AUTO_INCREMENT` column, the system automatically assigns values to this column.

For performance reasons, `AUTO_INCREMENT` numbers are allocated in a batch of values (30 thousand by default) to each TiDB server. This means that while `AUTO_INCREMENT` numbers are guaranteed to be unique, values assigned to an `INSERT` statement will only be monotonic on a per TiDB server basis.

> **Note:**
>
> If you want the `AUTO_INCREMENT` numbers to be monotonic on all TiDB servers and your TiDB version is v6.5.0 or later, it is recommended to enable the [MySQL compatibility mode](#mysql-compatibility-mode).

The following is a basic example of `AUTO_INCREMENT`:

{{< copyable "sql" >}}

```sql
CREATE TABLE t(id int PRIMARY KEY AUTO_INCREMENT, c int);
```

{{< copyable "sql" >}}

```sql
INSERT INTO t(c) VALUES (1);
INSERT INTO t(c) VALUES (2);
INSERT INTO t(c) VALUES (3), (4), (5);
```

```sql
mysql> SELECT * FROM t;
+----+---+
| id | c |
+----+---+
| 1  | 1 |
| 2  | 2 |
| 3  | 3 |
| 4  | 4 |
| 5  | 5 |
+----+---+
5 rows in set (0.01 sec)
```

In addition, `AUTO_INCREMENT` also supports the `INSERT` statements that explicitly specify column values. In such cases, TiDB stores the explicitly specified values:

{{< copyable "sql" >}}

```sql
INSERT INTO t(id, c) VALUES (6, 6);
```

```sql
mysql> SELECT * FROM t;
+----+---+
| id | c |
+----+---+
| 1  | 1 |
| 2  | 2 |
| 3  | 3 |
| 4  | 4 |
| 5  | 5 |
| 6  | 6 |
+----+---+
6 rows in set (0.01 sec)
```

The usage above is the same as that of `AUTO_INCREMENT` in MySQL. However, in terms of the specific value that is implicitly assigned, TiDB differs from MySQL significantly.

## Implementation principles

TiDB implements the `AUTO_INCREMENT` implicit assignment in the following way:

For each auto-increment column, a globally visible key-value pair is used to record the maximum ID that has been assigned. In a distributed environment, communication between nodes has some overhead. Therefore, to avoid the issue of write amplification, each TiDB node applies for a batch of consecutive IDs as caches when assigning IDs, and then applies for the next batch of IDs after the first batch is assigned. Therefore, TiDB nodes do not apply to the storage node for IDs when assigning IDs each time. For example:

```sql
CREATE TABLE t(id int UNIQUE KEY AUTO_INCREMENT, c int);
```

Assume two TiDB instances, `A` and `B`, in the cluster. If you execute an `INSERT` statement on the `t` table on `A` and `B` respectively:

```sql
INSERT INTO t (c) VALUES (1)
```

Instance `A` might cache the auto-increment IDs of `[1,30000]`, and instance `B` might cache the auto-increment IDs of `[30001,60000]`. In `INSERT` statements to be executed, these cached IDs of each instance will be assigned to the `AUTO_INCREMENT` column as the default values.

## Basic Features

### Uniqueness

> **Warning:**
>
> When the cluster has multiple TiDB instances, if the table schema contains the auto-increment IDs, it is recommended not to use explicit insert and implicit assignment at the same time, which means using the default values of the auto-increment column and the custom values. Otherwise, it might break the uniqueness of implicitly assigned values.

In the example above, perform the following operations in order:

1. The client inserts a statement `INSERT INTO t VALUES (2, 1)` to instance `B`, which sets `id` to `2`. The statement is successfully executed.

2. The client sends a statement `INSERT INTO t (c) (1)` to instance `A`. This statement does not specify the value of `id`, so the ID is assigned by `A`. At present, because `A` caches the IDs of `[1, 30000]`, it might assign `2` as the value of the auto-increment ID, and increases the local counter by `1`. At this time, the data whose ID is `2` already exists in the database, so the `Duplicated Error` error is returned.

### Monotonicity

TiDB guarantees that `AUTO_INCREMENT` values are monotonic (always increasing) on a per-server basis. Consider the following example where consecutive `AUTO_INCREMENT` values of 1-3 are generated:

{{< copyable "sql" >}}

```sql
CREATE TABLE t (a int PRIMARY KEY AUTO_INCREMENT, b timestamp NOT NULL DEFAULT NOW());
INSERT INTO t (a) VALUES (NULL), (NULL), (NULL);
SELECT * FROM t;
```

```sql
Query OK, 0 rows affected (0.11 sec)

Query OK, 3 rows affected (0.02 sec)
Records: 3  Duplicates: 0  Warnings: 0

+---+---------------------+
| a | b                   |
+---+---------------------+
| 1 | 2020-09-09 20:38:22 |
| 2 | 2020-09-09 20:38:22 |
| 3 | 2020-09-09 20:38:22 |
+---+---------------------+
3 rows in set (0.00 sec)
```

Monotonicity is not the same guarantee as consecutive. Consider the following example:

{{< copyable "sql" >}}

```sql
CREATE TABLE t (id INT NOT NULL PRIMARY KEY auto_increment, a VARCHAR(10), cnt INT NOT NULL DEFAULT 1, UNIQUE KEY (a));
INSERT INTO t (a) VALUES ('A'), ('B');
SELECT * FROM t;
INSERT INTO t (a) VALUES ('A'), ('C') ON DUPLICATE KEY UPDATE cnt = cnt + 1;
SELECT * FROM t;
```

```sql
Query OK, 0 rows affected (0.00 sec)

Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

+----+------+-----+
| id | a    | cnt |
+----+------+-----+
|  1 | A    |   1 |
|  2 | B    |   1 |
+----+------+-----+
2 rows in set (0.00 sec)

Query OK, 3 rows affected (0.00 sec)
Records: 2  Duplicates: 1  Warnings: 0

+----+------+-----+
| id | a    | cnt |
+----+------+-----+
|  1 | A    |   2 |
|  2 | B    |   1 |
|  4 | C    |   1 |
+----+------+-----+
3 rows in set (0.00 sec)
```

In this example, the `AUTO_INCREMENT` value of `3` is allocated for the `INSERT` of the key `A` in `INSERT INTO t (a) VALUES ('A'), ('C') ON DUPLICATE KEY UPDATE cnt = cnt + 1;` but never used because this `INSERT` statement contains a duplicate key `A`. This leads to a gap where the sequence is non-consecutive. This behavior is considered legal, even though it differs from MySQL. MySQL will also have gaps in the sequence in other scenarios such as transactions being aborted and rolled back.

## AUTO_ID_CACHE

The `AUTO_INCREMENT` sequence might appear to _jump_ dramatically if an `INSERT` operation is performed against a different TiDB server. This is caused by the fact that each server has its own cache of `AUTO_INCREMENT` values:

{{< copyable "sql" >}}

```sql
CREATE TABLE t (a int PRIMARY KEY AUTO_INCREMENT, b timestamp NOT NULL DEFAULT NOW());
INSERT INTO t (a) VALUES (NULL), (NULL), (NULL);
INSERT INTO t (a) VALUES (NULL);
SELECT * FROM t;
```

```sql
Query OK, 1 row affected (0.03 sec)

+---------+---------------------+
| a       | b                   |
+---------+---------------------+
|       1 | 2020-09-09 20:38:22 |
|       2 | 2020-09-09 20:38:22 |
|       3 | 2020-09-09 20:38:22 |
| 2000001 | 2020-09-09 20:43:43 |
+---------+---------------------+
4 rows in set (0.00 sec)
```

A new `INSERT` operation against the initial TiDB server generates the `AUTO_INCREMENT` value of `4`. This is because the initial TiDB server still has space left in the `AUTO_INCREMENT` cache for allocation. In this case, the sequence of values cannot be considered globally monotonic, because the value of `4` is inserted after the value of `2000001`:

```sql
mysql> INSERT INTO t (a) VALUES (NULL);
Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM t ORDER BY b;
+---------+---------------------+
| a       | b                   |
+---------+---------------------+
|       1 | 2020-09-09 20:38:22 |
|       2 | 2020-09-09 20:38:22 |
|       3 | 2020-09-09 20:38:22 |
| 2000001 | 2020-09-09 20:43:43 |
|       4 | 2020-09-09 20:44:43 |
+---------+---------------------+
5 rows in set (0.00 sec)
```

The `AUTO_INCREMENT` cache does not persist across TiDB server restarts. The following `INSERT` statement is performed after the initial TiDB server is restarted:

```sql
mysql> INSERT INTO t (a) VALUES (NULL);
Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM t ORDER BY b;
+---------+---------------------+
| a       | b                   |
+---------+---------------------+
|       1 | 2020-09-09 20:38:22 |
|       2 | 2020-09-09 20:38:22 |
|       3 | 2020-09-09 20:38:22 |
| 2000001 | 2020-09-09 20:43:43 |
|       4 | 2020-09-09 20:44:43 |
| 2030001 | 2020-09-09 20:54:11 |
+---------+---------------------+
6 rows in set (0.00 sec)
```

A high rate of TiDB server restarts might contribute to the exhaustion of `AUTO_INCREMENT` values. In the above example, the initial TiDB server still has values `[5-30000]` free in its cache. These values are lost, and will not be reallocated.

It is not recommended to rely on`AUTO_INCREMENT` values being continuous. Consider the following example, where a TiDB server has a cache of values `[2000001-2030000]`. By manually inserting the value `2029998`, you can see the behavior as a new cache range is retrieved:

```sql
mysql> INSERT INTO t (a) VALUES (2029998);
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO t (a) VALUES (NULL);
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO t (a) VALUES (NULL);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO t (a) VALUES (NULL);
Query OK, 1 row affected (0.02 sec)

mysql> INSERT INTO t (a) VALUES (NULL);
Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM t ORDER BY b;
+---------+---------------------+
| a       | b                   |
+---------+---------------------+
|       1 | 2020-09-09 20:38:22 |
|       2 | 2020-09-09 20:38:22 |
|       3 | 2020-09-09 20:38:22 |
| 2000001 | 2020-09-09 20:43:43 |
|       4 | 2020-09-09 20:44:43 |
| 2030001 | 2020-09-09 20:54:11 |
| 2029998 | 2020-09-09 21:08:11 |
| 2029999 | 2020-09-09 21:08:11 |
| 2030000 | 2020-09-09 21:08:11 |
| 2060001 | 2020-09-09 21:08:11 |
| 2060002 | 2020-09-09 21:08:11 |
+---------+---------------------+
11 rows in set (0.00 sec)
```

After the value `2030000` is inserted, the next value is `2060001`. This jump in sequence is due to another TiDB server obtaining the intermediate cache range of `[2030001-2060000]`. When multiple TiDB servers are deployed, there will be gaps in the `AUTO_INCREMENT` sequence because cache requests are interleaved.

### Cache size control

In earlier versions of TiDB, the cache size of the auto-increment ID was transparent to users. Starting from v3.0.14, v3.1.2, and v4.0.rc-2, TiDB has introduced the `AUTO_ID_CACHE` table option to allow users to set the cache size for allocating the auto-increment ID.

```sql
CREATE TABLE t(a int AUTO_INCREMENT key) AUTO_ID_CACHE 100;
Query OK, 0 rows affected (0.02 sec)

INSERT INTO t values();
Query OK, 1 row affected (0.00 sec)

SELECT * FROM t;
+---+
| a |
+---+
| 1 |
+---+
1 row in set (0.01 sec)

SHOW CREATE TABLE t;
+-------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                                                                                                             |
+-------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| t     | CREATE TABLE `t` (
  `a` int NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`a`) /*T![clustered_index] CLUSTERED */
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin AUTO_INCREMENT=101 /*T![auto_id_cache] AUTO_ID_CACHE=100 */ |
+-------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
```

At this time, if you restart TiDB, the auto-increment ID cache will be lost, and new insert operations will allocate IDs starting from a higher value beyond the previously cached range.

```sql
INSERT INTO t VALUES();
Query OK, 1 row affected (0.00 sec)

SELECT * FROM t;
+-----+
| a   |
+-----+
|   1 |
| 101 |
+-----+
2 rows in set (0.01 sec)
```

The newly allocated value is `101`. This shows that the size of cache for allocating auto-increment IDs is `100`.

In addition, when the length of consecutive IDs in a batch `INSERT` statement exceeds the length of `AUTO_ID_CACHE`, TiDB increases the cache size accordingly to ensure that the statement can insert data properly.

### Clear the auto-increment ID cache

In some scenarios, you might need to clear the auto-increment ID cache to ensure data consistency. For example:

<CustomContent platform="tidb">

- In the scenario of incremental replication using [Data Migration (DM)](/dm/dm-overview.md), once the replication is complete, data writing to the downstream TiDB switches from DM to your application's write operations. Meanwhile, the ID writing mode of the auto-increment column usually switches from explicit insertion to implicit allocation.
- After TiDB Lightning completes the data import, it automatically clears the auto-increment ID cache. However, TiCDC does not automatically clear the cache after incremental data synchronization. Therefore, you need to manually clear the auto-increment ID cache in the downstream cluster after stopping TiCDC, and before performing the failover.

</CustomContent>
<CustomContent platform="tidb-cloud">

- In the scenario of incremental replication using the [Data Migration](/tidb-cloud/migrate-incremental-data-from-mysql-using-data-migration.md) feature, once the replication is complete, data writing to the downstream TiDB switches from DM to your application's write operations. Meanwhile, the ID writing mode of the auto-increment column usually switches from explicit insertion to implicit allocation.
- After TiDB Lightning completes the data import, it automatically clears the auto-increment ID cache. However, TiCDC does not automatically clear the cache after incremental data synchronization. Therefore, you need to manually clear the auto-increment ID cache in the downstream cluster after stopping TiCDC, and before performing the failover.

</CustomContent>

- When your application involves both explicit ID insertion and implicit ID allocation, you need to clear the auto-increment ID cache to avoid conflicts between future implicitly allocated IDs and previously explicitly inserted IDs, which could result in primary key conflict errors. For more information, see [Uniqueness](/auto-increment.md#uniqueness).

To clear the auto-increment ID cache on all TiDB nodes in the cluster, you can execute the `ALTER TABLE` statement with `AUTO_INCREMENT = 0`. For example:

```sql
CREATE TABLE t(a int AUTO_INCREMENT key) AUTO_ID_CACHE 100;
Query OK, 0 rows affected (0.02 sec)

INSERT INTO t VALUES();
Query OK, 1 row affected (0.02 sec)

INSERT INTO t VALUES(50);
Query OK, 1 row affected (0.00 sec)

SELECT * FROM t;
+----+
| a  |
+----+
|  1 |
| 50 |
+----+
2 rows in set (0.01 sec)
```

```sql
ALTER TABLE t AUTO_INCREMENT = 0;
Query OK, 0 rows affected, 1 warning (0.07 sec)

SHOW WARNINGS;
+---------+------+-------------------------------------------------------------------------+
| Level   | Code | Message                                                                 |
+---------+------+-------------------------------------------------------------------------+
| Warning | 1105 | Can't reset AUTO_INCREMENT to 0 without FORCE option, using 101 instead |
+---------+------+-------------------------------------------------------------------------+
1 row in set (0.01 sec)

INSERT INTO t VALUES();
Query OK, 1 row affected (0.02 sec)

SELECT * FROM t;
+-----+
| a   |
+-----+
|   1 |
|  50 |
| 101 |
+-----+
3 rows in set (0.01 sec)
```

### Auto-increment step size and offset

Starting from v3.0.9 and v4.0.0-rc.1, similar to the behavior of MySQL, the value implicitly assigned to the auto-increment column is controlled by the `@@auto_increment_increment` and `@@auto_increment_offset` session variables.

The value (ID) implicitly assigned to auto-increment columns satisfies the following equation:

`(ID - auto_increment_offset) % auto_increment_increment == 0`

## MySQL compatibility mode

TiDB provides a MySQL-compatible mode for auto-increment columns that ensures strictly increasing IDs with minimal gaps. To enable this mode, set `AUTO_ID_CACHE` to `1` when creating a table:

```sql
CREATE TABLE t(a int AUTO_INCREMENT key) AUTO_ID_CACHE 1;
```

When `AUTO_ID_CACHE` is set to `1`, IDs are strictly increasing across all TiDB instances, each ID is guaranteed to be unique, and gaps between IDs are minimal compared to the default cache mode (`AUTO_ID_CACHE 0` with 30000 cached values).

For example, with `AUTO_ID_CACHE 1`, you might see a sequence as follows:

```sql
INSERT INTO t VALUES (); -- Returns ID 1
INSERT INTO t VALUES (); -- Returns ID 2
INSERT INTO t VALUES (); -- Returns ID 3
-- After failover
INSERT INTO t VALUES (); -- Might return ID 5
```

In contrast, with the default cache (`AUTO_ID_CACHE 0`), larger gaps can occur:

```sql
INSERT INTO t VALUES (); -- Returns ID 1
INSERT INTO t VALUES (); -- Returns ID 2
-- New TiDB instance allocates next batch
INSERT INTO t VALUES (); -- Returns ID 30001
```

While IDs are always increasing and without significant gaps like those seen with `AUTO_ID_CACHE 0`, small gaps in the sequence might still occur in the following scenarios. These gaps are necessary to maintain both uniqueness and the strictly increasing property of the IDs.

- During failover when the primary instance exits or crashes

    After you enable the MySQL compatibility mode, the allocated IDs are **unique** and **monotonically increasing**, and the behavior is almost the same as MySQL. Even when accessing across multiple TiDB instances, ID monotonicity is maintained. However, if the primary instance of the centralized service crashes, a few IDs might become non-continuous. This occurs because the secondary instance discards some IDs allocated by the primary instance during failover to ensure ID uniqueness.

- During rolling upgrades of TiDB nodes
- During normal concurrent transactions (similar to MySQL)

> **Note:**
>
> The behavior and performance of `AUTO_ID_CACHE 1` has evolved across TiDB versions:
>
> - Before v6.4.0, each ID allocation requires a TiKV transaction, which affects performance.
> - In v6.4.0, TiDB introduces a centralized allocating service that performs ID allocation as an in-memory operation, significantly improving performance.
> - Starting from v8.1.0, TiDB removes the automatic `forceRebase` operation during primary node exits to enable faster restarts. While this might result in additional non-consecutive IDs during failover, it prevents potential write blocking when many tables use `AUTO_ID_CACHE 1`.

## Restrictions

Currently, `AUTO_INCREMENT` has the following restrictions when used in TiDB:

- For TiDB v6.6.0 and earlier versions, the defined column must be either primary key or index prefixes.
- It must be defined on the column of `INTEGER`, `FLOAT`, or `DOUBLE` type.
- It cannot be specified on the same column with the `DEFAULT` column value.
- `ALTER TABLE` cannot be used to add or modify columns with the `AUTO_INCREMENT` attribute, including using `ALTER TABLE ... MODIFY/CHANGE COLUMN` to add the `AUTO_INCREMENT` attribute to an existing column, or using `ALTER TABLE ... ADD COLUMN` to add a column with the `AUTO_INCREMENT` attribute.
- `ALTER TABLE` can be used to remove the `AUTO_INCREMENT` attribute. However, starting from v2.1.18 and v3.0.4, TiDB uses the session variable `@@tidb_allow_remove_auto_inc` to control whether `ALTER TABLE MODIFY` or `ALTER TABLE CHANGE` can be used to remove the `AUTO_INCREMENT` attribute of a column. By default, you cannot use `ALTER TABLE MODIFY` or `ALTER TABLE CHANGE` to remove the `AUTO_INCREMENT` attribute.
- `ALTER TABLE` requires the `FORCE` option to set the `AUTO_INCREMENT` value to a smaller value.
- Setting the `AUTO_INCREMENT` to a value smaller than `MAX(<auto_increment_column>)` leads to duplicate keys because pre-existing values are not skipped.

---

## File: auto-random.md

---
title: AUTO_RANDOM
summary: Learn the AUTO_RANDOM attribute.
aliases: ['/docs/dev/auto-random/','/docs/dev/reference/sql/attributes/auto-random/']
---

# AUTO_RANDOM New in v3.1.0

## User scenario

Since the value of `AUTO_RANDOM` is random and unique, `AUTO_RANDOM` is often used in place of [`AUTO_INCREMENT`](/auto-increment.md) to avoid write hotspot in a single storage node caused by TiDB assigning consecutive IDs. If the current `AUTO_INCREMENT` column is a primary key and the type is `BIGINT`, you can execute the `ALTER TABLE t MODIFY COLUMN id BIGINT AUTO_RANDOM(5);` statement to switch from `AUTO_INCREMENT` to `AUTO_RANDOM`.

<CustomContent platform="tidb">

For more information about how to handle highly concurrent write-heavy workloads in TiDB, see [Best Practices for High-Concurrency Writes](/best-practices/high-concurrency-best-practices.md).

</CustomContent>

The `AUTO_RANDOM_BASE` parameter in the [CREATE TABLE](/sql-statements/sql-statement-create-table.md) statement is used to set the initial incremental part value of `auto_random`. This option can be considered as a part of the internal interface. You can ignore this parameter.

## Basic concepts

`AUTO_RANDOM` is a column attribute that is used to automatically assign values to a `BIGINT` column. Values assigned automatically are **random** and **unique**.

To create a table with an `AUTO_RANDOM` column, you can use the following statements. The `AUTO_RANDOM` column must be included in a primary key, and the `AUTO_RANDOM` column is the first column in the primary key.

```sql
CREATE TABLE t (a BIGINT AUTO_RANDOM, b VARCHAR(255), PRIMARY KEY (a));
CREATE TABLE t (a BIGINT PRIMARY KEY AUTO_RANDOM, b VARCHAR(255));
CREATE TABLE t (a BIGINT AUTO_RANDOM(6), b VARCHAR(255), PRIMARY KEY (a));
CREATE TABLE t (a BIGINT AUTO_RANDOM(5, 54), b VARCHAR(255), PRIMARY KEY (a));
CREATE TABLE t (a BIGINT AUTO_RANDOM(5, 54), b VARCHAR(255), PRIMARY KEY (a, b));
```

You can wrap the keyword `AUTO_RANDOM` in an executable comment. For more details, refer to [TiDB specific comment syntax](/comment-syntax.md#tidb-specific-comment-syntax).

```sql
CREATE TABLE t (a bigint /*T![auto_rand] AUTO_RANDOM */, b VARCHAR(255), PRIMARY KEY (a));
CREATE TABLE t (a bigint PRIMARY KEY /*T![auto_rand] AUTO_RANDOM */, b VARCHAR(255));
CREATE TABLE t (a BIGINT /*T![auto_rand] AUTO_RANDOM(6) */, b VARCHAR(255), PRIMARY KEY (a));
CREATE TABLE t (a BIGINT  /*T![auto_rand] AUTO_RANDOM(5, 54) */, b VARCHAR(255), PRIMARY KEY (a));
```

When you execute an `INSERT` statement:

- If you explicitly specify the value of the `AUTO_RANDOM` column, it is inserted into the table as is.
- If you do not explicitly specify the value of the `AUTO_RANDOM` column, TiDB generates a random value and inserts it into the table.

```sql
tidb> CREATE TABLE t (a BIGINT PRIMARY KEY AUTO_RANDOM, b VARCHAR(255)) /*T! PRE_SPLIT_REGIONS=2 */ ;
Query OK, 0 rows affected, 1 warning (0.01 sec)

tidb> INSERT INTO t(a, b) VALUES (1, 'string');
Query OK, 1 row affected (0.00 sec)

tidb> SELECT * FROM t;
+---+--------+
| a | b      |
+---+--------+
| 1 | string |
+---+--------+
1 row in set (0.01 sec)

tidb> INSERT INTO t(b) VALUES ('string2');
Query OK, 1 row affected (0.00 sec)

tidb> INSERT INTO t(b) VALUES ('string3');
Query OK, 1 row affected (0.00 sec)

tidb> SELECT * FROM t;
+---------------------+---------+
| a                   | b       |
+---------------------+---------+
|                   1 | string  |
| 1152921504606846978 | string2 |
| 4899916394579099651 | string3 |
+---------------------+---------+
3 rows in set (0.00 sec)

tidb> SHOW CREATE TABLE t;
+-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                                                                                                                                    |
+-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| t     | CREATE TABLE `t` (
  `a` bigint NOT NULL /*T![auto_rand] AUTO_RANDOM(5) */,
  `b` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`a`) /*T![clustered_index] CLUSTERED */
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin /*T! PRE_SPLIT_REGIONS=2 */ |
+-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

tidb> SHOW TABLE t REGIONS;
+-----------+-----------------------------+-----------------------------+-----------+-----------------+---------------------+------------+---------------+------------+----------------------+------------------+------------------------+------------------+
| REGION_ID | START_KEY                   | END_KEY                     | LEADER_ID | LEADER_STORE_ID | PEERS               | SCATTERING | WRITTEN_BYTES | READ_BYTES | APPROXIMATE_SIZE(MB) | APPROXIMATE_KEYS | SCHEDULING_CONSTRAINTS | SCHEDULING_STATE |
+-----------+-----------------------------+-----------------------------+-----------+-----------------+---------------------+------------+---------------+------------+----------------------+------------------+------------------------+------------------+
|     62798 | t_158_                      | t_158_r_2305843009213693952 |     62810 |              28 | 62811, 62812, 62810 |          0 |           151 |          0 |                    1 |                0 |                        |                  |
|     62802 | t_158_r_2305843009213693952 | t_158_r_4611686018427387904 |     62803 |               1 | 62803, 62804, 62805 |          0 |            39 |          0 |                    1 |                0 |                        |                  |
|     62806 | t_158_r_4611686018427387904 | t_158_r_6917529027641081856 |     62813 |               4 | 62813, 62814, 62815 |          0 |           160 |          0 |                    1 |                0 |                        |                  |
|      9289 | t_158_r_6917529027641081856 | 78000000                    |     48268 |               1 | 48268, 58951, 62791 |          0 |         10628 |      43639 |                    2 |             7999 |                        |                  |
+-----------+-----------------------------+-----------------------------+-----------+-----------------+---------------------+------------+---------------+------------+----------------------+------------------+------------------------+------------------+
4 rows in set (0.00 sec)
```

The `AUTO_RANDOM(S, R)` column value automatically assigned by TiDB has a total of 64 bits:

- `S` is the number of shard bits. The value ranges from `1` to `15`. The default value is `5`.
- `R` is the total length of the automatic allocation range. The value ranges from `32` to `64`. The default value is `64`.

The structure of an `AUTO_RANDOM` value with a signed bit is as follows:

| Signed bit | Reserved bits | Shard bits | Auto-increment bits |
|---------|-------------|--------|--------------|
| 1 bit | `64-R` bits | `S` bits | `R-1-S` bits |

The structure of an `AUTO_RANDOM` value without a signed bit is as follows:

| Reserved bits | Shard bits | Auto-increment bits |
|-------------|--------|--------------|
| `64-R` bits | `S` bits | `R-S` bits |

- Whether an `AUTO_RANDOM` column has a signed bit depends on whether the column has the `UNSIGNED` attribute. A column without the `UNSIGNED` attribute has one signed bit, while a column with the `UNSIGNED` attribute has no signed bit.
- Values implicitly allocated to an `AUTO_RANDOM` column are always positive. For columns with a signed bit, the signed bit of implicitly allocated values is always `0`. This rule does not apply to explicitly inserted values.
- The length of the reserved bits is `64-R`. The reserved bits are always `0`.
- The auto-increment bits must be at least 27 bits. For signed columns, `R-1-S >= 27` must be satisfied. For unsigned columns, `R-S >= 27` must be satisfied.
- The content of the shard bits is obtained by calculating the hash value of the starting time of the current transaction. To use a different length of shard bits (such as 10), you can specify `AUTO_RANDOM(10)` when creating the table.
- The value of the auto-increment bits is stored in the storage engine and allocated sequentially. Each time a new value is allocated, the value is incremented by 1. The auto-increment bits ensure that the values of `AUTO_RANDOM` are unique globally. When the auto-increment bits are exhausted, an error `Failed to read auto-increment value from storage engine` is reported when the value is allocated again.
- Value range: the maximum number of bits for the final generated value = shard bits + auto-increment bits. The range of a signed column is `[-(2^(R-1))+1, (2^(R-1))-1]`, and the range of an unsigned column is `[0, (2^R)-1]`.
- You can use `AUTO_RANDOM` with `PRE_SPLIT_REGIONS`. When a table is created successfully, `PRE_SPLIT_REGIONS` pre-splits data in the table into the number of Regions as specified by `2^(PRE_SPLIT_REGIONS)`.

> **Note:**
>
> Selection of shard bits (`S`):
>
> - Since there is a total of 64 available bits, the shard bits length affects the auto-increment bits length. That is, as the shard bits length increases, the length of auto-increment bits decreases, and vice versa. Therefore, you need to balance the randomness of allocated values and available space.
> - The best practice is to set the shard bits as `log(2, x)`, in which `x` is the current number of storage engines. For example, if there are 16 TiKV nodes in a TiDB cluster, you can set the shard bits as `log(2, 16)`, that is `4`. After all regions are evenly scheduled to each TiKV node, the load of bulk writes can be uniformly distributed to different TiKV nodes to maximize resource utilization.
>
> Selection of range (`R`):
>
> - Typically, the `R` parameter needs to be set when the numeric type of the application cannot represent a full 64-bit integer.
> - For example, the range of JSON number is `[-(2^53)+1, (2^53)-1]`. TiDB can easily assign an integer beyond this range to a column defined as `AUTO_RANDOM(5)`, causing unexpected behaviors when the application reads the column. In such cases, you can replace `AUTO_RANDOM(5)` with `AUTO_RANDOM(5, 54)` for signed columns, and replace `AUTO_RANDOM(5)` with `AUTO_RANDOM(5, 53)` for unsigned columns, ensuring that TiDB does not assign integers greater than `9007199254740991` (2^53-1) to the column.

Values allocated implicitly to the `AUTO_RANDOM` column affect `last_insert_id()`. To get the ID that TiDB last implicitly allocates, you can use the `SELECT last_insert_id ()` statement.

To view the shard bits number of the table with an `AUTO_RANDOM` column, you can execute the `SHOW CREATE TABLE` statement. You can also see the value of the `PK_AUTO_RANDOM_BITS=x` mode in the `TIDB_ROW_ID_SHARDING_INFO` column in the `information_schema.tables` system table. `x` is the number of shard bits.

After creating a table with an `AUTO_RANDOM` column, you can use `SHOW WARNINGS` to view the maximum implicit allocation times:

```sql
CREATE TABLE t (a BIGINT AUTO_RANDOM, b VARCHAR(255), PRIMARY KEY (a));
SHOW WARNINGS;
```

The output is as follows:

```sql
+-------+------+---------------------------------------------------------+
| Level | Code | Message                                                 |
+-------+------+---------------------------------------------------------+
| Note  | 1105 | Available implicit allocation times: 288230376151711743 |
+-------+------+---------------------------------------------------------+
1 row in set (0.00 sec)
```

## Implicit allocation rules of IDs

TiDB implicitly allocates values to `AUTO_RANDOM` columns similarly to `AUTO_INCREMENT` columns. They are also controlled by the session-level system variables [`auto_increment_increment`](/system-variables.md#auto_increment_increment) and [`auto_increment_offset`](/system-variables.md#auto_increment_offset). The auto-increment bits (ID) of implicitly allocated values conform to the equation `(ID - auto_increment_offset) % auto_increment_increment == 0`.

## Clear the auto-increment ID cache

When you insert data with explicit values into an `AUTO_RANDOM` column in a deployment with multiple TiDB server instances, potential ID collisions can occur, similar to an `AUTO_INCREMENT` column. If explicit inserts happen to use ID values that conflict with the internal counter TiDB uses for automatic generation, this can lead to errors. 

Here's how the collision can happen: each `AUTO_RANDOM` ID consists of random bits and an auto-incrementing part. TiDB uses an internal counter for this auto-incrementing part. If you explicitly insert an ID where the auto-incrementing part matches the counter's next value, a duplicate key error might occur when TiDB later attempts to generate the same ID automatically. For more details, see [AUTO_INCREMENT Uniqueness](/auto-increment.md#uniqueness).

With a single TiDB instance, this issue doesn't occur because the node automatically adjusts its internal counter when processing explicit insertions, preventing any future collisions. In contrast, with multiple TiDB nodes, each node maintains its own cache of IDs, which needs to be cleared to prevent collisions after explicit insertions. To clear these unallocated cached IDs and avoid potential collisions, you have two options: 

### Option 1: Automatically rebase (Recommended)

```sql
ALTER TABLE t AUTO_RANDOM_BASE=0;
```

This statement automatically determines an appropriate base value. Although it produces a warning message similar to `Can't reset AUTO_INCREMENT to 0 without FORCE option, using XXX instead`, the base value **will** change and you can safely ignore this warning.

> **Note:**
>
> You cannot set `AUTO_RANDOM_BASE` to `0` with the `FORCE` keyword. Attempting this results in an error.

### Option 2: Manually set a specific base value

If you need to set a specific base value (for example, `1000`), use the `FORCE` keyword:

```sql
ALTER TABLE t FORCE AUTO_RANDOM_BASE = 1000;
```

This approach is less convenient because it requires you to determine an appropriate base value yourself.

> **Note:**
>
> When using `FORCE`, you must specify a non-zero positive integer.

Both commands modify the starting point for the auto-increment bits used in subsequent `AUTO_RANDOM` value generations across all TiDB nodes. They do not affect already allocated IDs.

## Restrictions

Pay attention to the following restrictions when you use `AUTO_RANDOM`:

- To insert values explicitly, you need to set the value of the `@@allow_auto_random_explicit_insert` system variable to `1` (`0` by default). It is **not** recommended that you explicitly specify a value for the column with the `AUTO_RANDOM` attribute when you insert data. Otherwise, the numeral values that can be automatically allocated for this table might be used up in advance.
- Specify this attribute for the primary key column **ONLY** as the `BIGINT` type. Otherwise, an error occurs. In addition, when the attribute of the primary key is `NONCLUSTERED`, `AUTO_RANDOM` is not supported even on the integer primary key. For more details about the primary key of the `CLUSTERED` type, refer to [clustered index](/clustered-indexes.md).
- You cannot use `ALTER TABLE` to modify the `AUTO_RANDOM` attribute, including adding or removing this attribute.
- You cannot use `ALTER TABLE` to change from `AUTO_INCREMENT` to `AUTO_RANDOM` if the maximum value is close to the maximum value of the column type.
- You cannot change the column type of the primary key column that is specified with `AUTO_RANDOM` attribute.
- You cannot specify `AUTO_RANDOM` and `AUTO_INCREMENT` for the same column at the same time.
- You cannot specify `AUTO_RANDOM` and `DEFAULT` (the default value of a column) for the same column at the same time.
- When`AUTO_RANDOM` is used on a column, it is difficult to change the column attribute back to `AUTO_INCREMENT` because the auto-generated values might be very large.

---

## File: backup-and-restore-using-dumpling-lightning.md

---
title: Back up and Restore Data Using Dumpling and TiDB Lightning
summary: Learn how to use Dumpling and TiDB Lightning to back up and restore full data of TiDB.
---

# Back up and Restore Data Using Dumpling and TiDB Lightning

This document introduces how to use Dumpling and TiDB Lightning to back up and restore full data of TiDB.

If you need to back up a small amount of data (for example, less than 50 GiB) and do not require high backup speed, you can use [Dumpling](/dumpling-overview.md) to export data from the TiDB database and then use [TiDB Lightning](/tidb-lightning/tidb-lightning-overview.md) to restore the data into another TiDB database. 

If you need to back up larger databases, the recommended method is to use [BR](/br/backup-and-restore-overview.md). Note that Dumpling can be used to export large databases, but BR is a better tool for that.

## Requirements

- Install Dumpling:

    ```shell
    tiup install dumpling
    ```

- Install TiDB Lightning:

    ```shell
    tiup install tidb-lightning
    ```

- [Grant the source database privileges required for Dumpling](/dumpling-overview.md#export-data-from-tidb-or-mysql)
- [Grant the target database privileges required for TiDB Lightning](/tidb-lightning/tidb-lightning-requirements.md#privileges-of-the-target-database)

## Resource requirements

**Operating system**: The example in this document uses fresh CentOS 7 instances. You can deploy a virtual machine either on your local host or in the cloud. Because TiDB Lightning consumes as much CPU resources as needed by default, it is recommended that you deploy it on a dedicated server. If this is not possible, you can deploy it on a single server together with other TiDB components (for example, `tikv-server`) and then configure `region-concurrency` to limit the CPU usage from TiDB Lightning. Usually, you can configure the size to 75% of the logical CPU.

**Memory and CPU**: Because TiDB Lightning consumes high resources, it is recommended to allocate more than 64 GiB of memory and more than 32 CPU cores. To get the best performance, make sure that the CPU core to memory (GiB) ratio is greater than 1:2.

**Disk space**:

It is recommended to use Amazon S3, Google Cloud Storage (GCS), or Azure Blob Storage as the external storage. With such a cloud storage, you can store backup files quickly without being limited by the disk space.

If you need to save data of one backup task to the local disk, note the following limitations:

- Dumpling requires a disk space that can store the whole data source (or to store all upstream tables to be exported). To calculate the required space, see [Downstream storage space requirements](/tidb-lightning/tidb-lightning-requirements.md#storage-space-of-the-target-database).
- During the import, TiDB Lightning needs temporary space to store the sorted key-value pairs. The disk space should be enough to hold the largest single table from the data source.

**Note**: It is difficult to calculate the exact data volume exported by Dumpling from MySQL, but you can estimate the data volume by using the following SQL statement to summarize the `DATA_LENGTH` field in the `information_schema.tables` table:

```sql
-- Calculate the size of all schemas
SELECT
  TABLE_SCHEMA,
  FORMAT_BYTES(SUM(DATA_LENGTH)) AS 'Data Size',
  FORMAT_BYTES(SUM(INDEX_LENGTH)) 'Index Size'
FROM
  information_schema.tables
GROUP BY
  TABLE_SCHEMA;

-- Calculate the 5 largest tables
SELECT 
  TABLE_NAME,
  TABLE_SCHEMA,
  FORMAT_BYTES(SUM(data_length)) AS 'Data Size',
  FORMAT_BYTES(SUM(index_length)) AS 'Index Size',
  FORMAT_BYTES(SUM(data_length+index_length)) AS 'Total Size'
FROM
  information_schema.tables
GROUP BY
  TABLE_NAME,
  TABLE_SCHEMA
ORDER BY
  SUM(DATA_LENGTH+INDEX_LENGTH) DESC
LIMIT
  5;
```

### Disk space for the target TiKV cluster

The target TiKV cluster must have enough disk space to store the imported data. In addition to [the standard hardware requirements](/hardware-and-software-requirements.md), the storage space of the target TiKV cluster must be larger than **the size of the data source x [the number of replicas](/faq/manage-cluster-faq.md#is-the-number-of-replicas-in-each-region-configurable-if-yes-how-to-configure-it) x 2**. For example, if the cluster uses 3 replicas by default, the target TiKV cluster must have a storage space larger than 6 times the size of the data source. The formula has x 2 because:

- Index might take extra space.
- RocksDB has a space amplification effect.

## Use Dumpling to back up full data

1. Run the following command to export full data from TiDB to `s3://my-bucket/sql-backup` in Amazon S3:

    ```shell
    tiup dumpling -h ${ip} -P 3306 -u root -t 16 -r 200000 -F 256MiB -B my_db1 -f 'my_db1.table[12]' -o 's3://my-bucket/sql-backup'
    ```

    Dumpling exports data in SQL files by default. You can specify a different file format by adding the `--filetype` option.

    For more configurations of Dumpling, see [Option list of Dumpling](/dumpling-overview.md#option-list-of-dumpling).

2. After the export is completed, you can view the backup files in the directory `s3://my-bucket/sql-backup`.

## Use TiDB Lightning to restore full data

1. Edit the `tidb-lightning.toml` file to import full data backed up using Dumpling from `s3://my-bucket/sql-backup` to the target TiDB cluster:

    ```toml
    [lightning]
    # log
    level = "info"
    file = "tidb-lightning.log"

    [tikv-importer]
    # "local": Default backend. The local backend is recommended to import large volumes of data (1 TiB or more). During the import, the target TiDB cluster cannot provide any service.
    # "tidb": The "tidb" backend is recommended to import data less than 1 TiB. During the import, the target TiDB cluster can provide service normally. For more information on the backends, refer to https://docs.pingcap.com/tidb/stable/tidb-lightning-backends.
    backend = "local"
    # Sets the temporary storage directory for the sorted Key-Value files. The directory must be empty, and the storage space must be greater than the size of the dataset to be imported. For better import performance, it is recommended to use a directory different from `data-source-dir` and use flash storage, which can use I/O exclusively.
    sorted-kv-dir = "${sorted-kv-dir}"

    [mydumper]
    # The data source directory. The same directory where Dumpling exports data in "Use Dumpling to back up full data".
    data-source-dir = "${data-path}" #  A local path or S3 path. For example, 's3://my-bucket/sql-backup'

    [tidb]
    # The target TiDB cluster information.
    host = "${host}"              # e.g.: 172.16.32.1
    port = "${port}"              # e.g.: 4000
    user = "${user_name}"         # e.g.: "root"
    password = "${password}"      # e.g.: "rootroot"
    status-port = "${status-port}"  # During the import, TiDB Lightning needs to obtain the table schema information from the TiDB status port. e.g.: 10080
    pd-addr = "${ip}:${port}"     # The address of the PD cluster, e.g.: 172.16.31.3:2379. TiDB Lightning obtains some information from PD. When backend = "local", you must specify status-port and pd-addr correctly. Otherwise, the import will be abnormal.
    ```

    For more information on TiDB Lightning configuration, refer to [TiDB Lightning Configuration](/tidb-lightning/tidb-lightning-configuration.md).

2. Start the import by running `tidb-lightning`. If you launch the program directly in the command line, the process might exit unexpectedly after receiving a `SIGHUP` signal. In this case, it is recommended to run the program using a `nohup` or `screen` tool. For example:

    If you import data from S3, pass the SecretKey and AccessKey that have access to the S3 storage path as environment variables to the TiDB Lightning node. You can also read the credentials from `~/.aws/credentials`.

    ```shell
    export AWS_ACCESS_KEY_ID=${access_key}
    export AWS_SECRET_ACCESS_KEY=${secret_key}
    nohup tiup tidb-lightning -config tidb-lightning.toml > nohup.out 2>&1 &
    ```

3. After the import starts, you can `grep` the keyword `progress` in the log to check the progress of the import. The progress is updated every 5 minutes by default.

4. After TiDB Lightning completes the import, it exits automatically. Check whether `tidb-lightning.log` contains `the whole procedure completed` in the last lines. If yes, the import is successful. If no, the import encounters an error. Address the error as instructed in the error message.

> **Note:**
>
> Whether the import is successful or not, the last line of the log shows `tidb lightning exit`. It means that TiDB Lightning exits normally, but does not necessarily mean that the import is successful.

If the import fails, refer to [TiDB Lightning FAQ](/tidb-lightning/tidb-lightning-faq.md) for troubleshooting.

---

## File: basic-features.md

---
title: TiDB Features
summary: Learn about the feature overview of TiDB.
aliases: ['/docs/dev/basic-features/','/tidb/dev/experimental-features-4.0/']
---

# TiDB Features

This document lists the features supported in different TiDB versions, including [Long-Term Support (LTS)](/releases/versioning.md#long-term-support-releases) versions and [Development Milestone Release (DMR)](/releases/versioning.md#development-milestone-releases) versions after the latest LTS version.

You can try out TiDB features on [TiDB Playground](https://play.tidbcloud.com/?utm_source=docs&utm_medium=tidb_features).

> **Note:**
>
> PingCAP does not provide patch releases for DMR versions. Any bugs will be fixed in future releases. For general purposes, it is recommended to use the [latest LTS version](https://docs.pingcap.com/tidb/stable).
>
> The abbreviations in the table below have the following meanings:
>
> - Y: the feature is generally available (GA) and can be used in production environments. Note that even if a feature is GA in a DMR version, it is recommended to use the feature in production environments in a later LTS version.
> - N: the feature is not supported.
> - E: the feature is not GA yet (experimental) and you need to be aware of the usage limitations. Experimental features are subject to change or removal without prior notice. The syntax and implementation might be modified before the general availability. If you encounter any problems, you can report an [issue](https://github.com/pingcap/tidb/issues) on GitHub.

## Data types, functions, and operators

<StickyHeaderTable>

| Data types, functions, and operators | 8.5 | 8.1 | 7.5 | 7.1 | 6.5 | 6.1 | 5.4 |
|---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| [Numeric types](/data-type-numeric.md) | Y | Y | Y | Y | Y | Y | Y |
| [Date and time types](/data-type-date-and-time.md) | Y | Y | Y | Y | Y | Y | Y |
| [String types](/data-type-string.md) | Y | Y | Y | Y | Y | Y | Y |
| [JSON type](/data-type-json.md) | Y | Y | Y | Y | Y | E | E |
| [Vector types](/ai/reference/vector-search-data-types.md) | E | N | N | N | N | N | N |
| [Control flow functions](/functions-and-operators/control-flow-functions.md) | Y | Y | Y | Y | Y | Y | Y |
| [String functions](/functions-and-operators/string-functions.md) | Y | Y | Y | Y | Y | Y | Y |
| [Numeric functions and operators](/functions-and-operators/numeric-functions-and-operators.md) | Y | Y | Y | Y | Y | Y | Y |
| [Date and time functions](/functions-and-operators/date-and-time-functions.md) | Y | Y | Y | Y | Y | Y | Y |
| [Bit functions and operators](/functions-and-operators/bit-functions-and-operators.md) | Y | Y | Y | Y | Y | Y | Y |
| [Cast functions and operators](/functions-and-operators/cast-functions-and-operators.md) | Y | Y | Y | Y | Y | Y | Y |
| [Encryption and compression functions](/functions-and-operators/encryption-and-compression-functions.md) | Y | Y | Y | Y | Y | Y | Y |
| [Vector functions and operators](/ai/reference/vector-search-functions-and-operators.md) | E | N | N | N | N | N | N |
| [Information functions](/functions-and-operators/information-functions.md) | Y | Y | Y | Y | Y | Y | Y |
| [JSON functions](/functions-and-operators/json-functions.md) | Y | Y | Y | Y | Y | E | E |
| [Aggregation functions](/functions-and-operators/aggregate-group-by-functions.md) | Y | Y | Y | Y | Y | Y | Y |
| [Window functions](/functions-and-operators/window-functions.md) | Y | Y | Y | Y | Y | Y | Y |
| [Miscellaneous functions](/functions-and-operators/miscellaneous-functions.md) | Y | Y | Y | Y | Y | Y | Y |
| [Operators](/functions-and-operators/operators.md) | Y | Y | Y | Y | Y | Y | Y |
| [Character sets and collations](/character-set-and-collation.md) [^1] | Y | Y | Y | Y | Y | Y | Y |
| [User-level lock](/functions-and-operators/locking-functions.md) | Y | Y | Y | Y | Y | Y | N |

</StickyHeaderTable>

## Indexing and constraints

<StickyHeaderTable>

| Indexing and constraints | 8.5 | 8.1 | 7.5 | 7.1 | 6.5 | 6.1 | 5.4 |
|---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| [Expression indexes](/sql-statements/sql-statement-create-index.md#expression-index) [^2] | Y | Y | Y | Y | Y | E | E |
| [Columnar storage (TiFlash)](/tiflash/tiflash-overview.md) | Y | Y | Y | Y | Y | Y | Y |
| [Use FastScan to accelerate queries in OLAP scenarios](/tiflash/use-fastscan.md) | Y | Y | Y | Y | E | N | N |
| [RocksDB engine](/storage-engine/rocksdb-overview.md) | Y | Y | Y | Y | Y | Y | Y |
| [Titan plugin](/storage-engine/titan-overview.md) | Y | Y | Y | Y | Y | Y | Y |
| [Titan Level Merge](/storage-engine/titan-configuration.md#level-merge-experimental) | E | E | E | E | E | E | E |
| [Use buckets to improve scan concurrency](/tune-region-performance.md#use-bucket-to-increase-concurrency) | E | E | E | E | E | E | N |
| [Invisible indexes](/sql-statements/sql-statement-create-index.md#invisible-index) | Y | Y | Y | Y | Y | Y | Y |
| [Composite `PRIMARY KEY`](/constraints.md) | Y | Y | Y | Y | Y | Y | Y |
| [`CHECK` constraints](/constraints.md#check) | Y | Y | Y | N | N | N | N |
| [Unique indexes](/constraints.md) | Y | Y | Y | Y | Y | Y | Y |
| [Clustered index on integer `PRIMARY KEY`](/clustered-indexes.md) | Y | Y | Y | Y | Y | Y | Y |
| [Clustered index on composite or non-integer key](/clustered-indexes.md) | Y | Y | Y | Y | Y | Y | Y |
| [Multi-valued indexes](/sql-statements/sql-statement-create-index.md#multi-valued-indexes) | Y | Y | Y | Y | N | N | N |
| [Foreign key](/foreign-key.md) | Y | E | E | E | N | N | N |
| [TiFlash late materialization](/tiflash/tiflash-late-materialization.md) | Y | Y | Y | Y | N | N | N |
| [Global indexes](/global-indexes.md) | Y |  N | N  | N | N | N | N |
| [Vector indexes](/ai/reference/vector-search-index.md) | E | N | N | N | N | N | N |

</StickyHeaderTable>

## SQL statements

<StickyHeaderTable>

| SQL statements [^3] | 8.5 | 8.1 | 7.5 | 7.1 | 6.5 | 6.1 | 5.4 |
|---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| Basic `SELECT`, `INSERT`, `UPDATE`, `DELETE`, `REPLACE` | Y | Y | Y | Y | Y | Y | Y |
| `INSERT ON DUPLICATE KEY UPDATE` | Y | Y | Y | Y | Y | Y | Y |
| `LOAD DATA INFILE` | Y | Y | Y | Y | Y | Y | Y |
| `SELECT INTO OUTFILE` | Y | Y | Y | Y | Y | Y | Y |
| `INNER JOIN`, `LEFT\|RIGHT [OUTER] JOIN` | Y | Y | Y | Y | Y | Y | Y |
| `UNION`, `UNION ALL` | Y | Y | Y | Y | Y | Y | Y |
| [`EXCEPT` and `INTERSECT` operators](/functions-and-operators/set-operators.md) | Y | Y | Y | Y | Y | Y | Y |
| `GROUP BY`, `ORDER BY` | Y | Y | Y | Y | Y | Y | Y |
| [`GROUP BY` modifier](/functions-and-operators/group-by-modifier.md) | Y | Y | Y | N | N | N | N |
| [Window Functions](/functions-and-operators/window-functions.md) | Y | Y | Y | Y | Y | Y | Y |
| [Common Table Expressions (CTE)](/sql-statements/sql-statement-with.md) | Y | Y | Y | Y | Y | Y | Y |
| `START TRANSACTION`, `COMMIT`, `ROLLBACK` | Y | Y | Y | Y | Y | Y | Y |
| [`EXPLAIN`](/sql-statements/sql-statement-explain.md) | Y | Y | Y | Y | Y | Y | Y |
| [`EXPLAIN ANALYZE`](/sql-statements/sql-statement-explain-analyze.md) | Y | Y | Y | Y | Y | Y | Y |
| [User-defined variables](/user-defined-variables.md) | E | E | E | E | E | E | E |
| [`BATCH [ON COLUMN] LIMIT INTEGER DELETE`](/sql-statements/sql-statement-batch.md) | Y | Y | Y | Y | Y | Y | N |
| [`BATCH [ON COLUMN] LIMIT INTEGER INSERT/UPDATE/REPLACE`](/sql-statements/sql-statement-batch.md) | Y | Y | Y | Y | Y | N | N |
| [`ALTER TABLE ... COMPACT`](/sql-statements/sql-statement-alter-table-compact.md) | Y | Y | Y | Y | Y | E | N |
| [Table Lock](/sql-statements/sql-statement-lock-tables-and-unlock-tables.md) | E | E | E | E | E | E | E |
| [TiFlash Query Result Materialization](/tiflash/tiflash-results-materialization.md) | Y | Y | Y | Y | E | N | N |

</StickyHeaderTable>

## Advanced SQL features

<StickyHeaderTable>

| Advanced SQL features | 8.5 | 8.1 | 7.5 | 7.1 | 6.5 | 6.1 | 5.4 |
|---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| [Vector search](/ai/concepts/vector-search-overview.md) |  E |  N |  N  | N | N | N | N |
| [Prepared statement cache](/sql-prepared-plan-cache.md) | Y | Y | Y | Y | Y | Y | Y |
| [Non-prepared statement cache](/sql-non-prepared-plan-cache.md) | Y | Y | Y | E | N | N | N |
| [Instance-level execution plan cache](/system-variables.md#tidb_enable_instance_plan_cache-new-in-v840) | E | N | N | N | N | N | N |
| [SQL binding](/sql-plan-management.md#sql-binding) | Y | Y | Y | Y | Y | Y | Y |
| [Cross-database binding](/sql-plan-management.md#cross-database-binding) | Y | Y | N | N | N | N | N |
| [Create bindings according to historical execution plans](/sql-plan-management.md#create-a-binding-according-to-a-historical-execution-plan) | Y | Y | Y | Y | E | N | N |
| [Coprocessor cache](/coprocessor-cache.md) | Y | Y | Y | Y | Y | Y | Y |
| [Stale Read](/stale-read.md) | Y | Y | Y | Y | Y | Y | Y |
| [Follower reads](/follower-read.md) | Y | Y | Y | Y | Y | Y | Y |
| [Read historical data (tidb_snapshot)](/read-historical-data.md) | Y | Y | Y | Y | Y | Y | Y |
| [Optimizer hints](/optimizer-hints.md) | Y | Y | Y | Y | Y | Y | Y |
| [MPP execution engine](/explain-mpp.md) | Y | Y | Y | Y | Y | Y | Y |
| [MPP execution engine - compression exchange](/explain-mpp.md#mpp-version-and-exchange-data-compression) | Y | Y | Y | Y | N | N | N |
| [TiFlash Pipeline Model](/tiflash/tiflash-pipeline-model.md) | Y | Y | Y | N | N | N | N |
| [TiFlash replica selection strategy](/system-variables.md#tiflash_replica_read-new-in-v730) | Y | Y | Y | N | N | N | N |
| [Index Merge](/explain-index-merge.md) | Y | Y | Y | Y | Y | Y | Y |
| [Placement Rules in SQL](/placement-rules-in-sql.md) | Y | Y | Y | Y | Y | Y | E |
| [Cascades Planner](/system-variables.md#tidb_enable_cascades_planner) | E | E | E | E | E | E | E |
| [Runtime Filter](/runtime-filter.md) | Y | Y | Y | N | N | N | N |

</StickyHeaderTable>

## Data definition language (DDL)

<StickyHeaderTable>

| Data definition language (DDL) | 8.5 | 8.1 | 7.5 | 7.1 | 6.5 | 6.1 | 5.4 |
|---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| Basic `CREATE`, `DROP`, `ALTER`, `RENAME`, `TRUNCATE` | Y | Y | Y | Y | Y | Y | Y |
| [Generated columns](/generated-columns.md) | Y | Y | Y | Y | E | E | E |
| [Views](/views.md) | Y | Y | Y | Y | Y | Y | Y |
| [Sequences](/sql-statements/sql-statement-create-sequence.md) | Y | Y | Y | Y | Y | Y | Y |
| [Auto increment](/auto-increment.md) | Y | Y | Y | Y | Y[^4] | Y | Y |
| [Auto random](/auto-random.md) | Y | Y | Y | Y | Y | Y | Y |
| [TTL (Time to Live)](/time-to-live.md) | Y | Y | Y | Y | E | N | N |
| [DDL algorithm assertions](/sql-statements/sql-statement-alter-table.md) | Y | Y | Y | Y | Y | Y | Y |
| Multi-schema change: add columns | Y | Y | Y | Y | Y | E | E |
| [Change column type](/sql-statements/sql-statement-modify-column.md) | Y | Y | Y | Y | Y | Y | Y |
| [Temporary tables](/temporary-tables.md) | Y | Y | Y | Y | Y | Y | Y |
| Concurrent DDL statements | Y | Y | Y | Y | Y | N | N |
| [Acceleration of `ADD INDEX` and `CREATE INDEX`](/system-variables.md#tidb_ddl_enable_fast_reorg-new-in-v630) | Y | Y | Y | Y | Y | N | N |
| [Metadata lock](/metadata-lock.md) | Y | Y | Y | Y | Y | N | N |
| [`FLASHBACK CLUSTER`](/sql-statements/sql-statement-flashback-cluster.md) | Y | Y | Y | Y | Y | N | N |
| [Pause](/sql-statements/sql-statement-admin-pause-ddl.md)/[Resume](/sql-statements/sql-statement-admin-resume-ddl.md) DDL | Y | Y | Y | N | N | N | N |
| [TiDB Accelerated Table Creation](/accelerated-table-creation.md) | Y | E | N | N | N | N | N |
| [Configure BDR role to replicate DDL statements in BDR mode](/sql-statements/sql-statement-admin-bdr-role.md#admin-setshowunset-bdr-role) | Y | E | N | N | N | N | N |

</StickyHeaderTable>

## Transactions

<StickyHeaderTable>

| Transactions | 8.5 | 8.1 | 7.5 | 7.1 | 6.5 | 6.1 | 5.4 |
|---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| [Async commit](/system-variables.md#tidb_enable_async_commit-new-in-v50) | Y | Y | Y | Y | Y | Y | Y |
| [1PC](/system-variables.md#tidb_enable_1pc-new-in-v50) | Y | Y | Y | Y | Y | Y | Y |
| [Large transactions (1 TiB)](/transaction-overview.md#transaction-size-limit) | Y | Y | Y | Y | Y | Y | Y |
| [Pessimistic transactions](/pessimistic-transaction.md) | Y | Y | Y | Y | Y | Y | Y |
| [Optimistic transactions](/optimistic-transaction.md) | Y | Y | Y | Y | Y | Y | Y |
| [Repeatable-read isolation (snapshot isolation)](/transaction-isolation-levels.md) | Y | Y | Y | Y | Y | Y | Y |
| [Read-committed isolation](/transaction-isolation-levels.md) | Y | Y | Y | Y | Y | Y | Y |
| [Automatically terminating long-running idle transactions](/system-variables.md#tidb_idle_transaction_timeout-new-in-v760) | Y | Y | N | N | N | N | N |
| [Bulk DML execution mode (`tidb_dml_type = "bulk"`)](/system-variables.md#tidb_dml_type-new-in-v800) | E |  E | N | N | N | N | N |

</StickyHeaderTable>

## Partitioning

<StickyHeaderTable>

| Partitioning | 8.5 | 8.1 | 7.5 | 7.1 | 6.5 | 6.1 | 5.4 |
|---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| [Range partitioning](/partitioned-table.md#range-partitioning) | Y | Y | Y | Y | Y | Y | Y |
| [Hash partitioning](/partitioned-table.md#hash-partitioning) | Y | Y | Y | Y | Y | Y | Y |
| [Key partitioning](/partitioned-table.md#key-partitioning) | Y | Y | Y | Y | N | N | N |
| [List partitioning](/partitioned-table.md#list-partitioning) | Y | Y | Y | Y | Y | Y | E |
| [List COLUMNS partitioning](/partitioned-table.md) | Y | Y | Y | Y | Y | Y | E |
| [Default partition for List and List COLUMNS partitioned tables](/partitioned-table.md#default-list-partition) | Y | Y | Y | N | N | N | N |
| [`EXCHANGE PARTITION`](/partitioned-table.md) | Y | Y | Y | Y | Y | E | E |
| [`REORGANIZE PARTITION`](/partitioned-table.md#reorganize-partitions) | Y | Y | Y | Y | N | N | N |
| [`COALESCE PARTITION`](/partitioned-table.md#decrease-the-number-of-partitions) | Y | Y | Y | Y | N | N | N |
| [Dynamic pruning](/partitioned-table.md#dynamic-pruning-mode) | Y | Y | Y | Y | Y | Y | E |
| [Range COLUMNS partitioning](/partitioned-table.md#range-columns-partitioning) | Y | Y | Y | Y | Y | N | N |
| [Range INTERVAL partitioning](/partitioned-table.md#range-interval-partitioning) | Y | Y | Y | Y | E | N | N |
| [Convert a partitioned table to a non-partitioned table](/partitioned-table.md#convert-a-partitioned-table-to-a-non-partitioned-table) | Y | Y | Y | N | N | N | N |
| [Partition an existing table](/partitioned-table.md#partition-an-existing-table) | Y | Y | Y | N | N | N | N |
| [Global indexes](/global-indexes.md) | Y | N | N | N | N | N | N |

</StickyHeaderTable>

## Statistics

<StickyHeaderTable>

| Statistics | 8.5 | 8.1 | 7.5 | 7.1 | 6.5 | 6.1 | 5.4 |
|---|---|---|---|---|---|---|---|
| [CMSketch](/statistics.md) | Disabled by default | Disabled by default | Disabled by default | Disabled by default | Disabled by default | Disabled by default | Disabled by default |
| [Histograms](/statistics.md) | Y | Y | Y | Y | Y | Y | Y |
| [Extended statistics](/extended-statistics.md) | E | E | E | E | E | E | E |
| Statistics feedback | N | N | N | N | N | Deprecated | Deprecated |
| [Automatically update statistics](/statistics.md#automatic-update) | Y | Y | Y | Y | Y | Y | Y |
| [Dynamic pruning](/partitioned-table.md#dynamic-pruning-mode) | Y | Y | Y | Y | Y | Y | E |
| [Collect statistics for `PREDICATE COLUMNS`](/statistics.md#collect-statistics-on-some-columns) | Y | E | E | E | E | E | E |
| [Control the memory quota for collecting statistics](/statistics.md#the-memory-quota-for-collecting-statistics) | E | E | E | E | E | E | N |
| [Randomly sample about 10000 rows of data to quickly build statistics](/system-variables.md#tidb_enable_fast_analyze) | Deprecated | Deprecated | Deprecated | E | E | E | E |
| [Lock statistics](/statistics.md#lock-statistics) | Y | Y | Y | E | E | N | N |
| [Lightweight statistics initialization](/statistics.md#load-statistics) | Y | Y | Y | E | N | N | N |
| [Show the progress of collecting statistics](/sql-statements/sql-statement-show-analyze-status.md) | Y | Y | Y | N | N | N | N |

</StickyHeaderTable>

## Security

<StickyHeaderTable>

| Security | 8.5 | 8.1 | 7.5 | 7.1 | 6.5 | 6.1 | 5.4 |
|---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| [Transparent layer security (TLS)](/enable-tls-between-clients-and-servers.md) | Y | Y | Y | Y | Y | Y | Y |
| [Encryption at rest (TDE)](/encryption-at-rest.md) | Y | Y | Y | Y | Y | Y | Y |
| [Role-based authentication (RBAC)](/role-based-access-control.md) | Y | Y | Y | Y | Y | Y | Y |
| [Certificate-based authentication](/certificate-authentication.md) | Y | Y | Y | Y | Y | Y | Y |
| [`caching_sha2_password` authentication](/system-variables.md#default_authentication_plugin) | Y | Y | Y | Y | Y | Y | Y |
| [`tidb_sm3_password` authentication](/system-variables.md#default_authentication_plugin) | Y | Y | Y | Y | Y | N | N |
| [`tidb_auth_token` authentication](/security-compatibility-with-mysql.md#tidb_auth_token) | Y | Y | Y | Y | Y | N | N |
| [`authentication_ldap_sasl` authentication](/system-variables.md#default_authentication_plugin) | Y | Y | Y | N | N | N | N |
| [`authentication_ldap_simple` authentication](/system-variables.md#default_authentication_plugin) | Y | Y | Y | Y | N | N | N |
| [Password management](/password-management.md) | Y | Y | Y | Y | Y | N | N |
| [MySQL compatible `GRANT` system](/privilege-management.md) | Y | Y | Y | Y | Y | Y | Y |
| [Dynamic Privileges](/privilege-management.md#dynamic-privileges) | Y | Y | Y | Y | Y | Y | Y |
| [Security Enhanced Mode](/system-variables.md#tidb_enable_enhanced_security) | Y | Y | Y | Y | Y | Y | Y |
| [Redacted Log Files](/log-redaction.md) | Y | Y | Y | Y | Y | Y | Y |

</StickyHeaderTable>

## Data import and export

<StickyHeaderTable>

| Data import and export | 8.5 | 8.1 | 7.5 | 7.1 | 6.5 | 6.1 | 5.4 |
|---|---|---|---|---|---|---|---|
| [Fast import using TiDB Lightning](/tidb-lightning/tidb-lightning-overview.md) | Y | Y | Y | Y | Y | Y | Y |
| [Fast import using the `IMPORT INTO` statement](/sql-statements/sql-statement-import-into.md) | Y | Y | Y | N | N | N | N |
| mydumper logical dumper | Deprecated | Deprecated | Deprecated | Deprecated | Deprecated | Deprecated | Deprecated |
| [Dumpling logical dumper](/dumpling-overview.md) | Y | Y | Y | Y | Y | Y | Y |
| [Transactional `LOAD DATA`](/sql-statements/sql-statement-load-data.md) [^5] | Y | Y | Y | Y | Y | Y | Y |
| [Database migration toolkit (DM)](/migration-overview.md) | Y | Y | Y | Y | Y | Y | Y |
| [TiDB Binlog](https://docs-archive.pingcap.com/tidb/v8.3/tidb-binlog-overview/) [^6] | Removed | Y | Y | Y | Y | Y | Y |
| [Change data capture (CDC)](/ticdc/ticdc-overview.md) | Y | Y | Y | Y | Y | Y | Y |
| [Stream data to Amazon S3, GCS, Azure Blob Storage, and NFS through TiCDC](/ticdc/ticdc-sink-to-cloud-storage.md) | Y | Y | Y | Y | E | N | N |
| [TiCDC supports bidirectional replication between two TiDB clusters](/ticdc/ticdc-bidirectional-replication.md) | Y | Y | Y | Y | Y | N | N |
| [TiCDC OpenAPI v2](/ticdc/ticdc-open-api-v2.md) | Y | Y | Y | Y | N | N | N |
| [DM](/dm/dm-overview.md) supports migrating MySQL 8.0 | Y | Y | E | E | E | E | N |

</StickyHeaderTable>

## Management, observability, and tools

<StickyHeaderTable>

| Management, observability, and tools | 8.5 | 8.1 | 7.5 | 7.1 | 6.5 | 6.1 | 5.4 |
|---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| [TiDB Dashboard UI](/dashboard/dashboard-intro.md) | Y | Y | Y | Y | Y | Y | Y |
| [TiDB Dashboard Continuous Profiling](/dashboard/continuous-profiling.md) | Y | Y | Y | Y | Y | Y | E |
| [TiDB Dashboard Top SQL](/dashboard/top-sql.md) | Y | Y | Y | Y | Y | Y | E |
| [TiDB Dashboard SQL Diagnostics](/information-schema/information-schema-sql-diagnostics.md) | Y | Y | Y | Y | Y | E | E |
| [TiDB Dashboard Cluster Diagnostics](/dashboard/dashboard-diagnostics-access.md) | Y | Y | Y | Y | Y | E | E |
| [TiKV-FastTune dashboard](/grafana-tikv-dashboard.md#tikv-fasttune-dashboard) | E | E | E | E | E | E | E |
| [Information schema](/information-schema/information-schema.md) | Y | Y | Y | Y | Y | Y | Y |
| [Metrics schema](/metrics-schema.md) | Y | Y | Y | Y | Y | Y | Y |
| [Statements summary tables](/statement-summary-tables.md) | Y | Y | Y | Y | Y | Y | Y |
| [Statements summary tables - summary persistence](/statement-summary-tables.md#persist-statements-summary) | E | E | E | E | N | N | N |
| [Slow query log](/identify-slow-queries.md) | Y | Y | Y | Y | Y | Y | Y |
| [TiUP deployment](/tiup/tiup-overview.md) | Y | Y | Y | Y | Y | Y | Y |
| [Kubernetes operator](https://docs.pingcap.com/tidb-in-kubernetes/) | Y | Y | Y | Y | Y | Y | Y |
| [Built-in physical backup](/br/backup-and-restore-use-cases.md) | Y | Y | Y | Y | Y | Y | Y |
| [Global Kill](/sql-statements/sql-statement-kill.md) | Y | Y | Y | Y | Y | Y | E |
| [Lock View](/information-schema/information-schema-data-lock-waits.md) | Y | Y | Y | Y | Y | Y | Y |
| [`SHOW CONFIG`](/sql-statements/sql-statement-show-config.md) | Y | Y | Y | Y | Y | Y | Y |
| [`SET CONFIG`](/dynamic-config.md) | Y | Y | Y | Y | Y | Y | E |
| [DM WebUI](/dm/dm-webui-guide.md) | E | E | E | E | E | E | N |
| [Foreground Quota Limiter](/tikv-configuration-file.md#foreground-quota-limiter) | Y | Y | Y | Y | Y | E | N |
| [Background Quota Limiter](/tikv-configuration-file.md#background-quota-limiter) | E | E | E | E | E | N | N |
| [EBS volume snapshot backup and restore](https://docs.pingcap.com/tidb-in-kubernetes/v1.4/backup-to-aws-s3-by-snapshot) | Y | Y | Y | Y | Y | N | N |
| [PITR](/br/backup-and-restore-overview.md) | Y | Y | Y | Y | Y | N | N |
| [Global memory control](/configure-memory-usage.md#configure-the-memory-usage-threshold-of-a-tidb-server-instance) | Y | Y | Y | Y | Y | N | N |
| [Cross-cluster RawKV replication](/tikv-configuration-file.md#api-version-new-in-v610) | E | E | E | E | E | N | N |
| [Green GC](/system-variables.md#tidb_gc_scan_lock_mode-new-in-v50) | E | E | E | E | E | E | E |
| [Resource control](/tidb-resource-control-ru-groups.md) | Y | Y | Y | Y | N | N | N |
| [Runaway Queries management](/tidb-resource-control-runaway-queries.md) | Y | Y | E | N | N | N | N |
| [Background tasks management](/tidb-resource-control-background-tasks.md) | Y | E | E | N | N | N | N |
| [TiFlash Disaggregated Storage and Compute Architecture and S3 Support](/tiflash/tiflash-disaggregated-and-s3.md) | Y | Y | Y | E | N | N | N |
| [Selecting TiDB nodes for the Distributed eXecution Framework (DXF) tasks](/system-variables.md#tidb_service_scope-new-in-v740) | Y | Y | Y | N | N | N | N |
| PD Follower Proxy (controlled by [`tidb_enable_tso_follower_proxy`](/system-variables.md#tidb_enable_tso_follower_proxy-new-in-v530)) | Y | Y | Y | Y | Y | Y | Y |
| [Active PD Follower](/tune-region-performance.md#use-the-active-pd-follower-feature-to-enhance-the-scalability-of-pds-region-information-query-service) (controlled by [`pd_enable_follower_handle_region`](/system-variables.md#pd_enable_follower_handle_region-new-in-v760)) | Y | E | N | N | N | N | N |
| [PD microservices](/pd-microservices.md) | E | E | N | N | N | N | N |
| [TiDB Distributed eXecution Framework (DXF)](/tidb-distributed-execution-framework.md) | Y | Y | Y | E | N | N | N |
| [Global Sort](/tidb-global-sort.md) | Y | Y | E | N | N | N | N |
| [TiProxy](/tiproxy/tiproxy-overview.md) | Y | Y | N | N | N | N | N |
| [Schema cache](/schema-cache.md) | Y | N | N | N | N | N | N |

</StickyHeaderTable>

[^1]: TiDB incorrectly treats latin1 as a subset of utf8. See [TiDB #18955](https://github.com/pingcap/tidb/issues/18955) for more details.

[^2]: Starting from v6.5.0, the expression indexes created on the functions listed by the [`tidb_allow_function_for_expression_index`](/system-variables.md#tidb_allow_function_for_expression_index-new-in-v520) system variable have been tested and can be used in production environments, and more functions will be supported in the future releases. For functions not listed by this variable, the corresponding expression indexes are not recommended for use in production environments. See [expression indexes](/sql-statements/sql-statement-create-index.md#expression-index) for details.

[^3]: See [Statement Reference](/sql-statements/sql-statement-select.md) for a full list of SQL statements supported.

[^4]: Starting from [v6.4.0](/releases/release-6.4.0.md), TiDB supports [high-performance and globally monotonic `AUTO_INCREMENT` columns](/auto-increment.md#mysql-compatibility-mode)

[^5]: Starting from [TiDB v7.0.0](/releases/release-7.0.0.md), the new parameter `FIELDS DEFINED NULL BY` and support for importing data from S3 and GCS are experimental features. Starting from [v7.6.0](/releases/release-7.6.0.md), TiDB processes `LOAD DATA` in transactions in the same way as MySQL. The `LOAD DATA` statement in a transaction no longer automatically commits the current transaction or starts a new transaction. Moreover, you can explicitly commit or roll back the `LOAD DATA` statement in a transaction. Additionally, the `LOAD DATA` statement is affected by the TiDB transaction mode setting (optimistic or pessimistic transaction).

[^6]: Starting from v7.5.0, [TiDB Binlog](https://docs-archive.pingcap.com/tidb/v8.3/tidb-binlog-overview/) replication is deprecated. Starting from v8.3.0, TiDB Binlog is fully deprecated. Starting from v8.4.0, TiDB Binlog is removed. For incremental data replication, use [TiCDC](/ticdc/ticdc-overview.md) instead. For point-in-time recovery (PITR), use [PITR](/br/br-pitr-guide.md). Before you upgrade your TiDB cluster to v8.4.0 or later versions, be sure to switch to TiCDC and PITR.

---

## File: basic-sql-operations.md

---
title: Explore SQL with TiDB
summary: Learn about the basic SQL statements for the TiDB database.
aliases: ['/docs/dev/basic-sql-operations/','/docs/dev/how-to/get-started/explore-sql/']
---

# Explore SQL with TiDB

TiDB is compatible with MySQL, you can use MySQL statements directly in most of the cases. For unsupported features, see [Compatibility with MySQL](/mysql-compatibility.md#unsupported-features).

<CustomContent platform="tidb">

To experiment with SQL and test out TiDB compatibility with MySQL queries, you can try [TiDB Playground](https://play.tidbcloud.com/?utm_source=docs&utm_medium=basic-sql-operations). You can also first deploy a TiDB cluster and then run SQL statements in it.

</CustomContent>

This page walks you through the basic TiDB SQL statements such as DDL, DML and CRUD operations. For a complete list of TiDB statements, see [SQL Statement Overview](/sql-statements/sql-statement-overview.md).

## Category

SQL is divided into the following 4 types according to their functions:

- DDL (Data Definition Language): It is used to define database objects, including databases, tables, views, and indexes.

- DML (Data Manipulation Language): It is used to manipulate application related records.

- DQL (Data Query Language): It is used to query the records after conditional filtering.

- DCL (Data Control Language): It is used to define access privileges and security levels.

Common DDL features are creating, modifying, and deleting objects (such as tables and indexes). The corresponding commands are `CREATE`, `ALTER`, and `DROP`.

## Show, create and drop a database

A database in TiDB can be considered as a collection of objects such as tables and indexes.

To show the list of databases, use the `SHOW DATABASES` statement:

{{< copyable "sql" >}}

```sql
SHOW DATABASES;
```

To use the database named `mysql`, use the following statement:

{{< copyable "sql" >}}

```sql
USE mysql;
```

To show all the tables in a database, use the `SHOW TABLES` statement:

{{< copyable "sql" >}}

```sql
SHOW TABLES FROM mysql;
```

To create a database, use the `CREATE DATABASE` statement:

{{< copyable "sql" >}}

```sql
CREATE DATABASE db_name [options];
```

To create a database named `samp_db`, use the following statement:

{{< copyable "sql" >}}

```sql
CREATE DATABASE IF NOT EXISTS samp_db;
```

Add `IF NOT EXISTS` to prevent an error if the database exists.

To delete a database, use the `DROP DATABASE` statement:

{{< copyable "sql" >}}

```sql
DROP DATABASE samp_db;
```

## Create, show, and drop a table

To create a table, use the `CREATE TABLE` statement:

{{< copyable "sql" >}}

```sql
CREATE TABLE table_name column_name data_type constraint;
```

For example, to create a table named `person` which includes fields such as number, name, and birthday, use the following statement:

{{< copyable "sql" >}}

```sql
CREATE TABLE person (
    id INT,
    name VARCHAR(255),
    birthday DATE
    );
```

To view the statement that creates the table (DDL), use the `SHOW CREATE TABLE` statement:

{{< copyable "sql" >}}

```sql
SHOW CREATE TABLE person;
```

To delete a table, use the `DROP TABLE` statement:

{{< copyable "sql" >}}

```sql
DROP TABLE person;
```

## Create, show, and drop an index

Indexes are used to speed up queries on indexed columns. To create an index for the column whose value is not unique, use the `CREATE INDEX` statement:

{{< copyable "sql" >}}

```sql
CREATE INDEX person_id ON person (id);
```

Or use the `ALTER TABLE` statement:

{{< copyable "sql" >}}

```sql
ALTER TABLE person ADD INDEX person_id (id);
```

To create a unique index for the column whose value is unique, use the `CREATE UNIQUE INDEX` statement:

{{< copyable "sql" >}}

```sql
CREATE UNIQUE INDEX person_unique_id ON person (id);
```

Or use the `ALTER TABLE` statement:

{{< copyable "sql" >}}

```sql
ALTER TABLE person ADD UNIQUE person_unique_id (id);
```

To show all the indexes in a table, use the `SHOW INDEX` statement:

{{< copyable "sql" >}}

```sql
SHOW INDEX FROM person;
```

To delete an index, use the `DROP INDEX` or `ALTER TABLE` statement. `DROP INDEX` can be nested in `ALTER TABLE`:

{{< copyable "sql" >}}

```sql
DROP INDEX person_id ON person;
```

{{< copyable "sql" >}}

```sql
ALTER TABLE person DROP INDEX person_unique_id;
```

> **Note:**
> 
> DDL operations are not transactions. You don't need to run a `COMMIT` statement when executing DDL operations.

## Insert, update, and delete data

Common DML features are adding, modifying, and deleting table records. The corresponding commands are `INSERT`, `UPDATE`, and `DELETE`.

To insert data into a table, use the `INSERT` statement:

{{< copyable "sql" >}}

```sql
INSERT INTO person VALUES(1,'tom','20170912');
```

To insert a record containing data of some fields into a table, use the `INSERT` statement:

{{< copyable "sql" >}}

```sql
INSERT INTO person(id,name) VALUES('2','bob');
```

To update some fields of a record in a table, use the `UPDATE` statement:

{{< copyable "sql" >}}

```sql
UPDATE person SET birthday='20180808' WHERE id=2;
```

To delete the data in a table, use the `DELETE` statement:

{{< copyable "sql" >}}

```sql
DELETE FROM person WHERE id=2;
```

> **Note:**
> 
> The `UPDATE` and `DELETE` statements without the `WHERE` clause as a filter operate on the entire table.

## Query data

DQL is used to retrieve the desired data rows from a table or multiple tables.

To view the data in a table, use the `SELECT` statement:

{{< copyable "sql" >}}

```sql
SELECT * FROM person;
```

To query a specific column, add the column name after the `SELECT` keyword:

{{< copyable "sql" >}}

```sql
SELECT name FROM person;
```

```sql
+------+
| name |
+------+
| tom  |
+------+
1 rows in set (0.00 sec)
```

Use the `WHERE` clause to filter all records that match the conditions and then return the result:

{{< copyable "sql" >}}

```sql
SELECT * FROM person where id<5;
```

## Create, authorize, and delete a user

DCL are usually used to create or delete users, and manage user privileges.

To create a user, use the `CREATE USER` statement. The following example creates a user named `tiuser` with the password `123456`:

{{< copyable "sql" >}}

```sql
CREATE USER 'tiuser'@'localhost' IDENTIFIED BY '123456';
```

To grant `tiuser` the privilege to retrieve the tables in the `samp_db` database:

{{< copyable "sql" >}}

```sql
GRANT SELECT ON samp_db.* TO 'tiuser'@'localhost';
```

To check the privileges of `tiuser`:

{{< copyable "sql" >}}

```sql
SHOW GRANTS for tiuser@localhost;
```

To delete `tiuser`:

{{< copyable "sql" >}}

```sql
DROP USER 'tiuser'@'localhost';
```

---

## File: batch-processing.md

---
title: Batch Processing
summary: Introduce batch processing features in TiDB, including Pipelined DML, non-transactional DML, the `IMPORT INTO` statement, and the deprecated batch-dml feature.
---

# Batch Processing

Batch processing is a common and essential operation in real-world scenarios. It enables efficient handling of large datasets for tasks such as data migration, bulk imports, archiving, and large-scale updates.

To optimize performance for batch operations, TiDB introduces various features over its version evolution:

- Data import
    - `IMPORT INTO` statement (introduced in TiDB v7.2.0 and GA in v7.5.0)
- Data inserts, updates, and deletions
    - Pipelined DML (experimental, introduced in TiDB v8.0.0)
    - Non-transactional DML (introduced in TiDB v6.1.0)
    - Batch-dml (deprecated)

This document outlines the key benefits, limitations, and use cases of these features to help you choose the most suitable solution for efficient batch processing.

## Data import

The `IMPORT INTO` statement is designed for data import tasks. It enables you to quickly import data in formats such as CSV, SQL, or PARQUET into an empty TiDB table, without the need to deploy [TiDB Lightning](https://docs.pingcap.com/tidb/stable/tidb-lightning-overview) separately.

### Key benefits

- Extremely fast import speed
- Easier to use compared to TiDB Lightning

### Limitations

<CustomContent platform="tidb">

- No transactional [ACID](/glossary.md#acid) guarantees
- Subject to various usage restrictions

</CustomContent>

<CustomContent platform="tidb-cloud">

- No transactional [ACID](/tidb-cloud/tidb-cloud-glossary.md#acid) guarantees
- Subject to various usage restrictions

</CustomContent>

### Use cases

- Suitable for data import scenarios such as data migration or recovery. It is recommended to use `IMPORT INTO` instead of TiDB Lightning where applicable.

For more information, see [`IMPORT INTO`](/sql-statements/sql-statement-import-into.md).

## Data inserts, updates, and deletions

### Pipelined DML

Pipelined DML is an experimental feature introduced in TiDB v8.0.0. In v8.5.0, the feature is enhanced with significant performance improvements.

#### Key benefits

- Streams data to the storage layer during transaction execution instead of buffering it entirely in memory, allowing transaction size no longer limited by TiDB memory and supporting ultra-large-scale data processing
- Achieves better performance compared to standard DML
- Can be enabled through system variables without SQL modifications

#### Limitations

- Only supports [autocommit](/transaction-overview.md#autocommit) `INSERT`, `REPLACE`, `UPDATE`, and `DELETE` statements.

#### Use cases

- Suitable for general batch processing tasks, such as bulk data inserts, updates, and deletions.

For more information, see [Pipelined DML](/pipelined-dml.md).

### Non-transactional DML statements

Non-transactional DML is introduced in TiDB v6.1.0. Initially, only the `DELETE` statement supports this feature. Starting from v6.5.0, `INSERT`, `REPLACE`, and `UPDATE` statements also support this feature.

#### Key benefits

- Splits a single SQL statement into multiple smaller statements, bypassing memory limitations.
- Achieves performance that is slightly faster or comparable to standard DML.

#### Limitations

- Only supports [autocommit](/transaction-overview.md#autocommit) statements
- Requires modifications to SQL statements
- Imposes strict requirements on SQL syntax; some statements might need rewriting
- Lacks full transactional ACID guarantees; in case of failures, partial execution of a statement might occur

#### Use cases

- Suitable for scenarios involving bulk data inserts, updates, and deletions. Due to its limitations, it is recommended to consider non-transactional DML only when Pipelined DML is not applicable.

For more information, see [Non-transactional DML](/non-transactional-dml.md).

### Deprecated batch-dml feature

The batch-dml feature, available in TiDB versions prior to v4.0, is now deprecated and no longer recommended. This feature is controlled by the following system variables:

- `tidb_batch_insert`
- `tidb_batch_delete`
- `tidb_batch_commit`
- `tidb_enable_batch_dml`
- `tidb_dml_batch_size`

Due to the risk of data corruption or loss caused by inconsistent data and indexes, these variables have been deprecated and are planned for removal in future releases.

It is **NOT RECOMMENDED** to use the deprecated batch-dml feature under any circumstances. Instead, consider other alternative features outlined in this document.

---

## File: best-practices-for-security-configuration.md

---
title: Best Practices for TiDB Security Configuration
summary: Learn the best practices for TiDB security configuration to help mitigate potential security risks.
---

# Best Practices for TiDB Security Configuration

The security of TiDB is crucial for protecting data integrity and confidentiality. This document provides guidelines for configuring TiDB clusters securely during deployment. By following these best practices, you can effectively reduce potential security risks, prevent data breaches, and ensure the continuous, stable, and reliable operation of your TiDB database system.

> **Note:**
>
> This document offers general recommendations on TiDB security configurations. PingCAP does not guarantee the completeness or accuracy of the information, and it assumes no responsibility for any issues arising from the use of this guide. Users should assess these recommendations based on their specific needs and consult professionals for tailored advice.

## Set the initial password for the root user

By default, the root user in a newly created TiDB cluster has no password, which poses a potential security risk. If a password is not set, anyone can attempt to log in to the TiDB database as the root user, potentially gaining access to and modifying data.

To avoid this risk, it is recommended to set a root password during deployment:

- For deployments using TiUP, refer to [Deploy TiDB Cluster Using TiUP](/production-deployment-using-tiup.md#step-7-start-a-tidb-cluster) to generate a random password for the root user.
- For deployments using TiDB Operator, refer to [Set initial account and password](https://docs.pingcap.com/tidb-in-kubernetes/stable/initialize-a-cluster#set-initial-account-and-password) to set the root password.

You can also use the [`--initialize-secure`](/command-line-flags-for-tidb-configuration.md#--initialize-secure) option to restrict network access for the initial root user.

## Enable password complexity checks

By default, TiDB does not enforce password complexity policies, which might lead to the use of weak or empty passwords, increasing security risks.

To ensure that database users create strong passwords, it is recommended to configure a reasonable [password complexity policy](/password-management.md#password-complexity-policy). For example, configure a policy that requires passwords to include a combination of uppercase letters, lowercase letters, numbers, and special characters. By enforcing password complexity checks, you can improve database security, prevent brute force attacks, reduce internal threats, ensure compliance with regulations, and lower the risk of data breaches, thus enhancing overall security.

## Change the default Grafana password

TiDB installation includes the Grafana component by default, and the default username and password are typically `admin`/`admin`. If the password is not changed promptly, attackers could exploit this to gain control of the system.

It is recommended to immediately change the Grafana password to a strong one during the TiDB deployment, and regularly update the password to ensure system security. Here are the steps to change the Grafana password:

- Upon first login to Grafana, follow the prompts to change the password.

    

- Access the Grafana personal configuration center to change the password.

    

## Enhance TiDB Dashboard security

### Use a least privilege user

TiDB Dashboard shares the account system with TiDB SQL users, and TiDB Dashboard authorization is based on TiDB SQL user permissions. TiDB Dashboard requires minimal permissions and can even operate with read-only access.

To enhance security, it is recommended to create a [least-privilege SQL user](/dashboard/dashboard-user.md) for accessing the TiDB Dashboard and to avoid using high-privilege users.

### Restrict access control

By default, TiDB Dashboard is designed for trusted users. The default port includes additional API interfaces besides TiDB Dashboard. If you want to allow access to TiDB Dashboard from external networks or untrusted users, take the following measures to avoid security vulnerabilities:

- Use a firewall or other mechanisms to restrict the default `2379` port to trusted domains, preventing access by external users.

    > **Note:**
    >
    > TiDB, TiKV, and other components need to communicate with the PD component via the PD client port. Do not block internal network access between components, which will make the cluster unavailable.

- [Configure a reverse proxy](/dashboard/dashboard-ops-reverse-proxy.md#use-tidb-dashboard-behind-a-reverse-proxy) to securely provide TiDB Dashboard services to external users on a different port.

## Protect internal ports

By default, TiDB installation includes several privileged interfaces for inter-component communication. These ports typically do not need to be accessible to users, because they are primarily for internal communication. Exposing these ports on public networks increases the attack surface, violates the principle of least privilege, and raises the risk of security vulnerabilities. The following table lists the default listening ports in a TiDB cluster:

| Component         | Default port| Protocol   |
|-------------------|-------------|------------|
| TiDB              | 4000        | MySQL      |
| TiDB              | 10080       | HTTP       |
| TiKV              | 20160       | Protocol   |
| TiKV              | 20180       | HTTP       |
| PD                | 2379        | HTTP/Protocol|
| PD                | 2380        | Protocol   |
| TiFlash           | 3930        | Protocol   |
| TiFlash           | 20170       | Protocol   |
| TiFlash           | 20292       | HTTP       |
| TiFlash           | 8234        | HTTP       |
| TiProxy           | 6000        | MySQL      |
| TiProxy           | 3080        | HTTP       |
| DM master         | 8261        | HTTP       |
| DM master         | 8291        | HTTP       |
| DM worker         | 8262        | HTTP       |
| TiCDC             | 8300        | HTTP       |
| TiDB Lightning    | 8289        | HTTP       |
| TiDB Operator     | 6060        | HTTP       |
| TiDB Dashboard    | 2379        | HTTP       |
| TMS               | 8082        | HTTP       |
| TEM               | 8080        | HTTP       |
| TEM               | 8000        | HTTP       |
| TEM               | 4110        | HTTP       |
| TEM               | 4111        | HTTP       |
| TEM               | 4112        | HTTP       |
| TEM               | 4113        | HTTP       |
| TEM               | 4124        | HTTP       |
| Prometheus        | 9090        | HTTP       |
| Grafana           | 3000        | HTTP       |
| AlertManager      | 9093        | HTTP       |
| AlertManager      | 9094        | Protocol   |
| Node Exporter     | 9100        | HTTP       |
| Blackbox Exporter | 9115        | HTTP       |
| NG Monitoring     | 12020       | HTTP       |

It is recommended to only expose the `4000` port for the database and the `3000` port for the Grafana dashboard to ordinary users, while restricting access to other ports using network security policies or firewalls. The following is an example of using `iptables` to restrict port access:

```shell
# Allow internal port communication from the whitelist of component IP addresses
sudo iptables -A INPUT -s internal IP address range -j ACCEPT

# Only open ports 4000 and 3000 to external users
sudo iptables -A INPUT -p tcp --dport 4000 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 3000 -j ACCEPT

# Deny all other traffic by default
sudo iptables -P INPUT DROP
```

If you need to access TiDB Dashboard, it is recommended to [configure a reverse proxy](/dashboard/dashboard-ops-reverse-proxy.md#use-tidb-dashboard-behind-a-reverse-proxy) to securely provide services to external networks on a separate port.

## Resolving false positives from third-party MySQL vulnerability scanners

Most vulnerability scanners detect MySQL vulnerabilities based on version information. Because TiDB is MySQL protocol-compatible but not MySQL itself, version-based vulnerability scans might lead to false positives. It is recommended to focus vulnerability scans on principle-based assessments. If compliance scanning tools require a specific MySQL version, you can [modify the server version number](/faq/high-reliability-faq.md#does-tidb-support-modifying-the-mysql-version-string-of-the-server-to-a-specific-one-that-is-required-by-the-security-vulnerability-scanning-tool) to meet the requirement.

By changing the server version number, you can avoid false positives from vulnerability scanners. The [`server-version`](/tidb-configuration-file.md#server-version) value is used by TiDB nodes to verify the current TiDB version. Before upgrading the TiDB cluster, ensure that the `server-version` value is either empty or the actual version of TiDB to avoid unexpected behavior.

---

## File: binary-package.md

---
title: TiDB Installation Packages
summary: Learn about TiDB installation packages and the specific components included.
---

# TiDB Installation Packages

Before [deploying TiUP offline](/production-deployment-using-tiup.md#deploy-tiup-offline), you need to download the binary packages of TiDB as described in [Prepare the TiUP offline component package](/production-deployment-using-tiup.md#prepare-the-tiup-offline-component-package).

TiDB binary packages are available in amd64 and arm64 architectures. In either architecture, TiDB provides two binary packages: `TiDB-community-server` and `TiDB-community-toolkit`.

The `TiDB-community-server` package contains the following contents.

| Content | Change history |
|---|---|
| tidb-{version}-linux-{arch}.tar.gz |  |
| tikv-{version}-linux-{arch}.tar.gz |  |
| tiflash-{version}-linux-{arch}.tar.gz |  |
| pd-{version}-linux-{arch}.tar.gz |  |
| ctl-{version}-linux-{arch}.tar.gz |  |
| grafana-{version}-linux-{arch}.tar.gz |  |
| alertmanager-{version}-linux-{arch}.tar.gz |  |
| blackbox_exporter-{version}-linux-{arch}.tar.gz |  |
| prometheus-{version}-linux-{arch}.tar.gz |  |
| node_exporter-{version}-linux-{arch}.tar.gz |  |
| tiup-linux-{arch}.tar.gz |  |
| tiup-{version}-linux-{arch}.tar.gz |  |
| local_install.sh |  |
| cluster-{version}-linux-{arch}.tar.gz |  |
| insight-{version}-linux-{arch}.tar.gz |  |
| diag-{version}-linux-{arch}.tar.gz | New in v6.0.0 |
| influxdb-{version}-linux-{arch}.tar.gz |  |
| playground-{version}-linux-{arch}.tar.gz |  |
| tiproxy-{version}-linux-{arch}.tar.gz | New in v7.6.0 |

> **Note:**
>
> `{version}` depends on the version of the component or server you are installing. `{arch}` depends on the architecture of the system, which can be `amd64` or `arm64`.

The `TiDB-community-toolkit` package contains the following contents.

| Content | Change history |
|---|---|
| pd-recover-{version}-linux-{arch}.tar.gz |  |
| etcdctl | New in v6.0.0 |
| tiup-linux-{arch}.tar.gz |  |
| tiup-{version}-linux-{arch}.tar.gz |  |
| tidb-lightning-{version}-linux-{arch}.tar.gz |  |
| tidb-lightning-ctl |  |
| dumpling-{version}-linux-{arch}.tar.gz |  |
| cdc-{version}-linux-{arch}.tar.gz |  |
| dm-{version}-linux-{arch}.tar.gz |  |
| dm-worker-{version}-linux-{arch}.tar.gz |  |
| dm-master-{version}-linux-{arch}.tar.gz |  |
| dmctl-{version}-linux-{arch}.tar.gz |  |
| br-{version}-linux-{arch}.tar.gz |  |
| package-{version}-linux-{arch}.tar.gz |  |
| bench-{version}-linux-{arch}.tar.gz |  |
| errdoc-{version}-linux-{arch}.tar.gz |  |
| dba-{version}-linux-{arch}.tar.gz |  |
| PCC-{version}-linux-{arch}.tar.gz |  |
| sync_diff_inspector |  |
| reparo |  |
| server-{version}-linux-{arch}.tar.gz | New in v6.2.0 |
| grafana-{version}-linux-{arch}.tar.gz | New in v6.2.0 |
| alertmanager-{version}-linux-{arch}.tar.gz | New in v6.2.0 |
| prometheus-{version}-linux-{arch}.tar.gz | New in v6.2.0 |
| blackbox_exporter-{version}-linux-{arch}.tar.gz | New in v6.2.0  |
| node_exporter-{version}-linux-{arch}.tar.gz | New in v6.2.0  |

> **Note:**
>
> `{version}` depends on the version of the tool you are installing. `{arch}` depends on the architecture of the system, which can be `amd64` or `arm64`.

## See also

[Deploy TiUP offline](/production-deployment-using-tiup.md#deploy-tiup-offline)

---

## File: blocklist-control-plan.md

---
title: The Blocklist of Optimization Rules and Expression Pushdown
summary: Learn about the blocklist to control the optimization rules and the behavior of expression pushdown.
---

# The Blocklist of Optimization Rules and Expression Pushdown

This document introduces how to use the blocklist of optimization rules and the blocklist of expression pushdown to control the behavior of TiDB.

## The blocklist of optimization rules

The blocklist of optimization rules is one way to tune optimization rules, mainly used to manually disable some optimization rules.

### Important optimization rules

|**Optimization Rule**|**Rule Name**|**Description**|
| :--- | :--- | :--- |
| Column pruning | column_prune | One operator will prune the column if it is not needed by the upper executor. |
| Decorrelate subquery | decorrelate | Tries to rewrite the correlated subquery to non-correlated join or aggregation. |
| Aggregation elimination | aggregation_eliminate | Tries to remove unnecessary aggregation operators from the execution plan. |
| Projection elimination | projection_eliminate | Removes unnecessary projection operators from the execution plan. |
| Max/Min elimination | max_min_eliminate | Rewrites some max/min functions in aggregation to the `order by` + `limit 1` form. |
| Predicate pushdown | predicate_push_down | Tries to push predicates down to the operator that is closer to the data source. |
| Outer join elimination | outer_join_eliminate | Tries to remove the unnecessary left join or right join from the execution plan. |
| Partition pruning | partition_processor | Prunes partitions which are rejected by the predicates and rewrite partitioned table query to the `UnionAll + Partition Datasource` form. |
| Aggregation pushdown | aggregation_push_down | Tries to push aggregations down to their children. |
| TopN pushdown | topn_push_down | Tries to push the TopN operator to the place closer to the data source. |
| Join reorder | join_reorder | Decides the order of multi-table joins. |
| Derive TopN or Limit from window functions | derive_topn_from_window | Derives the TopN or Limit operator from window functions. |

### Disable optimization rules

You can use the blocklist of optimization rules to disable some of them if some rules lead to a sub-optimal execution plan for special queries.

#### Usage

> **Note:**
>
> All the following operations need the `super privilege` privilege of the database. Each optimization rule has a name. For example, the name of column pruning is `column_prune`. The names of all optimization rules can be found in the second column of the table [Important Optimization Rules](#important-optimization-rules).

- If you want to disable some rules, write its name to the `mysql.opt_rule_blacklist` table. For example:

    {{< copyable "sql" >}}

    ```sql
    INSERT INTO mysql.opt_rule_blacklist VALUES("join_reorder"), ("topn_push_down");
    ```

    Executing the following SQL statement can make the above operation take effect immediately. The effective range includes all old connections of the corresponding TiDB server:

    {{< copyable "sql" >}}

    ```sql
    admin reload opt_rule_blacklist;
    ```

    > **Note:**
    >
    > `admin reload opt_rule_blacklist` only takes effect on the TiDB server where the above statement has been run. If you want all TiDB servers of the cluster to take effect, run this command on each TiDB server.

- If you want to re-enable a rule, delete the corresponding data in the table, and then run the `admin reload` statement:

    {{< copyable "sql" >}}

    ```sql
    DELETE FROM mysql.opt_rule_blacklist WHERE name IN ("join_reorder", "topn_push_down");
    ```

    {{< copyable "sql" >}}

    ```sql
    admin reload opt_rule_blacklist;
    ```

## The blocklist of expression pushdown

The blocklist of expression pushdown is one way to tune the expression pushdown, mainly used to manually disable some expressions of some specific data types.

### Expressions that are supported to be pushed down

For more information about the expressions that are supported to be pushed down, see [Supported expressions for pushdown to TiKV](/functions-and-operators/expressions-pushed-down.md#supported-expressions-for-pushdown-to-tikv).

### Disable the pushdown of specific expressions

When you get wrong results due to the expression pushdown, you can use the blocklist to make a quick recovery for the application. More specifically, you can add some of the supported functions or operators to the `mysql.expr_pushdown_blacklist` table to disable the pushdown of specific expressions.

The schema of `mysql.expr_pushdown_blacklist` is shown as follows:

{{< copyable "sql" >}}

```sql
DESC mysql.expr_pushdown_blacklist;
```

```sql
+------------+--------------+------+------+-------------------+-------+
| Field      | Type         | Null | Key  | Default           | Extra |
+------------+--------------+------+------+-------------------+-------+
| name       | char(100)    | NO   |      | NULL              |       |
| store_type | char(100)    | NO   |      | tikv,tiflash,tidb |       |
| reason     | varchar(200) | YES  |      | NULL              |       |
+------------+--------------+------+------+-------------------+-------+
3 rows in set (0.00 sec)
```

Here is the description of each field above:

+ `name`: The name of the function that is disabled to be pushed down.
+ `store_type`: To specify the component that you want to prevent the function from being pushed down to for computing. Available components are `tidb`, `tikv`, and `tiflash`. The `store_type` is case-insensitive. If you need to specify multiple components, use a comma to separate each component.
    - When `store_type` is `tidb`, it indicates whether the function can be executed in other TiDB servers while the TiDB memory table is being read.
    - When `store_type` is `tikv`, it indicates whether the function can be executed in TiKV server's Coprocessor component.
    - When `store_type` is `tiflash`, it indicates whether the function can be executed in TiFlash Server's Coprocessor component.
+ `reason`: To record the reason why this function is added to the blocklist.

### Usage

This section describes how to use the blocklist of expression pushdown.

#### Add to the blocklist

To add one or more expressions (functions or operators) to the blocklist, perform the following steps:

1. Insert the corresponding function name or operator name, and the set of components you want to disable the pushdown, to the `mysql.expr_pushdown_blacklist` table.

2. Execute `admin reload expr_pushdown_blacklist`.

### Remove from the blocklist

To remove one or more expressions from the blocklist, perform the following steps:

1. Delete the corresponding function name or operator name, and the set of components you want to disable the pushdown, from the `mysql.expr_pushdown_blacklist` table.

2. Execute `admin reload expr_pushdown_blacklist`.

> **Note:**
>
> `admin reload expr_pushdown_blacklist` only takes effect on the TiDB server where this statement is run. If you want all TiDB servers of the cluster to take effect, run this command on each TiDB server.

## Expression blocklist usage example

In the following example, the `<` and `>` operators are added to the blocklist, and then the `>` operator is removed from the blocklist.

To judge whether the blocklist takes effect, observe the results of `EXPLAIN` (See [TiDB Query Execution Plan Overview](/explain-overview.md)).

1. The predicates `a < 2` and `a > 2` in the `WHERE` clause of the following SQL statement can be pushed down to TiKV.

    {{< copyable "sql" >}}

    ```sql
    EXPLAIN SELECT * FROM t WHERE a < 2 AND a > 2;
    ```

    ```sql
    +-------------------------+----------+-----------+---------------+------------------------------------+
    | id                      | estRows  | task      | access object | operator info                      |
    +-------------------------+----------+-----------+---------------+------------------------------------+
    | TableReader_7           | 0.00     | root      |               | data:Selection_6                   |
    | └─Selection_6           | 0.00     | cop[tikv] |               | gt(ssb_1.t.a, 2), lt(ssb_1.t.a, 2) |
    |   └─TableFullScan_5     | 10000.00 | cop[tikv] | table:t       | keep order:false, stats:pseudo     |
    +-------------------------+----------+-----------+---------------+------------------------------------+
    3 rows in set (0.00 sec)
    ```

2. Insert the expression to the `mysql.expr_pushdown_blacklist` table and execute `admin reload expr_pushdown_blacklist`.

    {{< copyable "sql" >}}

    ```sql
    INSERT INTO mysql.expr_pushdown_blacklist VALUES('<','tikv',''), ('>','tikv','');
    ```

    ```sql
    Query OK, 2 rows affected (0.01 sec)
    Records: 2  Duplicates: 0  Warnings: 0
    ```

    {{< copyable "sql" >}}

    ```sql
    admin reload expr_pushdown_blacklist;
    ```

    ```sql
    Query OK, 0 rows affected (0.00 sec)
    ```

3. Observe the execution plan again and you will find that both the `<` and `>` operators are not pushed down to TiKV Coprocessor.

    {{< copyable "sql" >}}

    ```sql
    EXPLAIN SELECT * FROM t WHERE a < 2 and a > 2;
    ```

    ```sql
    +-------------------------+----------+-----------+---------------+------------------------------------+
    | id                      | estRows  | task      | access object | operator info                      |
    +-------------------------+----------+-----------+---------------+------------------------------------+
    | Selection_7             | 10000.00 | root      |               | gt(ssb_1.t.a, 2), lt(ssb_1.t.a, 2) |
    | └─TableReader_6         | 10000.00 | root      |               | data:TableFullScan_5               |
    |   └─TableFullScan_5     | 10000.00 | cop[tikv] | table:t       | keep order:false, stats:pseudo     |
    +-------------------------+----------+-----------+---------------+------------------------------------+
    3 rows in set (0.00 sec)
    ```

4. Remove one expression (here is `>`) from the blocklist and execute `admin reload expr_pushdown_blacklist`.

    {{< copyable "sql" >}}

    ```sql
    DELETE FROM mysql.expr_pushdown_blacklist WHERE name = '>';
    ```

    ```sql
    Query OK, 1 row affected (0.01 sec)
    ```

    {{< copyable "sql" >}}

    ```sql
    admin reload expr_pushdown_blacklist;
    ```

    ```sql
    Query OK, 0 rows affected (0.00 sec)
    ```

5. Observe the execution plan again and you will find that `<` is not pushed down while `>` is pushed down to TiKV Coprocessor.

    {{< copyable "sql" >}}

    ```sql
    EXPLAIN SELECT * FROM t WHERE a < 2 AND a > 2;
    ```

    ```sql
    +---------------------------+----------+-----------+---------------+--------------------------------+
    | id                        | estRows  | task      | access object | operator info                  |
    +---------------------------+----------+-----------+---------------+--------------------------------+
    | Selection_8               | 0.00     | root      |               | lt(ssb_1.t.a, 2)               |
    | └─TableReader_7           | 0.00     | root      |               | data:Selection_6               |
    |   └─Selection_6           | 0.00     | cop[tikv] |               | gt(ssb_1.t.a, 2)               |
    |     └─TableFullScan_5     | 10000.00 | cop[tikv] | table:t       | keep order:false, stats:pseudo |
    +---------------------------+----------+-----------+---------------+--------------------------------+
    4 rows in set (0.00 sec)
    ```

---

## File: cached-tables.md

---
title: Cached Tables
summary: Learn the cached table feature in TiDB, which is used for rarely-updated small hotspot tables to improve read performance.
---

# Cached Tables

In v6.0.0, TiDB introduces the cached table feature for frequently accessed but rarely updated small hotspot tables. When this feature is used, the data of an entire table is loaded into the memory of the TiDB server, and TiDB directly gets the table data from the memory without accessing TiKV, which improves the read performance.

This document describes the usage scenarios of cached tables, the examples, and the compatibility restrictions with other TiDB features.

## Usage scenarios

The cached table feature is suitable for tables with the following characteristics:

- The data volume of the table is small, for example, less than 4 MiB.
- The table is read-only or rarely updated, for example, with a write QPS (queries per second) of less than 10 times per minute.
- The table is frequently accessed, and you expect a better read performance, for example, when encountering hotspots on small tables during direct reads from TiKV.

When the data volume of the table is small but the data is frequently accessed, the data is concentrated on a Region in TiKV and makes it a hotspot Region, which affects the performance. Therefore, the typical usage scenarios of cached tables are as follows:

- Configuration tables, from which applications read the configuration information.
- The tables of exchange rates in the financial sector. These tables are updated only once a day but not in real-time.
- Bank branch or network information tables, which are rarely updated.

Take configuration tables as an example. When the application restarts, the configuration information is loaded in all connections, which causes a high read latency. In this case, you can solve this problem by using the cached tables feature.

## Examples

This section describes the usage of cached tables by examples.

### Set a normal table to a cached table

Suppose that there is a table `users`:

```sql
CREATE TABLE users (
    id BIGINT,
    name VARCHAR(100),
    PRIMARY KEY(id)
);
```

To set this table to a cached table, use the `ALTER TABLE` statement:

```sql
ALTER TABLE users CACHE;
```

```sql
Query OK, 0 rows affected (0.01 sec)
```

### Verify a cached table

To verify a cached table, use the `SHOW CREATE TABLE` statement. If the table is cached, the returned result contains the `CACHED ON` attribute:

```sql
SHOW CREATE TABLE users;
```

```sql
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                                                                                               |
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| users | CREATE TABLE `users` (
  `id` bigint NOT NULL,
  `name` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`) /*T![clustered_index] CLUSTERED */
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin /* CACHED ON */ |
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
```

After reading data from a cached table, TiDB loads the data in memory. You can use the [`TRACE`](/sql-statements/sql-statement-trace.md) statement to check whether the data is loaded into memory. When the cache is not loaded, the returned result contains the `regionRequest.SendReqCtx` attribute, which indicates that TiDB reads data from TiKV.

```sql
TRACE SELECT * FROM users;
```

```sql
+------------------------------------------------+-----------------+------------+
| operation                                      | startTS         | duration   |
+------------------------------------------------+-----------------+------------+
| trace                                          | 17:47:39.969980 | 827.73µs   |
|   ├─session.ExecuteStmt                        | 17:47:39.969986 | 413.31µs   |
|   │ ├─executor.Compile                         | 17:47:39.969993 | 198.29µs   |
|   │ └─session.runStmt                          | 17:47:39.970221 | 157.252µs  |
|   │   └─TableReaderExecutor.Open               | 17:47:39.970294 | 47.068µs   |
|   │     └─distsql.Select                       | 17:47:39.970312 | 24.729µs   |
|   │       └─regionRequest.SendReqCtx           | 17:47:39.970454 | 189.601µs  |
|   ├─*executor.UnionScanExec.Next               | 17:47:39.970407 | 353.073µs  |
|   │ ├─*executor.TableReaderExecutor.Next       | 17:47:39.970411 | 301.106µs  |
|   │ └─*executor.TableReaderExecutor.Next       | 17:47:39.970746 | 6.57µs     |
|   └─*executor.UnionScanExec.Next               | 17:47:39.970772 | 17.589µs   |
|     └─*executor.TableReaderExecutor.Next       | 17:47:39.970776 | 6.59µs     |
+------------------------------------------------+-----------------+------------+
12 rows in set (0.01 sec)
```

After executing [`TRACE`](/sql-statements/sql-statement-trace.md) again, the returned result no longer contains the `regionRequest.SendReqCtx` attribute, which indicates that TiDB no longer reads data from TiKV but reads data from the memory instead.

```sql
+----------------------------------------+-----------------+------------+
| operation                              | startTS         | duration   |
+----------------------------------------+-----------------+------------+
| trace                                  | 17:47:40.533888 | 453.547µs  |
|   ├─session.ExecuteStmt                | 17:47:40.533894 | 402.341µs  |
|   │ ├─executor.Compile                 | 17:47:40.533903 | 205.54µs   |
|   │ └─session.runStmt                  | 17:47:40.534141 | 132.084µs  |
|   │   └─TableReaderExecutor.Open       | 17:47:40.534202 | 14.749µs   |
|   ├─*executor.UnionScanExec.Next       | 17:47:40.534306 | 3.21µs     |
|   └─*executor.UnionScanExec.Next       | 17:47:40.534316 | 1.219µs    |
+----------------------------------------+-----------------+------------+
7 rows in set (0.00 sec)
```

Note that the `UnionScan` operator is used to read the cached tables, so you can see `UnionScan` in the execution plan of the cached tables through `explain`:

```sql
+-------------------------+---------+-----------+---------------+--------------------------------+
| id                      | estRows | task      | access object | operator info                  |
+-------------------------+---------+-----------+---------------+--------------------------------+
| UnionScan_5             | 1.00    | root      |               |                                |
| └─TableReader_7         | 1.00    | root      |               | data:TableFullScan_6           |
|   └─TableFullScan_6     | 1.00    | cop[tikv] | table:users   | keep order:false, stats:pseudo |
+-------------------------+---------+-----------+---------------+--------------------------------+
3 rows in set (0.00 sec)
```

### Write data to a cached table

Cached tables support data writes. For example, you can insert a record into the `users` table:

```sql
INSERT INTO users(id, name) VALUES(1001, 'Davis');
```

```sql
Query OK, 1 row affected (0.00 sec)
```

```sql
SELECT * FROM users;
```

```sql
+------+-------+
| id   | name  |
+------+-------+
| 1001 | Davis |
+------+-------+
1 row in set (0.00 sec)
```

> **Note:**
>
> When you insert data to a cached table, second-level write latency might occur. The latency is controlled by the global environment variable [`tidb_table_cache_lease`](/system-variables.md#tidb_table_cache_lease-new-in-v600). You can decide whether to use the cached table feature by checking whether the latency is acceptable based on your application. For example, in a read-only scenario, you can increase the value of `tidb_table_cache_lease`:
>
> ```sql
> set @@global.tidb_table_cache_lease = 10;
> ```
>
> The write latency of cached tables is high, because the cached table feature is implemented with a complex mechanism that requires a lease to be set for each cache. When there are multiple TiDB instances, one instance does not know whether the other instances have cached data. If an instance modifies the table data directly, the other instances read the old cache data. To ensure correctness, the cached table implementation uses a lease mechanism to ensure that the data is not modified before the lease expires. That is why the write latency is high.

The metadata of cached tables is stored in the `mysql.table_cache_meta` table. This table records the IDs of all cached tables, the current lock status (`lock_type`), and the lock lease information (`lease`). This table is only internally used in TiDB and you are not recommended to modify it. Otherwise, unexpected errors might occur.

```sql
SHOW CREATE TABLE mysql.table_cache_meta\G
*************************** 1. row ***************************
       Table: table_cache_meta
Create Table: CREATE TABLE `table_cache_meta` (
  `tid` bigint NOT NULL DEFAULT '0',
  `lock_type` enum('NONE','READ','INTEND','WRITE') NOT NULL DEFAULT 'NONE',
  `lease` bigint NOT NULL DEFAULT '0',
  `oldReadLease` bigint NOT NULL DEFAULT '0',
  PRIMARY KEY (`tid`) /*T![clustered_index] CLUSTERED */
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin
1 row in set (0.00 sec)
```

### Revert a cached table to a normal table

> **Note:**
>
> Executing DDL statements on a cached table will fail. Before executing DDL statements on a cached table, you need to remove the cache attribute first and set the cached table back to a normal table.

```sql
TRUNCATE TABLE users;
```

```sql
ERROR 8242 (HY000): 'Truncate Table' is unsupported on cache tables.
```

```sql
mysql> ALTER TABLE users ADD INDEX k_id(id);
```

```sql
ERROR 8242 (HY000): 'Alter Table' is unsupported on cache tables.
```

To revert a cached table to a normal table, use `ALTER TABLE t NOCACHE`:

```sql
ALTER TABLE users NOCACHE;
```

```sql
Query OK, 0 rows affected (0.00 sec)
```

## Size limit of cached tables

Cached tables are only suitable for scenarios with small tables, because TiDB loads the data of an entire table into memory, and the cached data becomes invalid after modification and needs to be reloaded.

Currently, the size limit of a cached table is 64 MiB in TiDB. If the table data exceeds 64 MiB, executing `ALTER TABLE t CACHE` will fail.

## Compatibility restrictions with other TiDB features

Cached tables **DO NOT** support the following features:

- Performing the `ALTER TABLE t ADD PARTITION` operation on partitioned tables is not supported.
- Performing the `ALTER TABLE t CACHE` operation on temporary tables is not supported.
- Performing the `ALTER TABLE t CACHE` operation on views is not supported.
- Stale Read is not supported.
- Direct DDL operations on a cached table are not supported. You need to set the cached table back to a normal table first by using `ALTER TABLE t NOCACHE` before performing DDL operations.

Cached tables **CANNOT** be used in the following scenarios:

- Setting the system variable `tidb_snapshot` to read historical data.
- During modification, the cached data becomes invalid until the data is reloaded.

## Compatibility with TiDB migration tools

The cached table is a TiDB extension to MySQL syntax. Only TiDB can recognize the `ALTER TABLE ... CACHE` statement. TiDB migration tools **DO NOT** support cached tables, including Backup & Restore (BR), TiCDC, and Dumpling. These tools treat cached tables as normal tables.

That is to say, when a cached table is backed up and restored, it becomes a normal table. If the downstream cluster is a different TiDB cluster and you want to continue using the cached table feature, you can manually enable cached tables on the downstream cluster by executing `ALTER TABLE ... CACHE` on the downstream table.

## See also

* [ALTER TABLE](/sql-statements/sql-statement-alter-table.md)
* [System Variables](/system-variables.md)

---

## File: certificate-authentication.md

---
title: Certificate-Based Authentication for Login
summary: Learn the certificate-based authentication used for login.
aliases: ['/docs/dev/certificate-authentication/','/docs/dev/reference/security/cert-based-authentication/']
---

# Certificate-Based Authentication for Login

TiDB supports a certificate-based authentication method for users to log into TiDB. With this method, TiDB issues certificates to different users, uses encrypted connections to transfer data, and verifies certificates when users log in. This approach is more secure than the traditional password-based authentication method commonly used by MySQL users and is thus adopted by an increasing number of users.

To use certificate-based authentication, you might need to perform the following operations:

+ Create security keys and certificates
+ Configure certificates for TiDB and the client
+ Configure the user certificate information to be verified when the user logs in
+ Update and replace certificates

The rest of the document introduces in detail how to perform these operations.

## Create security keys and certificates

<CustomContent platform="tidb">

It is recommended that you use [OpenSSL](https://www.openssl.org/) to create keys and certificates. The certificate generation process is similar to the process described in [Enable TLS Between TiDB Clients and Servers](/enable-tls-between-clients-and-servers.md). The following paragraphs demonstrate how to configure more attribute fields that need to be verified in the certificate.

</CustomContent>

<CustomContent platform="tidb-cloud">

It is recommended that you use [OpenSSL](https://www.openssl.org/) to create keys and certificates. The certificate generation process is similar to the process described in [Enable TLS Between TiDB Clients and Servers](https://docs.pingcap.com/tidb/stable/enable-tls-between-clients-and-servers). The following paragraphs demonstrate how to configure more attribute fields that need to be verified in the certificate.

</CustomContent>

### Generate CA key and certificate

1. Execute the following command to generate the CA key:

    ```bash
    sudo openssl genrsa 2048 > ca-key.pem
    ```

    The output of the above command:

    ```
    Generating RSA private key, 2048 bit long modulus (2 primes)
    ....................+++++
    ...............................................+++++
    e is 65537 (0x010001)
    ```

2. Execute the following command to generate the certificate corresponding to the CA key:

    ```bash
    sudo openssl req -new -x509 -nodes -days 365000 -key ca-key.pem -out ca-cert.pem
    ```

3. Enter detailed certificate information. For example:

    ```bash
    Country Name (2 letter code) [AU]:US
    State or Province Name (full name) [Some-State]:California
    Locality Name (e.g. city) []:San Francisco
    Organization Name (e.g. company) [Internet Widgits Pty Ltd]:PingCAP Inc.
    Organizational Unit Name (e.g. section) []:TiDB
    Common Name (e.g. server FQDN or YOUR name) []:TiDB admin
    Email Address []:s@pingcap.com
    ```

    > **Note:**
    >
    > In the above certificate details, texts after `:` are the entered information.

### Generate server key and certificate

1. Execute the following command to generate the server key:

    ```bash
    sudo openssl req -newkey rsa:2048 -days 365000 -nodes -keyout server-key.pem -out server-req.pem
    ```

2. Enter detailed certificate information. For example:

    ```bash
    Country Name (2 letter code) [AU]:US
    State or Province Name (full name) [Some-State]:California
    Locality Name (e.g. city) []:San Francisco
    Organization Name (e.g. company) [Internet Widgits Pty Ltd]:PingCAP Inc.
    Organizational Unit Name (e.g. section) []:TiKV
    Common Name (e.g. server FQDN or YOUR name) []:TiKV Test Server
    Email Address []:k@pingcap.com

    Please enter the following 'extra' attributes
    to be sent with your certificate request
    A challenge password []:
    An optional company name []:
    ```

3. Execute the following command to generate the RSA key of the server:

    ```bash
    sudo openssl rsa -in server-key.pem -out server-key.pem
    ```

    The output of the above command:

    ```bash
    writing RSA key
    ```

4. Use the CA certificate signature to generate the signed server certificate:

    ```bash
    sudo openssl x509 -req -in server-req.pem -days 365000 -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 -out server-cert.pem
    ```

    The output of the above command (for example):

    ```bash
    Signature ok
    subject=C = US, ST = California, L = San Francisco, O = PingCAP Inc., OU = TiKV, CN = TiKV Test Server, emailAddress = k@pingcap.com
    Getting CA Private Key
    ```

    > **Note:**
    >
    > When you log in, TiDB checks whether the information in the `subject` section of the above output is consistent or not.

### Generate client key and certificate

After generating the server key and certificate, you need to generate the key and certificate for the client. It is often necessary to generate different keys and certificates for different users.

1. Execute the following command to generate the client key:

    ```bash
    sudo openssl req -newkey rsa:2048 -days 365000 -nodes -keyout client-key.pem -out client-req.pem
    ```

2. Enter detailed certificate information. For example:

    ```bash
    Country Name (2 letter code) [AU]:US
    State or Province Name (full name) [Some-State]:California
    Locality Name (e.g. city) []:San Francisco
    Organization Name (e.g. company) [Internet Widgits Pty Ltd]:PingCAP Inc.
    Organizational Unit Name (e.g. section) []:TiDB
    Common Name (e.g. server FQDN or YOUR name) []:tpch-user1
    Email Address []:zz@pingcap.com

    Please enter the following 'extra' attributes
    to be sent with your certificate request
    A challenge password []:
    An optional company name []:
    ```

3. Execute the following command to generate the RSA key of the client:

    ```bash
    sudo openssl rsa -in client-key.pem -out client-key.pem
    ```

    The output of the above command:

    ```bash
    writing RSA key
    ```

4. Use the CA certificate signature to generate the client certificate:

    ```bash
    sudo openssl x509 -req -in client-req.pem -days 365000 -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 -out client-cert.pem
    ```

    The output of the above command (for example):

    ```bash
    Signature ok
    subject=C = US, ST = California, L = San Francisco, O = PingCAP Inc., OU = TiDB, CN = tpch-user1, emailAddress = zz@pingcap.com
    Getting CA Private Key
    ```

    > **Note:**
    >
    > The information of the `subject` section in the above output is used for [certificate configuration for login verification](#configure-the-user-certificate-information-for-login-verification) in the `REQUIRE` section.

### Verify certificate

Execute the following command to verify certificate:

```bash
openssl verify -CAfile ca-cert.pem server-cert.pem client-cert.pem
```

If the certificate is verified, you will see the following result:

```
server-cert.pem: OK
client-cert.pem: OK
```

## Configure TiDB and the client to use certificates

After generating the certificates, you need to configure the TiDB server and the client to use the corresponding server certificate or client certificate.

### Configure TiDB to use server certificate

Modify the `[security]` section in the TiDB configuration file. This step specifies the directory in which the CA certificate, the server key, and the server certificate are stored. You can replace `path/to/server-cert.pem`, `path/to/server-key.pem`, `path/to/ca-cert.pem` with your own directory.

```toml
[security]
ssl-cert = "path/to/server-cert.pem"
ssl-key = "path/to/server-key.pem"
ssl-ca = "path/to/ca-cert.pem"
```

Start TiDB and check logs. If the following information is displayed in the log, the configuration is successful:

```
[INFO] [server.go:286] ["mysql protocol server secure connection is enabled"] ["client verification enabled"=true]
```

### Configure the client to use client certificate

Configure the client so that the client uses the client key and certificate for login.

Taking the MySQL client as an example, you can use the newly created client certificate, client key and CA by specifying `ssl-cert`, `ssl-key`, and `ssl-ca`:

```bash
mysql -u test -h 0.0.0.0 -P 4000 --ssl-cert /path/to/client-cert.new.pem --ssl-key /path/to/client-key.new.pem --ssl-ca /path/to/ca-cert.pem
```

> **Note:**
>
> `/path/to/client-cert.new.pem`, `/path/to/client-key.new.pem`, and `/path/to/ca-cert.pem` are the directory of the CA certificate, client key, and client certificate. You can replace them with your own directory.

## Configure the user certificate information for login verification

First, connect TiDB using the client to configure the login verification. Then, you can get and configure the user certificate information to be verified.

### Get user certificate information

The user certificate information can be specified by `REQUIRE SUBJECT`, `REQUIRE ISSUER`, `REQUIRE SAN`, and `REQUIRE CIPHER`, which are used to check the X.509 certificate attributes.

+ `REQUIRE SUBJECT`: Specifies the subject information of the client certificate when you log in. With this option specified, you do not need to configure `REQUIRE SSL` or `REQUIRE X509`. The information to be specified is consistent with the entered subject information in [Generate client keys and certificates](#generate-client-key-and-certificate).

    To get this option, execute the following command:

    ```bash
    openssl x509 -noout -subject -in client-cert.pem | sed 's/.\{8\}//'  | sed 's/, /\//g' | sed 's/ = /=/g' | sed 's/^/\//'
    ```

+ `REQUIRE ISSUER`: Specifies the `subject` information of the CA certificate that issues the user certificate. The information to be specified is consistent with the entered `subject` information in [Generate CA key and certificate](#generate-ca-key-and-certificate).

    To get this option, execute the following command:

    ```bash
    openssl x509 -noout -subject -in ca-cert.pem | sed 's/.\{8\}//'  | sed 's/, /\//g' | sed 's/ = /=/g' | sed 's/^/\//'
    ```

+ `REQUIRE SAN`: Specifies the `Subject Alternative Name` information of the CA certificate that issues the user certificate. The information to be specified is consistent with the [`alt_names` of the `openssl.cnf` configuration file](https://docs.pingcap.com/tidb/stable/generate-self-signed-certificates) used to generate the client certificate.

    + Execute the following command to get the information of the `REQUIRE SAN` item in the generated certificate:

        ```shell
        openssl x509 -noout -extensions subjectAltName -in client.crt
        ```

    + `REQUIRE SAN` currently supports the following `Subject Alternative Name` check items:

        - URI
        - IP
        - DNS

    + Multiple check items can be configured after they are connected by commas. For example, configure `REQUIRE SAN` as follows for the `u1` user:

        ```sql
        CREATE USER 'u1'@'%' REQUIRE SAN 'DNS:d1,URI:spiffe://example.org/myservice1,URI:spiffe://example.org/myservice2';
        ```

        The above configuration only allows the `u1` user to log in to TiDB using the certificate with the URI item `spiffe://example.org/myservice1` or `spiffe://example.org/myservice2` and the DNS item `d1`.

+ `REQUIRE CIPHER`: Checks the cipher method supported by the client. Use the following statement to check the list of supported cipher methods:

    ```sql
    SHOW SESSION STATUS LIKE 'Ssl_cipher_list';
    ```

### Configure user certificate information

After getting the user certificate information (`REQUIRE SUBJECT`, `REQUIRE ISSUER`, `REQUIRE SAN`, `REQUIRE CIPHER`), configure these information to be verified when creating a user, granting privileges, or altering a user. Replace `<replaceable>` with the corresponding information in the following statements.

You can configure one option or multiple options using the space or `and` as the separator.

+ Configure user certificate when creating a user (`CREATE USER`):

    ```sql
    CREATE USER 'u1'@'%' REQUIRE ISSUER '<replaceable>' SUBJECT '<replaceable>' SAN '<replaceable>' CIPHER '<replaceable>';
    ```

+ Configure user certificate when altering a user:

    ```sql
    ALTER USER 'u1'@'%' REQUIRE ISSUER '<replaceable>' SUBJECT '<replaceable>' SAN '<replaceable>' CIPHER '<replaceable>';
    ```

After the above configuration, the following items will be verified when you log in:

+ SSL is used; the CA that issues the client certificate is consistent with the CA configured in the server.
+ The `issuer` information of the client certificate matches the information specified in `REQUIRE ISSUER`.
+ The cipher used for the connection matches the one specified in `REQUIRE CIPHER`.
+ The `Subject Alternative Name` information of the client certificate matches the information specified in `REQUIRE SAN`.

You can log into TiDB only after all the above items are verified. Otherwise, the `ERROR 1045 (28000): Access denied` error is returned. You can use the following command to check the TLS version, the cipher algorithm and whether the current connection uses the certificate for the login.

Connect the MySQL client and execute the following statement:

```sql
\s
```

The output:

```
--------------
mysql  Ver 8.5.0 for Linux on x86_64 (MySQL Community Server - GPL)

Connection id:       1
Current database:    test
Current user:        root@127.0.0.1
SSL:                 Cipher in use is TLS_AES_128_GCM_SHA256
```

Then execute the following statement:

```sql
SHOW VARIABLES LIKE '%ssl%';
```

The output:

```
+---------------+----------------------------------+
| Variable_name | Value                            |
+---------------+----------------------------------+
| have_openssl  | YES                              |
| have_ssl      | YES                              |
| ssl_ca        | /path/to/ca-cert.pem             |
| ssl_cert      | /path/to/server-cert.pem         |
| ssl_cipher    |                                  |
| ssl_key       | /path/to/server-key.pem          |
+---------------+----------------------------------+
6 rows in set (0.06 sec)
```

## Update and replace certificate

The key and certificate are updated regularly. The following sections introduce how to update the key and certificate.

The CA certificate is the basis for mutual verification between the client and server. To replace the CA certificate, generate a combined certificate that supports the authentication for both old and new certificates. On the client and server, first replace the CA certificate, then replace the client/server key and certificate.

### Update CA key and certificate

1. Back up the old CA key and certificate (suppose that `ca-key.pem` is stolen):

    ```bash
    mv ca-key.pem ca-key.old.pem && \
    mv ca-cert.pem ca-cert.old.pem
    ```

2. Generate the new CA key:

    ```bash
    sudo openssl genrsa 2048 > ca-key.pem
    ```

3. Generate the new CA certificate using the newly generated CA key:

    ```bash
    sudo openssl req -new -x509 -nodes -days 365000 -key ca-key.pem -out ca-cert.new.pem
    ```

    > **Note:**
    >
    > Generating the new CA certificate is to replace the keys and certificates on the client and server, and to ensure that online users are not affected. Therefore, the appended information in the above command must be consistent with the `REQUIRE ISSUER` information.

4. Generate the combined CA certificate:

    ```bash
    cat ca-cert.new.pem ca-cert.old.pem > ca-cert.pem
    ```

After the above operations, restart the TiDB server with the newly created combined CA certificate. Then the server accepts both the new and old CA certificates.

Also replace the old CA certificate with the combined certificate so that the client accepts both the old and new CA certificates.

### Update client key and certificate

> **Note:**
>
> Perform the following steps **only after** you have replaced the old CA certificate on the client and server with the combined CA certificate.

1. Generate the new RSA key of the client:

    ```bash
    sudo openssl req -newkey rsa:2048 -days 365000 -nodes -keyout client-key.new.pem -out client-req.new.pem && \
    sudo openssl rsa -in client-key.new.pem -out client-key.new.pem
    ```

    > **Note:**
    >
    > The above command is to replace the client key and certificate, and to ensure that the online users are not affected. Therefore, the appended information in the above command must be consistent with the `REQUIRE SUBJECT` information.

2. Use the combined certificate and the new CA key to generate the new client certificate:

    ```bash
    sudo openssl x509 -req -in client-req.new.pem -days 365000 -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 -out client-cert.new.pem
    ```

3. Make the client (for example, MySQL) connect TiDB with the new client key and certificate:

    ```bash
    mysql -u test -h 0.0.0.0 -P 4000 --ssl-cert /path/to/client-cert.new.pem --ssl-key /path/to/client-key.new.pem --ssl-ca /path/to/ca-cert.pem
    ```

    > **Note:**
    >
    > `/path/to/client-cert.new.pem`, `/path/to/client-key.new.pem`, and `/path/to/ca-cert.pem` specify the directory of the CA certificate, client key, and client certificate. You can replace them with your own directory.

### Update the server key and certificate

1. Generate the new RSA key of the server:

    ```bash
    sudo openssl req -newkey rsa:2048 -days 365000 -nodes -keyout server-key.new.pem -out server-req.new.pem && \
    sudo openssl rsa -in server-key.new.pem -out server-key.new.pem
    ```

2. Use the combined CA certificate and the new CA key to generate the new server certificate:

    ```bash
    sudo openssl x509 -req -in server-req.new.pem -days 365000 -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 -out server-cert.new.pem
    ```

3. Configure the TiDB server to use the new server key and certificate. Place the files in the same directory specified in the [Configure TiDB to use server certificate](#configure-tidb-to-use-server-certificate) section.

    ```sql
    ALTER INSTANCE RELOAD TLS;
    ```

## Policy-based access control for certificates

TiDB supports policy-based access control (PBAC) for certificates, leveraging policies defined by the underlying key management server. This enables fine-grained control over access based on various criteria, such as time-based policies (for example, certificates only valid during specific hours), location-based policies (for example, restricting access to certain geographic locations), and other customizable conditions, ensuring enhanced security and flexibility in certificate management.