Docsity

MySQL UNION Statement and Transactions: Combining Queries and Maintaining Data Integrity, Papers of Database Management Systems (DBMS)

Partial preview of the text

Download MySQL UNION Statement and Transactions: Combining Queries and Maintaining Data Integrity and more Papers Database Management Systems (DBMS) in PDF only on Docsity!

Managing Data

in MySQL

Performing Multiple-Table Retrievals

with UNION

If you want to create a result set that combines the results from several

queries, you can do so by using a UNION statement

SELECT i FROM t1 UNION SELECT i FROM t2 UNION SELECT i FROM t3;

Be reminded that the number of selected column must match to the

number of column selected from all of the table. In case of the query above,

we have selected the column i from table t1, t2, and t3. After the selection,

we have used the UNION to put them in a single result table

Performing Multiple-Table Retrievals

with UNION

Property of Union

  • Duplicate-row handling.
    • By default, UNION eliminates duplicate rows from the result set
    • UNION DISTINCT is synonymous with UNION ;both retain only

distinct rows.

  • If you want to preserve duplicates, change each UNION to UNION ALL
  • If you mix UNION or UNION DISTINCT with UNION ALL ,any distinct

union operation takes precedence over any UNION ALL operations to

its left.

Performing Multiple-Table Retrievals

with UNION

Property of Union

  • ORDER BY and LIMIT handling.
    • To sort a UNION result as a whole, place each SELECT within

parentheses and add an ORDER BY clause following the last one.

However, because the UNION uses column names from the first

SELECT, the ORDER BY should refer to those names, not the column

names from the last SELECT

(SELECT i, c FROM t1) UNION (SELECT i, d FROM t3)

ORDER BY c;

Performing Multiple-Table Retrievals

with UNION

Property of Union

  • ORDER BY and LIMIT handling.
    • ORDER BY and LIMIT also can be used within a parenthesized

individual SELECT of a UNION to apply only to that SELECT :

(SELECT * FROM t1 ORDER BY i LIMIT 2)

UNION (SELECT * FROM t2 ORDER BY i LIMIT 1)

UNION (SELECT * FROM t3 ORDER BY d LIMIT 2);

Performing Multiple-Table Retrievals

with UNION

Property of Union

  • ORDER BY and LIMIT handling.
    • ORDER BY within an individual SELECT is used only if LIMIT is also

present, to deter mine which rows the LIMIT applies to. It does not

affect the order in which rows appear in the final UNION result

Using Views

  • Create a view for SELECT query that you always use through out your application - Sample usage: - Creation CREATE VIEW vpres AS SELECT last_name, first_name, city, state FROM president; - Retrieval - SELECT * FROM vpres; - SELECT * FROM vpres WHERE last_name = 'Adams'; ‘with condition

Multiple-Table Deletes and Updates

  • To write a multiple-table DELETE ,name all the tables in a FROM clause and specify the conditions used to match rows in the tables in the WHERE clause. - Sample - DELETE col1 FROM t1 INNER JOIN t2 ON t1.id = t2.id; - DELETE t1.col1, t2.col1 FROM t1 INNER JOIN t2 ON t1.id = t2.id; ‘to avoid ambiguity - SELECT t1.* FROM t1 LEFT JOIN t2 ON t1.id = t2.id WHERE t2.id IS NULL; ‘deletion of non-matching row - DELETE FROM t1 USING t1 INNER JOIN t2 ON t1.id = t2.id; - DELETE FROM t1, t2 USING t1 INNER JOIN t2 ON t1.id = t2.id; - DELETE FROM t1 USING t1 LEFT JOIN t2 ON t1.id = t2.id WHERE t2.id IS NULL;

Performing Transactions

  • A transaction is a set of SQL statements that execute as a unit and that can be canceled if necessary.
  • Either all the statements execute successfully, or none of them have any effect. This is achieved through the use of commit and rollback capabilities.
  • If all of the statements in the transaction succeed, you commit it to record their effects permanently in the database.
  • If an error occurs during the transaction, you roll it back to cancel it.
  • Any statements executed up to that point within the transaction are undone, leaving the database in the state it was in prior to the point at which the transaction began.
  • Commit and rollback provide the means for ensuring that halfway-done operations don’t make their way into your database and leave it in a partially updated (inconsistent) state.

Performing Transactions

  • The rollback capabilities of transaction support enable you to handle a database crash situation properly by undoing the effect of the statements that executed before the error occurred
  • Transactions make sure that the rows involved in an operation are not modified by other clients while you’re working with them. - MySQL automatically performs locking for single SQL statements to keep clients from interfering with each other,but this is not always sufficient to guarantee that a database operation achieves its intended result, because some operations are performed over the course of several statements.
  • A transaction group statements into a single execution unit to prevent concurrency problems that could otherwise occur in a multiple-client environment.
  • Transactional processing provides stronger guarantees about the outcome of database operations, but also requires more overhead in CPU cycles, memory, and disk space.

Performing Transactions

  • Using Transactions to Ensure Safe Statement Execution
    • To use transactions, you must use a transactional storage engine such as InnoDB or Falcon. Engines such as MyISAM and MEMORY will not work.
    • By default, MySQL runs in autocommit mode, which means that changes made by individual statements are committed to the database immediately to make them permanent.
    • One way to perform a transaction is to issue a START TRANSACTION (or BEGIN ) statement to suspend autocommit mode, execute the statements that make up the transaction, and end the transaction with a COMMIT statement to make the changes permanent.
    • If an error occurs during the transaction, cancel it by issuing a ROLLBACK statement instead to undo the changes. START TRANSACTION suspends the current autocommit mode, so after the transaction has been committed or rolled back, the mode reverts to its state prior to the START TRANSACTION .(If autocommit was enabled beforehand,ending the transaction puts you back in autocommit mode.If it was disabled,ending the current transaction causes you to begin the next one.)

Performing Transactions

  • Using Transactions to Ensure Safe Statement Execution
    • Sample Usage mysql> CREATE TABLE t (name CHAR(20), UNIQUE (name)) ENGINE = InnoDB; mysql> START TRANSACTION; mysql> INSERT INTO t SET name = 'William'; mysql> INSERT INTO t SET name = 'Wallace'; mysql> COMMIT; mysql> SELECT * FROM t; With rollback mysql> START TRANSACTION; mysql> INSERT INTO t SET name = 'Gromit'; mysql> INSERT INTO t SET name = 'Wallace'; ERROR 1062 (23000): Duplicate entry 'Wallace' for key 1 mysql> ROLLBACK; mysql> SELECT * FROM t; Nothing will change in the database because there is an error

Performing Transactions

  • Transaction Isolation
    • InnoDB implements transaction isolation levels to give clients control over what kind of changes made by other transactions they want to see.Different isolation levels allow or prevent the various problems that can occur when different transactions run simultaneously: - Dirty reads .A dirty read occurs when a change made by one transaction can be seen by other transactions before the transaction has been committed. Another transaction thus might think the row has been changed ,even though that will not really be true if the transaction that changed the row later is rolled back. - Nonrepeatable reads. A nonrepeatable read refers to the failure by a transaction to get the same result for a given SELECT statement each time it executes it.This might happen if one transaction performs a SELECT twice but another transaction changes some of the rows in between the two executions. - Phantom rows. A phantom is a row that becomes visible to a transaction when it was not previously. Suppose that a transaction performs a SELECT and then another transaction inserts a row.If the first transaction runs the same SELECT again and sees the new row, that is a phantom.

Performing Transactions

  • Transaction Isolation
    • To deal with these problems, InnoDB supports four transaction isolation levels. These levels determine which modifications made by one transaction can be seen by other transactions that execute at the same time: - READ UNCOMMITTED A transaction can see row modifications made by other transactions even before they have been committed. - READ COMMITTED , A transaction can see row modifications made by other transactions only if they have been committed. - REPEATABLE READ, If a transaction performs a given SELECT twice, the result is repeatable. That is, it gets the same result each time, even if other transactions have changed or inserted rows in the meantime. - SERIALIZABLE , This isolation level is similar to REPEATABLE READ but isolates transactions more completely: Rows examined by one transaction cannot be modified by other transactions until the first transaction completes. This enables one transaction to read rows and at the same time prevent them from being modified by other transactions until it is done with them.