Does INSERT INTO … SELECT … always match fields by ordinal position?

前端 未结 3 592
太阳男子
太阳男子 2021-02-18 16:16

My tests seem to confirm that

INSERT INTO a (x, y) SELECT y, x FROM b

maps b.y to a.x, i.e., the fields are matched o

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-18 16:48

    Yes, you are correct.

    The order of the fields in the INSERT INTO statement does not need to match the table definition.

    But the alias/field names of the SELECT will be ignored, and the values inserted into the fields named by the INSERT INTO statement.

    CREATE TABLE test (
      a      AS INT,
      b      AS INT,
      c      AS INT
    )
    INSERT INTO
      test (
        b,
        c,
        a
      )
    SELECT
      1 AS a,
      2 AS b,
      3 AS c
    
    SELECT * FROM test
    
     a | b | c
    ---+---+---
     3 | 1 | 2
    

提交回复
热议问题