MySQL arrange existing table columns

前端 未结 6 534
鱼传尺愫
鱼传尺愫 2021-01-30 03:35

How can I change the position of a certain existing column in MySQL table?

Ex: I want to move the column username from its current position to

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-30 04:28

    Your SQL should look like this:

    ALTER TABLE `Customers` MODIFY `UserName` INT (11) AFTER `Orders`
    

    Done! One line changes position and there's nothing else to do.


    I advise against @rahim-asgari recommendation of ALTER TABLE MYTABLE ADD MYFILED INT( 5 ) NOT NULL AFTER POSITION, since you'll to:

    1. Add a new field
    2. Copy old field's data into the new field
    3. Modify any constraints/Indexes
    4. Delete old field

    Syntax:

    ALTER TABLE `TableName` MODIFY `FieldToBeMoved` [SAME FIELD SETTINGS] [ACTION] `TargetPosition`
    
    • [SAME FIELD SETTINGS]
      Refers to the configuration of your field. TINYINT, VARCHAR, TEXT, etc. Remember to include the size. Ej. varchar (255)

    • [ACTION]
      You can move a field BEFORE or AFTER a specific field.
      Replace for BEFORE or AFTER accordingly.


    EXAMPLE

    If your...

    • Table name: Customers
    • Field to move: UserName
    • UserName settings: int(11)
    • Target Position (Last field of the table): Orders

提交回复
热议问题