Compartilhar via


DESCRIBE TABLE

Aplica-se a:marca de seleção positiva SQL do Databricks marca de seleção positiva Runtime do Databricks

Retorna as informações básicas de metadados de uma tabela. As informações de metadados incluem o nome, o tipo e o comentário da coluna. Opcionalmente, você pode definir uma especificação de partição ou um nome de coluna para retornar os metadados pertencentes a uma partição ou coluna, respectivamente. Com tabelas Delta, nem todos os campos são retornados.

Os metadados são retornados no formulário de relatório ou como um documento JSON.

Importante

Use DESCRIBE AS JSON para analisar descrever a saída programaticamente. O formato de relatório não JSON está sujeito a alterações.

Sintaxe

{ DESC | DESCRIBE } [ TABLE ] [ EXTENDED ] table_name { [ PARTITION clause ] | [ column_name ] } [ AS JSON ]

Para compatibilidade, FORMATTED pode ser especificado como um sinônimo para EXTENDED.

Parâmetros

  • EXTENDED

    Se definido, exibe informações detalhadas sobre as colunas especificadas, incluindo as estatísticas de coluna coletadas pelo comando e informações de metadados adicionais (como qualificador de esquema, proprietário e tempo de acesso).

  • table_name

    Identifica a tabela a ser descrita. O nome não pode usar uma especificação temporal ou especificação de opções. Se a tabela não puder ser encontrada, o Azure Databricks gerará um erro TABLE_OR_VIEW_NOT_FOUND.

  • Cláusula PARTITION

    Um parâmetro opcional que direciona o Databricks SQL para retornar metadados de adição para as partições nomeadas.

  • column_name

    Um parâmetro opcional com o nome da coluna que precisa ser descrito. As colunas aninhadas atualmente não podem ser especificadas.

    O formato JSON tem suporte para colunas individuais.

  • AS JSON

    Aplica-se a:com marcação de verificação sim Databricks Runtime 16.2 e posteriores

    Opcionalmente, retorna os metadados da tabela como uma cadeia de caracteres JSON em vez de um relatório legível por humanos. Use esse formato ao analisar o resultado usando um programa.

    O suporte é oferecido apenas quando o formato EXTENDED é especificado.

Os parâmetros partition_spec e column_name são mutuamente exclusivos e não podem ser especificados juntos.

Saída formatada em JSON

Quando AS JSON é especificado, a saída é retornada como uma cadeia de caracteres JSON. Há suporte para o seguinte esquema:

{
  "table_name": "<table_name>",
  "catalog_name": "<catalog_name>",
  "schema_name": "<schema_name>",
  "namespace": ["<schema_name>"],
  "type": "<table_type>",
  "provider": "<provider>",
  "columns": [
    {
      "name": "<name>",
      "type": <type_json>,
      "comment": "<comment>",
      "nullable": <boolean>,
      "default": "<default_val>"
    }
  ],
  "partition_values": {
    "<col_name>": "<val>"
  },
  "partition_columns": ["col1", "col2"],
  "location": "<path>",
  "view_text": "<view_text>",
  "view_original_text": "<view_original_text>",
  "view_schema_mode": "<view_schema_mode>",
  "view_catalog_and_namespace": "<view_catalog_and_namespace>",
  "view_query_output_columns": ["<col_name>"],
  "comment": "<comment>",
  "table_properties": {
    "property1": "<property1>",
    "property2": "<property2>"
  },
  "statistics": {
    "num_rows": <count>,
    "size_in_bytes": <bytes>,
    "table_change_stats": {
      "inserted": <count>,
      "deleted": <count>,
      "updated": <count>,
      "change_percent": <percent_changed_float>
    }
  },
  "storage_properties": {
    "property1": "<property1>",
    "property2": "<property2>"
  },
  "serde_library": "<serde_library>",
  "input_format": "<input_format>",
  "output_format": "<output_format>",
  "num_buckets": <num_buckets>,
  "bucket_columns": ["<col_name>"],
  "sort_columns": ["<col_name>"],
  "created_time": "<timestamp_ISO-8601>",
  "created_by": "<created_by>",
  "last_access": "<timestamp_ISO-8601>",
  "partition_provider": "<partition_provider>"
}

Abaixo estão as definições de esquema para <type_json>:

Tipo de SQL Declaração JSON
TINYINT { "name" : "tinyint" }
SMALLINT { "name" : "smallint" }
INT { "name" : "int" }
BIGINT { "name" : "bigint" }
FLOAT { "name" : "float" }
DOUBLE { "name" : "double" }
DECIMAL(p, s) { "name" : "decimal", "precision": p, "scale": s }
STRING { "name" : "string" }
VARCHAR(n) { "name" : "varchar", "length": n }
CHAR(n) { "name" : "char", "length": n }
BINARY { "name" : "binary" }
BOOLIANO { "name" : "boolean" }
DATE { "name" : "date" }
TIMESTAMP { "name" : "timestamp_ltz" }
TIMESTAMP_NTZ { "name" : "timestamp_ntz" }
INTERVAL start_unit TO end_unit { "name" : "interval", "start_unit": "<start_unit>", "end_unit": "<end_unit>" }
ARRAY<element_type> { "name" : "array", "element_type": <type_json>, "element_nullable": <boolean_val> }
MAP<key_type, value_type> { "name" : "map", "key_type": <type_json>, "value_type": <type_json>, "element_nullable": <boolean_val> }
STRUCT<field_name …, …> { "name" : "struct", "fields": [ {"name" : "<field_name>", "type" : <type_json>, “nullable”: <boolean_val>, "comment": “<field_comment>”, "default": “<default_val>”}] }
VARIANT { "name" : "variant" }

