ALTER TABLE

Se aplica a:check marked yes Databricks SQL check marked yes Databricks Runtime

Modifica el esquema o las propiedades de una tabla.

Para obtener información sobre cambios de tipo o cambios de nombre de las columnas en Delta Lake, consulte reescritura de los datos.

Para cambiar el comentario de una tabla, use COMMENT ON.

Para modificar un STREAMING TABLE, use ALTER STREAMING TABLE.

Si la tabla se almacena en caché, el comando borra los datos almacenados en caché de la tabla y todos los elementos dependientes que hacen referencia a ella. La memoria caché se rellenará en diferido cuando se acceda a la tabla o a los elementos dependientes la próxima vez.

Nota:

Al agregar una columna a una tabla Delta existente, no se puede definir un valor de DEFAULT. Todas las columnas agregadas a las tablas Delta se tratan como NULL para las filas existentes. Después de agregar una columna, puede definir opcionalmente un valor predeterminado para la columna, pero solo se aplica a las nuevas filas insertadas en la tabla. Use la sintaxis siguiente:

ALTER TABLE table_name ALTER COLUMN column_name SET DEFAULT default_expression

En tablas externas, puede ejecutar solo ALTER TABLE SET OWNER y ALTER TABLE RENAME TO.

Permisos necesarios

Si usa Unity Catalog, debe tener el permiso MODIFY para:

  • ALTER COLUMN
  • ADD COLUMN
  • DROP COLUMN
  • SET TBLPROPERTIES
  • UNSET TBLPROPERTIES
  • modificar OPTIMIZACIÓN PREDICTIVA

Todas las demás operaciones requieren la titularidad de la tabla.

Sintaxis

ALTER TABLE table_name
   { RENAME TO clause |
     ADD COLUMN clause |
     ALTER COLUMN clause |
     DROP COLUMN clause |
     RENAME COLUMN clause |
     ADD CONSTRAINT clause |
     DROP CONSTRAINT clause |
     DROP FEATURE clause |
     ADD PARTITION clause |
     DROP PARTITION clause |
     PARTITION SET LOCATION clause |
     RENAME PARTITION clause |
     RECOVER PARTITIONS clause |
     SET { ROW FILTER clause } |
     DROP ROW FILTER |
     SET TBLPROPERTIES clause |
     UNSET TBLPROPERTIES clause |
     SET SERDE clause |
     SET LOCATION clause |
     SET OWNER TO clause |
     SET SERDE clause |
     SET TAGS clause |
     UNSET TAGS clause |
     CLUSTER BY clause }
     PREDICTIVE OPTIMIZATION clause}

