Assuming you are using a transaction mechanism (usually Innodb), clear and add the table to the same transaction.
Make sure your readers use READ_COMMITTED or a higher level of transaction isolation (the default is REPEATABLE READ, which is higher).
In this way, readers will continue to read the old contents of the table during the update.
There are a few things to keep in mind:
- If the table is so large that it has exhausted the rollback area, this is possible if you update the entire (say) 1M row table. Of course, this is customizable, but there are limitations.
- If the transaction failed and rolls back - rollback of large transactions is VERY inefficient in InnoDB (it is optimized for commit, not rollback).
- Be careful with locks and block waiting expectations, which are more likely if you use large transactions.
Markr source share