SQL Inception

Marius Balčytis

SELECT CONCAT('SQL', ' ', 'Inception');

Courtesy of Sergej Veliseičik

Hello, I'm Marius Balčytis

Problem

You need to run SQL migration script

Example

idpricestatus
110.00active
212.00inactive
324.00inactive
443.00active
551.00inactive

Double the price and activate inactive products

Solution

            UPDATE prices
                SET price = price * 2, status = 'active'
                WHERE status = 'inactive';
        

Problem

Solution

Problem

Solution

            UPDATE prices SET price = price * 2, status = 'active'
    WHERE id = 2;
            UPDATE prices SET price = price * 2, status = 'active'
    WHERE id = 3;
            UPDATE prices SET price = price * 2, status = 'active'
    WHERE id = 5;
        

How?

Select needed rows, review

            SELECT *, price * 2 FROM prices WHERE status = 'inactive';
        

Select SQL statements

            SELECT CONCAT(
                    'UPDATE prices SET price = ',
                    price * 2,
                    ', status = "active" WHERE id = ', id,
                    ';'
                )
                FROM prices WHERE status = 'inactive';
        

Add backup and no-replay fail-safe

            SELECT CONCAT(
                    'UPDATE prices SET price = ',
                    price * 2,
                    ', status = "active" WHERE id = ', id,
                    ' AND status = "inactive" AND price = ', price,
                    ';'
                )
                FROM prices WHERE status = 'inactive';
        

Our data

idpricestatus
110.00active
212.00inactive
324.00inactive
443.00active
551.00inactive

Result

            UPDATE prices SET price = 24.00, status = "active"
    WHERE id = 2 AND status = "inactive" AND price = 12.00;
            UPDATE prices SET price = 48.00, status = "active"
    WHERE id = 3 AND status = "inactive" AND price = 24.00;
            UPDATE prices SET price = 102.00, status = "active"
    WHERE id = 5 AND status = "inactive" AND price = 51.00;
        

What then?

Thanks!

Questions?