ALTER TABLE without locking the table?

后端 未结 19 2112
梦毁少年i
梦毁少年i 2020-11-30 17:41

When doing an ALTER TABLE statement in MySQL, the whole table is read-locked (allowing concurrent reads, but prohibiting concurrent writes) for the duration of the statement

19条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-30 18:15

    Since you asked about other databases, here's some information about Oracle.

    Adding a NULL column to an Oracle table is a very quick operation as it only updates the data dictionary. This holds an exclusive lock on the table for a very short period of time. It will however, invalidate any depedant stored procedures, views, triggers, etc. These will get recompiled automatically.

    From there if necessary you can create index using the ONLINE clause. Again, only very short data dictionary locks. It'll read the whole table looking for things to index, but does not block anyone while doing this.

    If you need to add a foreign key, you can do this and get Oracle to trust you that the data is correct. Otherwise it needs to read the whole table and validate all the values which can be slow (create your index first).

    If you need to put a default or calculated value into every row of the new column, you'll need to run a massive update or perhaps a little utility program that populates the new data. This can be slow, especially if the rows get alot bigger and no longer fit in their blocks. Locking can be managed during this process. Since the old versino of your application, which is still running, does not know about this column you might need a sneaky trigger or to specify a default.

    From there, you can do a switcharoo on your application servers to the new version of the code and it'll keep running. Drop your sneaky trigger.

    Alternatively, you can use DBMS_REDEFINITION which is a black box designed to do this sort of thing.

    All this is so much bother to test, etc that we just have an early Sunday morning outage whenever we release a major version.

提交回复
热议问题