# Table Row and KV Mapping

+ The pattern of KEY: **`tablePrefix{TableID}_recordPrefixSep{RowID}`**
+ Mapping of table data to KV
+ TiKV hosts a vast sorted key-value map

```10
1, "TiDB", "SQL Layer", 10: ~!@t10_r1@!~ --> ["TiDB", "SQL Layer", 10]
2, "TiKV", "KV Engine", 20: ~!@t10_r2@!~ --> ["TiKV", "KV Engine", 20]
3, "PD", "Manager", 30: ~!@t10_r3@!~ --> ["PD", "Manager", 30]
```
------------------------------------------------------------------------------
Based on the distributed storage capacity provided by TiKV, TiDB builds a computing engine that combines excellent transaction processing capabilities and good data analysis capabilities. This article first introduces how TiDB maps data from a library table to a (Key, Value) key-value pair in TiKV starting with the data mapping algorithm, then describes the TiDB metadata management method, and finally introduces the main architecture of the TiDB SQL layer.

In a relational database, a table can have many columns. To map each column of data in a row to a (Key, Value) key-value pair, you need to consider how to construct a Key. First, in the OLTP scenario, there are a large number of operations such as adding, deleting, changing, and checking single or multiple rows, which require the database to have the ability to quickly read one row of data. Therefore, it is best to have a unique ID (visible or implicit) for the corresponding Key to facilitate quick positioning. Second, many OLAP-type query require full table scan. If you can encode the keys of all row in a table into one interval, you can efficiently complete the task of full table scan with range query.

  - In order to ensure that the data of the same table are put together and easy to find, TiDB assigns a table ID to each table, represented by TableID. The table ID is an integer that is unique across the cluster.
  - TiDB assigns a row ID to each row of data in the table, expressed as a rowID. The row ID is also an integer, unique within the table. For row IDs, TiDB has made a small optimization. If a table has int primary key, TiDB uses the value of the primary key as the row ID of the row data.

Each row of data is encoded into (Key, Value) key-value pair according to the following rules:
  Key:   `tablePrefix{TableID}_recordPrefixSep{RowID}`
  Value: `[col1, col2, col3, col4]`
  
Note: This slide shows the mapping pattern for table rows, indexes are stored in a slightly different way.