Updated on 2024-06-03 GMT+08:00

REPLACE

Description

Inserts data into a table or replaces existing data in a table. If the data to be inserted has the primary key or unique key conflicts with the existing data, the REPLACE statement deletes the existing data and then inserts the new data.

You can use REPLACE in the following ways:

  • Replace or insert values. That is, VALUES or VALUE is used to construct a row of records and insert the row into the table.
  • Replace or insert the query. One or more rows of records are constructed based on the result set returned by SELECT and inserted into a table.
  • Set the value of a specified column. Similar to value insertion, the default value is used for columns that are not specified.

Precautions

  • To execute this statement, you must have the DELETE and INSERT permissions on the table.
  • If the primary key or unique key does not conflict, you can directly insert the data. If the primary key or unique key conflicts, delete the original data and then insert the new data.
  • The return format of the REPLACE operation is REPLACE 0 X, where X indicates the number of DELETE and INSERT operations.
  • In the REPLACE...SELECT syntax, the number of columns in select_list must be the same as the number of columns to be inserted.
  • In the REPLACE...SET syntax:
    • If col_name has a default value, SET col_name = col_name + 1 is equivalent to SET col_name = Default value of col_name + 1.
    • If col_name has neither default value nor NOT NULL constraint, SET col_name = col_name + 1 is equivalent to col_name = NULL.
    • If col_name does not have a default value but has a NOT NULL constraint, the data types that support a default value are timestamp, timestamp with time zone, time, time with time zone, interval, tinterval, smalldatetime, date, uuid, name, point, polygon, circle, lseg, box, json, jsonb, xml, varbit, numeric, cidr, inet, macaddr, numrange, int8range, int4range, tsrange, tstzrange, daterange, hash16, hash32, bool, bytea, char, bigint, int, smallint, tinyint, text, raw, blob, clob, float4, float8, abstime, reltime, bpchar, varchar, nvarchar, money, uint1, uint2, uint4, uint8, set, and enum. The default values are described in Table 1.
      Table 1 Default values for the data type

      Data Type

      Default Value of col_name

      int8, int4, int2, int1, float8, float4, numeric, uint1, uint2, uint4, and uint8

      0. If numeric specifies a decimal place, the decimal place is displayed. For example, NUMERIC (10, 3): 0.000

      text, clob, bpchar, varchar, char, nvarchar2, name, blob, raw, and varbit

      Empty string.

      numrange, int8range, int4range, tsrange, tstzrange, and daterange

      empty

      bytea

      \x

      money

      $0.00

      json, jsonb, and xml

      'null'

      macaddr

      00:00:00:00:00:00

      inet

      0.0.0.0

      cidr

      0.0.0.0/32

      point

      (0,0)

      lseg

      [(0,0),(0,0)]

      box

      (0,0),(0,0)

      path

      ((0,0))

      polygon

      ((0,0))

      circle

      <(0,0),0>

      uuid

      00000000-0000-0000-0000-000000000000

      hash16

      0000000000000000

      hash32

      00000000000000000000000000000000

      bool

      f

      abstime

      abstime '1970-01-01 00:00:00'

      reltime

      reltime '00:00:00'

      interval

      interval '00:00:00'

      tinterval

      tinterval(abstime '1970-01-01 00:00:00', abstime '1970-01-01 00:00:00')

      timestamp

      timestamp '1970-01-01 00:00:00'

      timestamp with time zone

      timestamptz '1970-01-01 00:00:00'

      date

      date '1970-01-01'

      time

      time '00:00:00'

      time with time zone

      timetz '00:00:00'

      smalldatetime

      smalldatetime '1970-01-01 00:00:00'

      • The default value of the enumerated type (ENUM) is the first element. If the first element does not exist, NULL is returned.
      • The SET data type is supported only when sql_compatibility is set to 'B'. The default value is an empty string.
      • When sql_compatibility is set to 'A', an empty string of the text, clob, blob, raw, bytea, varchar, nvarchar2, bpchar, char, name, byteawithoutorderwithqualcol, or byteawithoutordercol type is equivalent to NULL. If a column has a NOT NULL constraint, an error is reported when a reference column is used to insert data into a table.
      • When sql_compatibility is set to 'B', if b_format_version is set to '5.7', b_format_dev_version is set to 's1', and sql_mode does not contain strict_tans_tables, only_full_group_by, no_zero_in_date, no_zero_date, or error_for_division_by_zero, then the default values of timestamp and datetime are 0000-00-00 00:00:00, and the default value of DATE is 0000-00-00 under the NOT NULL constraint.
      • The uint1, uint2, uint4, and uint8 data types are supported only when sql_compatibility is set to 'B'.
      • If the default value of the function expression can be calculated during parsing, the default value is the calculated constant. Otherwise, the value is NULL.
      • In other scenarios, the default value is NULL.
  • In the REPLACE... SET syntax, the current col_name value depends on the previous col_name value. If there is no previous col_name value, the default value is used. For example, in the SET f1 = f1 + 1, f2 = f1 scenario, f1 is equal to the default value of f1 (assumed to 0) plus 1, and f2 is equal to the calculated value of f1, that is 1.
  • Triggers are supported. The execution sequence of triggers is determined by the actual execution process.
    • Executing INSERT will trigger the BEFORE INSERT and AFTER INSERT triggers.
    • Executing DELETE will trigger the BEFORE DELETE and AFTER DELETE triggers.
  • The unique constraint or primary key of DEFERRABLE is not supported.
  • If a table has multiple unique constraints and the inserted data violates multiple unique constraints, all the data that violates the constraints is deleted and new data is inserted. In this scenario, data may be deleted by mistake. Therefore, exercise caution when performing this operation.
  • If multiple rows are inserted and these rows have unique constraint conflicts with data in the same row in the table, the REPLACE operation is performed in sequence.
  • In SET col_name = col_name + 1, the length of col_name cannot exceed 1. For example, in SET col_name = table_name.col_name + 1, the length of table_name.col_name is 2. Formats such as B.A, C.B.A, and D.C.B.A are not supported.
  • When comparing floating-point data, note that precision loss may occur.
  • If a row-level security policy is created on a table, REPLACE INTO is not supported.
  • Foreign tables are not supported.
  • Encrypted tables are not supported.
  • Memory tables are not supported.

