MySQL Cookbook Free Open Book

MySQL Cookbook

Previous Section Next Section

3.24 Moving Records Between Tables Safely

3.24.1 Problem

You're moving records by copying them from one table to another and then deleting them from the original table. But some records seem to be getting lost.

3.24.2 Solution

Be careful to delete exactly the same set of records from the source table that you copied to the destination table.

3.24.3 Discussion

Applications that copy rows from one table to another can do so with a single operation, such as INSERT ... SELECT to retrieve the relevant rows from the source table and add them to the destination table. If an application needs to move (rather than copy) rows, the procedure is a little more complicated: After copying the rows to the destination table, you must remove them from the source table. Conceptually, this is nothing more than INSERT ... SELECT followed by DELETE. In practice, the operation may require more care, because it's necessary to select exactly the same set of rows in the source table for both the INSERT and DELETE statements. If other clients insert new rows into the source table after you issue the INSERT and before you issue the DELETE, this can be tricky.

To illustrate, suppose you have an application that uses a working log table worklog into which records are entered on a continual basis, and a long-term repository log table repolog. Periodically, you move worklog records into repolog to keep the size of the working log small, and so that clients can issue possibly long-running log analysis queries on the repository without blocking processes that create new records in the working log.[3]

[3] If you use a MyISAM log table that you only insert into and never delete from or modify, you can run queries on the table without preventing other clients from inserting new log records at the end of the table.

How do you properly move records from worklog to repolog in this situation, given that worklog is subject to ongoing insert activity? The obvious (but incorrect) way is to issue an INSERT ... SELECT statement to copy all the worklog records into repolog, followed by a DELETE to remove them from worklog:

INSERT INTO repolog SELECT * FROM worklog;
DELETE FROM worklog;

This is a perfectly workable strategy when you're certain nobody else will insert any records into worklog during the time between the two statements. But if other clients insert new records in that period, they'll be deleted without ever having been copied, and you'll lose records. If the tables hold logs of web page requests, that may not be such a big deal, but if they're logs of financial transactions, you could have a serious problem.

What can you do to keep from losing records? Two possibilities are to issue both statements within a transaction, or to lock both tables while you're using them. These techniques are covered in Chapter 15. However, either one might block other clients longer than you'd prefer, because you tie up the tables for the duration of both queries. An alternative strategy is to move only those records that are older than some cutoff point. For example, if the log records have a column t containing a timestamp, you can limit the scope of the selected records to all those created before today. Then it won't matter whether new records are added to worklog between the copy and delete operations. Be sure to specify the cutoff properly, though. Here's a method that fails under some circumstances:

INSERT INTO repolog SELECT * FROM worklog WHERE t < CURDATE( );
DELETE FROM worklog WHERE t < CURDATE( );

This won't work if you happen to issue the INSERT statement at one second before midnight and the SELECT statement one second later. The value of CURDATE( ) will differ for the two statements, and the DELETE operation may remove too many records. If you're going to use a cutoff, make sure it has a fixed value, not one that may change between statements. For example, a SQL variable can be used to save the value of CURDATE( ) in a form that won't change as time passes:

SET @cutoff = CURDATE( );
INSERT INTO repolog SELECT * FROM worklog WHERE t < @cutoff;
DELETE FROM worklog WHERE t < @cutoff;

This ensures that both statements use the same cutoff value so that the DELETE operation doesn't remove records that it shouldn't.

    Previous Section Next Section
    Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Y][Z]


         Main Menu
    Main Page
    Table of content
    Copyright
    Preface
    Chapter 1. Using the mysql Client Program
    Chapter 2. Writing MySQL-Based Programs
    Chapter 3. Record Selection Techniques
    3.1 Introduction
    3.2 Specifying Which Columns to Display
    3.3 Avoiding Output Column Order Problems When Writing Programs
    3.4 Giving Names to Output Columns
    3.5 Using Column Aliases to Make Programs Easier to Write
    3.6 Combining Columns to Construct Composite Values
    3.7 Specifying Which Rows to Select
    3.8 WHERE Clauses and Column Aliases
    3.9 Displaying Comparisons to Find Out How Something Works
    3.10 Reversing or Negating Query Conditions
    3.11 Removing Duplicate Rows
    3.12 Working with NULL Values
    3.13 Negating a Condition on a Column That Contains NULL Values
    3.14 Writing Comparisons Involving NULL in Programs
    3.15 Mapping NULL Values to Other Values for Display
    3.16 Sorting a Result Set
    3.17 Selecting Records from the Beginning or End of a Result Set
    3.18 Pulling a Section from the Middle of a Result Set
    3.19 Choosing Appropriate LIMIT Values
    3.20 Calculating LIMIT Values from Expressions
    3.21 What to Do When LIMIT Requires the 'Wrong' Sort Order
    3.22 Selecting a Result Set into an Existing Table
    3.23 Creating a Destination Table on the Fly from a Result Set
    3.24 Moving Records Between Tables Safely
    3.25 Creating Temporary Tables
    3.26 Cloning a Table Exactly
    3.27 Generating Unique Table Names
    Chapter 4. Working with Strings
    Chapter 5. Working with Dates and Times
    Chapter 6. Sorting Query Results
    Chapter 7. Generating Summaries
    Chapter 8. Modifying Tables with ALTER TABLE
    Chapter 9. Obtaining and Using Metadata
    Chapter 10. Importing and Exporting Data
    Chapter 11. Generating and Using Sequences
    Chapter 12. Using Multiple Tables
    Chapter 13. Statistical Techniques
    Chapter 14. Handling Duplicates
    Chapter 15. Performing Transactions
    Chapter 16. Introduction to MySQL on the Web
    Chapter 17. Incorporating Query Resultsinto Web Pages
    Chapter 18. Processing Web Input with MySQL
    Chapter 19. Using MySQL-Based Web Session Management
    Appendix A. Obtaining MySQL Software
    Appendix B. JSP and Tomcat Primer
    Appendix C. References
    Colophone
    Index


    More Books
    PHP Hacks
    Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
    The Koran (Holy Qur'an)
    Macromedia Flash 8 Bible
    Search Engine Optimization for Dummies
    YouTube Traffic
    PHP 5 for Dummies
    Harry Potter and The Chamber of Secrets
    Harry Potter and the Sorcerer's Stone
    The Pilgrim's Progress
    Wireless Hacks
    Flash Hacks. 100 Industrial-Strength Tips & Tools
    PayPal Hacks. 100 Industrial-Strength Tips and Tools
    Amazon Hacks
    Pdf Hacks
    The Da Vinci Code
    Google Hacks
    The Holy Bible
    Windows XP For Dummies
    Harry Potter and the Half-Blood Prince
    Seo Book
    Upgrading and Repairing Networks
    Macromedia Dreamweaver 8 UNLEASHED
    Windows XP Annoyances
    Windows XP Hacks
    Microsoft Windows XP Power Toolkit
    Teach Yourself MS Office In 24Hours
    iPod & iTunes Missing Manual
    PC Hacks 100 Industrial-Strength Tips and Tools
    PC Overclocking, Optimization, and Tuning - 2th Edition
    PC Hardware In A Nutshell 3rd Edition
    PC Hardware in a Nutshell, 2nd Edition
    Upgrading and Repairing PCs
    Google for Dummies
    MySQL Cookbook
    Teach Yourself Macromedia Flash 8 In 24 Hours
    PHP CookBook
    Sams Teach Yourself JavaScript in 24 Hours
    PHP5 Manual
    Free Games Paper Airplanes
    500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele