HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlCritical

How do I swap tables in MySQL?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
tablesswapmysqlhow

Problem

Suppose, I have a table foo, which contains some statistics that are computed every now and then. It is heavily used by other queries.

That's why I want to compute more recent statistics in foo_new and swap them when computation is ready.

I could do

ALTER TABLE foo RENAME foo_tmp;
ALTER TABLE foo_new RENAME foo;


but what happens if a query needs table foo inbetween those two lines when there is no table foo? I guess I have to lock it somehow... or is there another way to do it?

Solution

Use this one command:

RENAME TABLE foo TO foo_old, foo_new To foo;


It is an atomic operation: both tables are locked together (and for a very short time), so any access occurs either before or after the RENAME.

Code Snippets

RENAME TABLE foo TO foo_old, foo_new To foo;

Context

StackExchange Database Administrators Q#22108, answer score: 115

Revisions (0)

No revisions yet.