Syntax

  • Replace or insert values.
    REPLACE [ INTO ] table_name
        [ PARTITION ( partition_name [, ... ] ) ]
        [ ( col_name [, ... ] ) ]
        { VALUES | VALUE } ( value [, ... ] ) [, ... ];
  • Replace or insert the query.
    REPLACE [ INTO ] table_name
        [ PARTITION ( partition_name [, ... ] ) ]
        [ ( col_name [, ... ]) ]
        query;
  • Set the value of a specified column.
    REPLACE [ INTO ] table_name
        [ PARTITION ( partition_name [, ... ] ) ]
        SET col_name = value [, ... ];

Parameters

  • table_name

    Specifies the name of the target table where data will be inserted.

    Value range: an existing table name.

  • col_name

    Specifies the name of a column in a table.

    • The column name can be qualified with a subcolumn name or array index, if needed.
    • Each column not present in the column list will be filled with a default value, either its declared default value or NULL if there is none. Inserting data into only some columns of a composite type leaves the other columns NULL.
    • The target column names (specified by col_name) can be listed in any order. If no list of column names is given at all, the default is all the columns of the table in their declared order.
    • The target columns are the first N column names, if there are only N columns provided by the VALUE clause and QUERY.
    • The values provided by the VALUE clause and QUERY are joined with the corresponding columns from left to right in the table.

    Value range: an existing column.

  • PARTITION ( partition_name [, ... ] )

    Inserts data to a specified partition. partition_name indicates the partition name.

    If the value of the VALUE clause is inconsistent with that of the specified partition, an exception is displayed.

  • value

    Specifies the value to be inserted. The value format is as follows:

    { expression | DEFAULT }
    1. expression indicates that a valid expression or value is assigned to the corresponding column.

      If single-quotation marks are inserted in a column, the single-quotation marks need to be used for escape.

      If the expression for any column is not of the correct data type, automatic type conversion will be attempted. If the attempt fails, data insertion fails, and the system returns an error message.

    2. DEFAULT indicates the default value of the corresponding column name. The value is NULL if no default value is assigned to it.
  • query

    Specifies a query statement (SELECT statement) whose result is used as the data to be inserted.

Examples

-- Create a table.
gaussdb=# CREATE TABLE test(f1 int primary key, f2 int, f3 int);

-- Insert data.
gaussdb=# INSERT INTO test VALUES(1, 1, 1), (2, 2, 2), (3, 3, 3);
INSERT 0 3

-- Replace or insert values.
gaussdb=# REPLACE INTO test VALUES(1, 11, 11);
REPLACE 0 2

-- Query the result.
gaussdb=# SELECT * FROM test WHERE f1 = 1;
 f1 | f2 | f3
----+----+----
  1 | 11 | 11
(1 row)

-- Replace or insert the query.
gaussdb=# REPLACE INTO test SELECT 2, 22, 22;
REPLACE 0 2

-- Query the result.
gaussdb=# SELECT * FROM test WHERE f1 = 2;
 f1 | f2 | f3
----+----+----
  2 | 22 | 22
(1 row)

-- Replace or insert the specified column.
gaussdb=# REPLACE INTO test SET f1 = f1 + 3, f2 = f1 * 10 + 3, f3 = f2;
REPLACE 0 2

-- Query the result.
gaussdb=# SELECT * FROM test WHERE f1 = 3;
 f1 | f2 | f3
----+----+----
  3 | 33 | 33
(1 row)

-- Delete the table.
gaussdb=# DROP TABLE test;