| 249 | |
| 250 | |
| 251 | void registerDataTypeMap(DataTypeFactory & factory) |
| 252 | { |
| 253 | factory.registerDataType("Map", create, DataTypeFactory::Case::Sensitive, Documentation{ |
| 254 | .description = R"DOCS_MD( |
| 255 | Data type `Map(K, V)` stores key-value pairs. |
| 256 | |
| 257 | Unlike other databases, maps are not unique in ClickHouse, i.e. a map can contain two elements with the same key. |
| 258 | (The reason for that is that maps are internally implemented as `Array(Tuple(K, V))`.) |
| 259 | |
| 260 | You can use use syntax `m[k]` to obtain the value for key `k` in map `m`. |
| 261 | Also, `m[k]` scans the map, i.e. the runtime of the operation is linear in the size of the map. |
| 262 | |
| 263 | **Parameters** |
| 264 | |
| 265 | - `K` — The type of the Map keys. Arbitrary type except [Nullable](../../sql-reference/data-types/nullable.md) and [LowCardinality](../../sql-reference/data-types/lowcardinality.md) nested with [Nullable](../../sql-reference/data-types/nullable.md) types. |
| 266 | - `V` — The type of the Map values. Arbitrary type. |
| 267 | |
| 268 | **Examples** |
| 269 | |
| 270 | Create a table with a column of type map: |
| 271 | |
| 272 | ```sql title="Query" |
| 273 | CREATE TABLE tab (m Map(String, UInt64)) ENGINE=Memory; |
| 274 | INSERT INTO tab VALUES ({'key1':1, 'key2':10}), ({'key1':2,'key2':20}), ({'key1':3,'key2':30}); |
| 275 | ``` |
| 276 | |
| 277 | To select `key2` values: |
| 278 | |
| 279 | ```sql title="Query" |
| 280 | SELECT m['key2'] FROM tab; |
| 281 | ``` |
| 282 | |
| 283 | ```text title="Response" |
| 284 | ┌─arrayElement(m, 'key2')─┐ |
| 285 | │ 10 │ |
| 286 | │ 20 │ |
| 287 | │ 30 │ |
| 288 | └─────────────────────────┘ |
| 289 | ``` |
| 290 | |
| 291 | If the requested key `k` is not contained in the map, `m[k]` returns the value type's default value, e.g. `0` for integer types and `''` for string types. |
| 292 | To check whether a key exists in a map, you can use function [mapContains](/sql-reference/functions/tuple-map-functions#mapContainsKey). |
| 293 | |
| 294 | ```sql title="Query" |
| 295 | CREATE TABLE tab (m Map(String, UInt64)) ENGINE=Memory; |
| 296 | INSERT INTO tab VALUES ({'key1':100}), ({}); |
| 297 | SELECT m['key1'] FROM tab; |
| 298 | ``` |
| 299 | |
| 300 | ```text title="Response" |
| 301 | ┌─arrayElement(m, 'key1')─┐ |
| 302 | │ 100 │ |
| 303 | │ 0 │ |
| 304 | └─────────────────────────┘ |
| 305 | ``` |
| 306 | |
| 307 | ## Converting Tuple to Map {#converting-tuple-to-map} |
| 308 |
no test coverage detected