Parámetros

  • table_name

    Identifica la tabla que se va a modificar. El nombre no debe incluir una especificación temporal. Si no se encuentra la tabla, Azure Databricks genera un error TABLE_OR_VIEW_NOT_FOUND.

  • RENAME TOto_table_name

    Cambia el nombre de la tabla en el mismo esquema.

  • AGREGAR COLUMNA

    Agrega una o más columnas a la tabla.

  • ALTER COLUMN

    Cambia una propiedad o la ubicación de una columna.

  • DROP COLUMN

    Elimine una o varias columnas o campos en una tabla Delta Lake.

  • RENAME COLUMN

    Cambia el nombre de una columna o de un campo de una tabla de Delta Lake.

  • ADD CONSTRAINT

    Agrega una restricción de comprobación, una restricción de clave externa informativa o una restricción de clave principal informativa a la tabla.

    Las claves externas y las claves primarias solo se admiten para tablas en Unity Catalog, no para el catálogo hive_metastore.

  • DROP CONSTRAINT

    Elimina una restricción PRIMARY KEY, FOREIGN KEY o CHECK de la tabla.

  • DROP FEATURE feature_name [ TRUNCATE HISTORY ]

    Se aplica a:check marked yes Databricks SQL check marked yes Databricks Runtime 14.1 y versiones posteriores

    Quita una característica de una tabla de Delta Lake.

    La eliminación de características que afectan tanto a los lectores como a los escritores requieren un proceso de dos fases:

    Consulte las características de la tabla para obtener más información.

    • feature_name

      El nombre de una característica en forma de STRING literal o identificador que Azure Databricks debe entender y admitir en la tabla.

      Los feature_names admitidos son:

      • ‘deletionVectors’ o deletionvectors
        • ‘v2Checkpoint’ o v2checkpoint

      Si la característica no está presente en la tabla Azure Databricks genera DELTA_FEATURE_DROP_FEATURE_NOT_PRESENT.

    • TRUNCATE HISTORY

      Opcionalmente, permite iniciar la segunda fase de quitar una característica de lector más escritor transcurridas 24 horas, truncando el historial de la tabla hasta el momento en que se ejecutó el comando de invocación.

      Truncar el historial de tablas limita la capacidad de realizar DESCRIBE HISTORY y ejecutar consultas de viaje en el tiempo.

  • ADD PARTITION

    Agrega una o varias particiones a la tabla.

  • DROP PARTITION

    Quita una o varias particiones de la tabla.

  • PARTITION … SET LOCATION

    Asigna la ubicación de una partición.

  • RENAME PARTITION

    Reemplaza las claves de una partición.

  • RECOVER PARTITIONS

    Indica a Azure Databricks que examine la ubicación de la tabla y agregue los archivos que se hayan agregado directamente al sistema de archivos a la tabla.

  • SETCláusula ROW FILTER

    Se aplica a:check marked yes Databricks SQL check marked yes Databricks Runtime 12.2 y versiones posteriores check marked yes Catálogo de Unity

    Importante

    Esta característica está en versión preliminar pública.

    Agrega una función de filtro de fila a la tabla. Todas las consultas futuras desde esa tabla recibirán un subconjunto de sus filas para las que la función se evalúa como un valor TRUE booleano. Esto puede ser útil para fines de control de acceso específicos en los que la función puede inspeccionar la identidad o las pertenencias a grupos del usuario que realiza la invocación para decidir si se filtran determinadas filas.

  • DROP ROW FILTER

    Se aplica a:check marked yes Unity Catalog

    Importante

    Esta característica está en versión preliminar pública.

    Quita el filtro de fila de la tabla, si existe. Las consultas futuras devolverán todas las filas de la tabla sin ningún filtrado automático.

  • SET TBLPROPERTIES

    Este parámetro le permite establecer o restablecer una o más propiedades que defina el usuario.

  • UNSET TBLPROPERTIES

    Este parámetro quita una o más propiedades que defina el usuario.

  • SET LOCATION

    Mueve la ubicación de una tabla.

    SET LOCATION path
    
    • LOCATION path

      path debe ser un literal de STRING. Especifica la nueva ubicación de la tabla.

      Los archivos de la ubicación original no se trasladarán a la nueva ubicación.

  • [ SET ] OWNER TOprincipal

    Transfiere la propiedad de la tabla a principal.

    Se aplica a:check marked yes Databricks SQL Versión 2022.35 del almacén de SQL o versiones posteriores check marked yes Databricks Runtime 11.2 y versiones posteriores

    SET se permite como una palabra clave opcional.

  • SET TAGS ( { tag_name = tag_value } [, ...] )

    Se aplica a:check marked yes Databricks SQL check marked yes Databricks Runtime 13.3 LTS y versiones posteriores

    Aplica etiquetas a la tabla. Debe tener el permiso apply_tag para agregar etiquetas a la tabla.

    • tag_name

      Un literal de STRING. El tag_name debe ser único en la tabla o columna.

    • tag_value

      Un literal de STRING.

  • UNSET TAGS ( tag_name [, ...] )

    Se aplica a:check marked yes Databricks SQL check marked yes Databricks Runtime 13.3 LTS y versiones posteriores

    Elimina las etiquetas de la tabla. Debe tener el permiso apply_tag para quitar etiquetas de la tabla.

    • tag_name

      Un literal de STRING. El tag_name debe ser único en la tabla o columna.

  • Cláusula CLUSTER BY

    Se aplica a:check marked yes Databricks SQL check marked yes Databricks Runtime 13.3 LTS y versiones posteriores

    Agrega, cambia o anula la estrategia de agrupación en clústeres para una tabla de Delta Lake.

  • { ENABLE | DISABLE | INHERIT } PREDICTIVE OPTIMIZATION

    Aplica para:check marked yes Databricks SQL check marked yes Databricks Runtime 12.2 y versiones superiores check marked yesUnity Catalog únicamente

    Importante

    Esta característica está en versión preliminar pública.

    Modifica la tabla de Delta Lake administrada a la configuración de optimización predictiva deseada.

    De forma predeterminada, cuando se crean tablas, el comportamiento es INHERIT desde el esquema.

    Cuando la optimización predictiva está habilitada explícitamente o se hereda como habilitada OPTIMIZE y VACUUM se invocará automáticamente en la tabla según lo considere adecuado Azure Databricks. Para obtener más información, vea: optimización predictiva para Delta Lake.

Ejemplos

Para ver ejemplos de incorporación de restricciones y modificación de columnas de Delta Lake, consulte:

-- RENAME table
> DESCRIBE student;
                col_name data_type comment
 ----------------------- --------- -------
                    name    string    NULL
                  rollno       int    NULL
                     age       int    NULL
 # Partition Information
              # col_name data_type comment
                     age       int    NULL

> ALTER TABLE Student RENAME TO StudentInfo;

-- After Renaming the table
> DESCRIBE StudentInfo;
                col_name data_type comment
 ----------------------- --------- -------
                    name    string    NULL
                  rollno       int    NULL
                     age       int    NULL
 # Partition Information
              # col_name data_type comment
                     age       int    NULL

-- RENAME partition
> SHOW PARTITIONS StudentInfo;
 partition
 ---------
    age=10
    age=11
    age=12

> ALTER TABLE default.StudentInfo PARTITION (age='10') RENAME TO PARTITION (age='15');

-- After renaming Partition
> SHOW PARTITIONS StudentInfo;
 partition
 ---------
    age=11
    age=12
    age=15