Exemplos

-- Creates a table `customer`. Assumes current schema is `salesdb`.
> CREATE TABLE customer(
        cust_id INT,
        state VARCHAR(20),
        name STRING COMMENT 'Short name'
    )
    USING parquet
    PARTITIONED BY (state);

> INSERT INTO customer PARTITION (state = 'AR') VALUES (100, 'Mike');

-- Returns basic metadata information for unqualified table `customer`
> DESCRIBE TABLE customer;
                col_name data_type    comment
 ----------------------- --------- ----------
                 cust_id       int       null
                    name    string Short name
                   state    string       null
 # Partition Information
              # col_name data_type    comment
                   state    string       null

-- Returns basic metadata information for qualified table `customer`
> DESCRIBE TABLE salesdb.customer;
                col_name data_type    comment
 ----------------------- --------- ----------
                 cust_id       int       null
                    name    string Short name
                   state    string       null
 # Partition Information
              # col_name data_type    comment
                   state    string       null

-- Returns additional metadata such as parent schema, owner, access time etc.
> DESCRIBE TABLE EXTENDED customer;
                     col_name                      data_type    comment
 ---------------------------- ------------------------------ ----------
                      cust_id                            int       null
                         name                         string Short name
                        state                         string       null
      # Partition Information
                   # col_name                      data_type    comment
                        state                         string       null

 # Detailed Table Information
                     Database                        default
                        Table                       customer
                        Owner                  <TABLE OWNER>
                 Created Time   Tue Apr 07 22:56:34 JST 2020
                  Last Access                        UNKNOWN
                   Created By                <SPARK VERSION>
                         Type                        MANAGED
                     Provider                        parquet
                     Location file:/tmp/salesdb.db/custom...
                Serde Library org.apache.hadoop.hive.ql.i...
                  InputFormat org.apache.hadoop.hive.ql.i...
                 OutputFormat org.apache.hadoop.hive.ql.i...
           Partition Provider                        Catalog

-- Returns partition metadata such as partitioning column name, column type and comment.
> DESCRIBE TABLE EXTENDED customer PARTITION (state = 'AR');
                       col_name                      data_type    comment
 ------------------------------ ------------------------------ ----------
                         cust_id                            int       null
                           name                         string Short name
                          state                         string       null
        # Partition Information
                     # col_name                      data_type    comment
                          state                         string       null

 # Detailed Partition Inform...
                       Database                        default
                          Table                       customer
               Partition Values                     [state=AR]
                       Location file:/tmp/salesdb.db/custom...
                  Serde Library org.apache.hadoop.hive.ql.i...
                    InputFormat org.apache.hadoop.hive.ql.i...
                   OutputFormat org.apache.hadoop.hive.ql.i...
             Storage Properties [serialization.format=1, pa...
           Partition Parameters {transient_lastDdlTime=1586...
                   Created Time   Tue Apr 07 23:05:43 JST 2020
                    Last Access                        UNKNOWN
           Partition Statistics                      659 bytes

          # Storage Information
                       Location file:/tmp/salesdb.db/custom...
                  Serde Library org.apache.hadoop.hive.ql.i...
                    InputFormat org.apache.hadoop.hive.ql.i...
                   OutputFormat org.apache.hadoop.hive.ql.i...
 ------------------------------ ------------------------------ ----------

-- Returns the metadata for `name` column.
-- Optional `TABLE` clause is omitted and column is fully qualified.
> DESCRIBE customer salesdb.customer.name;
 info_name info_value
 --------- ----------
  col_name       name
 data_type     string
   comment Short name

- Returns the table metadata in JSON format.
DESCRIBE EXTENDED customer AS JSON;
{
  "table_name":"customer",
  "catalog_name":"spark_catalog",
  "schema_name":"default",
  "namespace":["default"],
  "columns":[
    {"name":"cust_id","type":{"name":"integer"},"nullable":true},
    {"name":"name","type":{"name":"string"},"comment":"Short name","nullable":true},
    {"name":"state","type":{"name":"varchar","length":20},"nullable":true}],
  "location": "file:/tmp/salesdb.db/custom...",
  "created_time":"2020-04-07T14:05:43Z",
  "last_access":"UNKNOWN",
  "created_by":"None",
  "type":"MANAGED",
  "provider":"parquet",
  "partition_provider":"Catalog",
  "partition_columns":["state"]}

DESCRIBE DETAIL

DESCRIBE DETAIL [schema_name.]table_name

Retorne informações sobre esquema, particionamento, tamanho da tabela e assim por diante. Por exemplo, para tabelas Delta, você pode ver as versões atuais do leitor e do autor de uma tabela. Confira Examinar os detalhes da tabela do Delta Lake com describe detail.