-- Add new columns to a table
> DESCRIBE StudentInfo;
                col_name data_type comment
 ----------------------- --------- -------
                    name    string    NULL
                  rollno       int    NULL
                     age       int    NULL
 # Partition Information
              # col_name data_type comment
                     age       int    NULL

> ALTER TABLE StudentInfo ADD columns (LastName string, DOB timestamp);

-- After Adding New columns to the table
> DESCRIBE StudentInfo;
                col_name data_type comment
 ----------------------- --------- -------
                    name    string    NULL
                  rollno       int    NULL
                LastName    string    NULL
                     DOB timestamp    NULL
                     age       int    NULL
 # Partition Information
              # col_name data_type comment
                     age       int    NULL

-- Add a new partition to a table
> SHOW PARTITIONS StudentInfo;
 partition
 ---------
    age=11
    age=12
    age=15

> ALTER TABLE StudentInfo ADD IF NOT EXISTS PARTITION (age=18);

-- After adding a new partition to the table
> SHOW PARTITIONS StudentInfo;
 partition
 ---------
    age=11
    age=12
    age=15
    age=18

-- Drop a partition from the table
> SHOW PARTITIONS StudentInfo;
 partition
 ---------
    age=11
    age=12
    age=15
    age=18

> ALTER TABLE StudentInfo DROP IF EXISTS PARTITION (age=18);

-- After dropping the partition of the table
> SHOW PARTITIONS StudentInfo;
 partition
 ---------
    age=11
    age=12
    age=15

-- Adding multiple partitions to the table
> SHOW PARTITIONS StudentInfo;
 partition
 ---------
    age=11
    age=12
    age=15

> ALTER TABLE StudentInfo ADD IF NOT EXISTS PARTITION (age=18) PARTITION (age=20);

-- After adding multiple partitions to the table
> SHOW PARTITIONS StudentInfo;
 partition
 ---------
    age=11
    age=12
    age=15
    age=18
    age=20

-- ALTER or CHANGE COLUMNS
> DESCRIBE StudentInfo;
                col_name data_type comment
+-----------------------+---------+-------
                    name    string    NULL
                  rollno       int    NULL
                LastName    string    NULL
                     DOB timestamp    NULL
                     age       int    NULL
 # Partition Information
              # col_name data_type comment
                     age       int    NULL

ALTER TABLE StudentInfo ALTER COLUMN name COMMENT "new comment";

--After ALTER or CHANGE COLUMNS
> DESCRIBE StudentInfo;
                col_name data_type     comment
 ----------------------- --------- -----------
                    name    string new comment
                  rollno       int        NULL
                LastName    string        NULL
                     DOB timestamp        NULL
                     age       int        NULL
 # Partition Information
              # col_name data_type     comment
                     age       int        NULL

-- RENAME COLUMN
> ALTER TABLE StudentInfo RENAME COLUMN name TO FirstName;

--After RENAME COLUMN
> DESCRIBE StudentInfo;
                col_name data_type     comment
 ----------------------- --------- -----------
               FirstName    string new comment
                  rollno       int        NULL
                LastName    string        NULL
                     DOB timestamp        NULL
                     age       int        NULL
 # Partition Information
              # col_name data_type     comment
                     age       int        NULL

-- Change the file Location
> ALTER TABLE dbx.tab1 PARTITION (a='1', b='2') SET LOCATION '/path/to/part/ways';

-- SET SERDE/ SERDE Properties (DBR only)
> ALTER TABLE test_tab SET SERDE 'org.apache.hadoop.hive.serde2.columnar.LazyBinaryColumnarSerDe';

> ALTER TABLE dbx.tab1 SET SERDE 'org.apache.hadoop' WITH SERDEPROPERTIES ('k' = 'v', 'kay' = 'vee');

-- SET TABLE PROPERTIES
> ALTER TABLE dbx.tab1 SET TBLPROPERTIES ('winner' = 'loser');

-- DROP TABLE PROPERTIES
> ALTER TABLE dbx.tab1 UNSET TBLPROPERTIES ('winner');

-- Drop the "deletion vectors" from a Delta table
> ALTER TABLE my_table DROP FEATURE deletionVectors;

-- 24 hours later
> ALTER TABLE my_table DROP FEATURE deletionVectors TRUNCATE HISTORY;

-- Applies three tags to the table named `test`.
> ALTER TABLE test SET TAGS ('tag1' = 'val1', 'tag2' = 'val2', 'tag3' = 'val3');

-- Removes three tags from the table named `test`.
> ALTER TABLE test UNSET TAGS ('tag1', 'tag2', 'tag3');

-- Applies three tags to table `main.schema1.test` column `col1`.
> ALTER TABLE main.schema1.test ALTER COLUMN col1 SET TAGS ('tag1' = 'val1', 'tag2' = 'val2', 'tag3' = 'val3');

-- Removes three tags from table `main.schema1.test` column `col1`.
> ALTER TABLE main.schema1.test ALTER COLUMN col1 UNSET TAGS ('tag1', 'tag2', 'tag3');
-- Enables predictive optimization for my_table
> ALTER TABLE my_table ENABLE PREDICTIVE OPTIMIZATION;