manual ok bd

Upload: javierutebo

Post on 06-Oct-2015

237 views

Category:

Documents


0 download

DESCRIPTION

datos

TRANSCRIPT

Home/Basic MySQL Tutorial/ MySQL Temporary TableMySQL Temporary TableSummary: in this tutorial, we will discuss aboutMySQL temporary tableand show you how to create, use and drop temporary tables.Introduction to MySQL temporary tableIn MySQL, a temporary table is a special type of table that allows you to store a temporary result set, which you can reuse several times in a single session. A temporary table is very handy when it is impossible or expensive to query data that requires a singleSELECT statementwithJOINclauses. You often use temporary tables instored proceduresto store immediate result sets for the subsequent uses.MySQL temporary tables have some additional features: A temporary table is created by usingCREATE TEMPORARY TABLEstatement. Notice that theTEMPORARYkeyword is added betweenCREATEandTABLEkeywords. MySQL drops the temporary table automatically when the session ends or connection is terminated. Of course, you can use theDROP TABLEstatement to drop a temporary table explicitly when you are no longer use it. A temporary table is only available and accessible by the client who creates the table. Different clients can create a temporary table with the same name without causing errors because only the client who creates a temporary table can see it. However, in the same session, two temporary tables cannot have the same name. A temporary table can have the same name as an existing table in a database. For example, if you create a temporary table namedemployeesin thesample database, the existingemployeestable becomes inaccessible. Every query you issue against theemployeestable refers to theemployeestemporary table. When you remove theemployeestemporary table, the permanentemployeestable is available and accessible again. Though this is allowed however it is not recommended to create a temporary table whose name is same as a name of a permanent table because it may lead to a confusion. For example, in case the connection to the MySQL database server is lost and you reconnect to the server automatically, you cannot differentiate between the temporary table and the permanent table. In the worst case, you may issue aDROP TABLEstatement to remove the permanent table instead of the temporary table, which is not expected.Create MySQL temporary tableLike theCREATE TABLE statement, MySQL provides many options to create a temporary table. To create a temporary table, you just add theTEMPORARYkeyword to theCREATE TABLEstatement.For example, the following statement creates a top 10 customers by revenue temporary table based on the result set of aSELECTstatement:123456789CREATE TEMPORARY TABLE top10customersSELECT p.customerNumber, c.customerName, FORMAT(SUM(p.amount),2) totalFROM payments pINNER JOIN customers c ON c.customerNumber = p.customerNumberGROUP BY p.customerNumberORDER BY total DESCLIMIT 10

Now, you can query data from thetop10customerstemporary table as from a permanent table:1SELECT * FROM top10customers

Drop MySQL temporary tableYou can use theDROP TABLE statementto remove temporary tables however it is good practice to use theDROP TEMPORARY TABLEstatement instead. Because theDROP TEMPORARY TABLEremoves only temporary tables, not the permanent tables. In addition, theDROP TEMPORARY TABLEstatement helps you avoid the mistake of removing a permanent table when you name your temporary table the same as the name of the permanent table.For example, to remove thetop10customerstemporary table, you use the following statement:1DROP TEMPORARY TABLE top10customers

Notice that if you try to remove a permanent table with theDROP TEMPORARY TABLEstatement, you will get an error message saying that the table you are trying drop is unknown.Note if you develop an application that uses a connection pooling or persistent connections, it is not guaranteed that the temporary tables are removed automatically when your application is terminated. Because the database connection that the application used may be still open and is placed in a connection pool for other clients to reuse it. This means you should always remove the temporary tables that you created whenever you are done with them.In this tutorial, you have learned about MySQL temporary table and its characteristic. We also gave you an example of how to create, use and drop a temporary table.

Home/Basic MySQL Tutorial/ MySQL Managing Database IndexMySQL Managing Database IndexSummary: in this tutorial, you will learn how to work withMySQL indexand how to take advantages of the index to speed up the dataretrieval. We will introduce you several useful statements that allows you to manage MySQL indexes.Database index, or just index, helps speed up the retrieval of data from tables. When you query data from a table, first MySQL checks if the indexes exist, then MySQL uses the indexes to select exact physical corresponding rows of the table instead of scanning the whole table.A database index is similar to an index of a book. If you want to find a topic, you look up in the index first, and then you open the page that has the topic without scanning the whole book.It is highly recommended that you should create index on columns of table from which you often query the data. Notice that all primary key columns are in the primary index of the table automatically.If index helps speed up the querying data, why dont we use indexes for all columns? If you create an index for every column, MySQL has to build and maintain the index table. Whenever a change is made to the records of the table, MySQL has to rebuild the index, which takes time as well as decreases the performance of the database server.Creating MySQL IndexYou often create indexes when you create tables. MySQL automatically add any column that is declared asPRIMARY KEY,KEY,UNIQUEorINDEXto the index. In addition, you can add indexes to the tables that already have data.In order to create indexes, you use theCREATE INDEXstatement. The following illustrates the syntax of theCREATE INDEXstatement:123CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_nameUSING [BTREE | HASH | RTREE] ON table_name (column_name [(length)] [ASC | DESC],...)

First, you specify the index based on the table type or storage engine: UNIQUEmeans MySQL will create a constraint that all values in the index must be unique. Duplicate NULL value is allowed in all storage engine except BDB. FULLTEXTindex is supported only by MyISAM storage engine and only accepted on column that has data type isCHAR,VARCHARorTEXT. SPATIALindex supports spatial column and is available on MyISAM storage engine. In addition, the column value must not be NULL.Then, you name the index and its type after the USING keyword such asBTREE,HASHorRTREEalso based on the storage engine of the table.Here are the storage engines of the table with the corresponding allowed index types:Storage EngineAllowable Index Types

MyISAMBTREE, RTREE

InnoDBBTREE

MEMORY/HEAPHASH, BTREE

NDBHASH

Third, you declare table name and a list columns that you want to add to the index.Example of creating index in MySQLIn thesample database, you can addofficeCodecolumn of theemployeestable to the index by using theCREATE INDEXstatement as follows:1CREATE INDEX officeCode ON employees(officeCode)

Removing IndexesBesides creating index, you can also remove index by using theDROP INDEXstatement. Interestingly, theDROP INDEXstatement is also mapped toALTER TABLE statement. The following is the syntax of removing the index:1DROP INDEX index_name ON table_name

For example, if you want to drop indexofficeCodeof theemployeestable,which we have created above, you can execute following query:1DROP INDEX officeCode ON employees

In this tutorial, youve learned about indexes and how to manage MySQL index including creating and removing indexes.

Home/Basic MySQL Tutorial/ How to Use MySQL DISTINCT to Eliminate Duplicate RowsHow to Use MySQL DISTINCT to Eliminate Duplicate RowsSummary: in this tutorial, you will learn how to useMySQL DISTINCToperatorwith theSELECTstatement to eliminate duplicate rows in the result set.When querying data from a table, you may get duplicate rows. In order to remove the duplicate rows, you use theDISTINCToperator in theSELECT statement. The syntax of using theDISTINCToperatoris as follows:123SELECT DISTINCT columnsFROM table_nameWHERE where_conditions

Lets take a look a simple example of using theDISTINCT operatorto select the distinct last names of employees from theemployeestable.First, we query the last names of employees from theemployeestable using theSELECTstatement as follows:123SELECT lastnameFROM employeesORDER BY lastname

Some employees has the same last name Bondur,Firrelli, etc. To remove the duplicate last names, you use theDISTINCToperator in theSELECTclause as follows:123SELECT DISTINCT lastnameFROM employeesORDER BY lastname

The duplicate last names are eliminated in the result set when we use theDISTINCToperator.MySQL DISTINCT and NULL valuesIf a column hasNULLvalues and you use theDISTINCToperator for that column, MySQL will keep oneNULLvalue and eliminate the other because theDISTINCToperator treats allNULLvalues as the same value.For example, in thecustomerstable, we have many rows with state column hasNULLvalues. When we use theDISTINCToperator to query states of customers, we will see distinct states plus a NULL value as the following query:12SELECT DISTINCT stateFROM customers

MySQL DISTINCT with multiple columnsYou can use theDISTINCToperator with more than one column. The combination of all columns will be used to define the uniqueness of the row in the result set.For example, to get the unique combination of city and state from thecustomerstable, you use the following query:1234SELECT DISTINCT state, cityFROM customersWHERE state IS NOT NULLORDER BY state, city

Without theDISTINCToperator, you will get duplicate combination state and city as follows:1234SELECT state, cityFROM customersWHERE state IS NOT NULLORDER BY state, city

DISTINCT vs. GROUP BY ClauseIf you use theGROUP BY clausein theSELECTstatement without usingaggregate functions, theGROUP BYclause will behave like theDISTINCToperator. The following queries produce the same result set:123456SELECT DISTINCT stateFROM customers;SELECT stateFROM customersGROUP BY state;

The difference betweenDISTINCToperator andGROUP BYclause is that theGROUP BYclause sorts the result set whereas theDISTINCToperator does not.MySQL DISTINCT and COUNT aggregate functionTheDISTINCToperator is used with theCOUNTfunction to count unique records in a table. In this case, it ignores theNULLvalues. For example, to count the unique states of customers in the U.S., you use the following query:123SELECT COUNT(DISTINCT state)FROM customersWHERE country = 'USA';

In this tutorial, we have shown you various ways of using MySQLDISTINCToperator such as eliminating duplicate records and counting non-NULL values.

Home/Basic MySQL Tutorial/ Using MySQL LIMITUsing MySQL LIMITSummary:in this tutorial, you will learn how to useMySQL LIMITclause to select records from the beginning, middle and end of a result set.MySQL LIMIT syntaxTheLIMITclause is used in theSELECT statementto constrain the number of rows in a result set. TheLIMITclause accepts one or two arguments. The values of both arguments must be zero or positive integer constants.The following illustrates the LIMIT clause syntax with 2 arguments:12SELECT * FROM tblLIMIT offset, count

Lets see what theoffsetandcountmean in the LIMIT clause: Theoffsetspecifies the offset of the first row to return. Theoffsetof the first row is 0, not 1. Thecountspecifies maximum number of rows to return.When you useLIMITwith one argument, this argument will be used to specifies the maximum number of rows to return from the beginning of the result set.12SELECT * FROM tblLIMIT count

The query above is equivalent to the following query with theLIMITclause that accepts two arguments:12SELECT * FROM tblLIMIT 0, count

Using MySQL LIMIT to get the first N rowsYou can use theLIMITclause to select the firstNrows in a table as follows:12SELECT * FROM tblLIMIT N

For example, to select the first 10 customers, you use the following query:12345SELECT customernumber, customername, creditlimitFROM customersLIMIT 10;

Using MySQL LIMIT to get the highest and lowest valuesTheLIMITclause often used withORDER BY clause. First, you use theORDER BYclause to sort the result set based on a certain criteria, and then you useLIMITclause to find lowest or highest values.For example, to select 5 customers who have the highest credit limit, you use the following query:123456SELECT customernumber, customername, creditlimitFROM customersORDER BY creditlimit DESCLIMIT 5;

And the following query returns 5 customers who have the lowest credit limit:123456SELECT customernumber, customername, creditlimitFROM customersORDER BY creditlimit ASCLIMIT 5;

Using MySQL LIMIT to get the N highest valuesOne of the toughest questions in MySQL is how to select the N highest values in a result set e.g., select the second most expensive product, which you cannot useMAX or MIN functionsto answer. However, you can use MySQL LIMIT to answer those kinds of questions.Lets take a look at the products result set of the following query:1234SELECT productName, buypriceFROM productsORDER BY buyprice DESC;

Our task is to get the highlight product, which is the second most expensive product in the products result set. In order to do so, you useLIMITclause to select 1 row from the second row as the following query: (notice that the offset starts from zero)12345SELECT productName, buypriceFROM productsORDER BY buyprice DESCLIMIT 1, 1

In this tutorial, you have learned how to use MySQL LIMIT clause to select records from thebeginning, the middle and the end of a result set.

Home/Basic MySQL Tutorial/ Using MySQL LIKE Operator to Select Data Based On PatternsUsing MySQL LIKE Operator to Select Data Based On PatternsSummary:in this tutorial, you will learn how to useMySQL LIKEoperator to select data based on patterns.TheLIKEoperator is commonly used to select data based on patterns. Using theLIKEoperatorin appropriate way is essential to increase the query performance.TheLIKEoperator allows you to select data from a table based on a specified pattern. Therefore theLIKEoperator is often used in theWHERE clauseof theSELECT statement.MySQL provides two wildcard characters for using with theLIKEoperator, the percentage%and underscore_. The percentage (%) wildcard allows you to match any string of zero or more characters. The underscore (_) wildcard allows you to match any single character.MySQL LIKE examplesLets practice with some examples of how to use theLIKEoperator.MySQL LIKE with percentage (%) wildcardSuppose you want to search for employee whose first name starts with character a, you can use the percentage wildcard (%) at the end of the pattern as follows:123SELECT employeeNumber, lastName, firstNameFROM employeesWHERE firstName LIKE 'a%'

MySQL scans the wholeemployeestable to find employee whose first name starts with character a and followed by any number of characters.To search for employee whose last name ends with on string e.g.,Patterson,Thompson, you can use the%wildcard at the beginning of the pattern as the following query:123SELECT employeeNumber, lastName, firstNameFROM employeesWHERE lastName LIKE '%on'

If you know the searched string is embedded inside in the column, you can use the percentage (%) wildcard at the beginning and the end of the pattern. For example, to find all employees whose last names contain on string, you can execute following query:123SELECT employeeNumber, lastName, firstNameFROM employeesWHERE lastname LIKE '%on%'

MySQL LIKE with underscore(_) wildcardTo find employee whose first name starts withT, ends withmand contains any single character between e.g.,Tom,Tim, you use the underscore wildcard to construct the pattern as follows:123SELECT employeeNumber, lastName, firstNameFROM employeesWHERE firstname LIKE 'T_m'

MySQL LIKE operator with NOT operatorThe MySQL allows you to combine theNOToperator with theLIKEoperator to find string that does not match a specific pattern.Suppose you want to search for employee whose last name does not start with character B, you can use the NOT LIKE with the pattern as the following query:123SELECT employeeNumber, lastName, firstNameFROM employeesWHERE lastName NOT LIKE 'B%'

Notice that the pattern is not case sensitive with theLIKEoperator therefore the b% and B% patterns produce the same result.MySQL LIKE with ESCAPE clauseSometimes the pattern, which you want to match, contains wildcard character e.g., 10%, _20 etc. In this case, you can use the ESCAPE clause to specify the escape character so that MySQL interprets the wildcard character as literal character. If you dont specify the escape character explicitly, the backslash character \ is the default escape character.For example, if you want to find product whose product code contains string_20, you can perform following query:123SELECT productCode, productNameFROM productsWHERE productCode LIKE '%\_20%'

Or specify a different escape character e.g., $ by using theESCAPEclause:123SELECT productCode, productNameFROM productsWHERE productCode LIKE '%$_20%' ESCAPE '$'

The pattern %$_20% matches any string that contains _20 string.TheLIKEoperator forces MySQL to scan the whole table to find the matching rows therefore it does not allow the database engine to useindexfor fast searching. As the result, the performance of the query that uses theLIKEoperator degrades when you query data from a table with a large number of rows.In this tutorial, you have learned how to use theLIKEoperator to query data based on patterns, which is more flexible than using comparison operators.

Home/Basic MySQL Tutorial/ Combining Result Sets by Using MySQL UNIONCombining Result Sets by Using MySQL UNIONSummary:in this tutorial, you will learn how to useMySQL UNIONoperator to combine two or more result sets from multipleSELECTstatements into a single result set.MySQL UNION OperatorMySQLUNIONoperator allows you to combine two or more result sets from multiple tables into a single result set. The syntax of the MySQL UNION is as follows:123456SELECT column1, column2UNION [DISTINCT | ALL]SELECT column1, column2UNION [DISTINCT | ALL]

There are some rules that you need to follow in order to use the UNION operator: The number of columns appears in the correspondingSELECT statementsmust be equal. The columns appear in the corresponding positions of eachSELECTstatement must have the samedata typeor at least convertible data type.By default, theUNIONoperator eliminates duplicate rows from the result even if you dont useDISTINCToperator explicitly. Therefore it is said thatUNIONclause is the shortcut ofUNION DISTINCT.If you use theUNION ALLexplicitly, the duplicate rows, if available, remain in the result. TheUNION ALLperforms faster than theUNION DISTINCT.MySQL UNION exampleLets practice with an example of using MySQLUNIONto get a better understanding.Suppose you want to combine data from thecustomersandemployeestables into a single result set, you canUNIONoperator as the following query:12345SELECT customerNumber id, contactLastname nameFROM customersUNIONSELECT employeeNumber id,firstname nameFROM employees

Here is the output:

MySQL UNION without AliasIn the example above, we used thecolumn aliasfor each column in theSELECTstatements. What would be the output if we didnt use the column alias? MySQL uses the names of columns in the firstSELECTstatement as the labels for the output.Lets try the query that combinescustomersandemployeesinformation without using column alias:123456(SELECT customerNumber, contactLastnameFROM customers)UNION(SELECT employeeNumber, firstnameFROM employees)ORDER BY contactLastname, customerNumber

The result hascustomerNumberandcontactLastnameas the label,which are the names of columns in the firstSELECTstatement.

MySQL UNION with ORDER BYIf you want to sort the results returned from the query using theUNIONoperator, you need to useORDER BY clausein the last SQLSELECTstatement. You can put eachSELECTstatement in theparentheses and use theORDER BYclause as the last statement.Lets take a look at the following example:123456(SELECT customerNumber id,contactLastname nameFROM customers)UNION(SELECT employeeNumber id,firstname nameFROM employees)ORDER BY name,id

In the query above, first we combineidandnameof bothemployeesandcustomersinto one result set using theUNIONoperator. Then we sort the result set by using theORDER BYclause. Notice that we put theSELECTstatements inside the parentheses and place theORDER BYclause as the last statement.If you place theORDER BYclause in eachSELECTstatement, it will not affect the order of the rows in the final result produced by theUNIONoperator.MySQL also provides you with alternative option to sort the result set based on column position usingORDER BYclause as the following query:123456(SELECT customerNumber, contactLastnameFROM customers)UNION(SELECT employeeNumber,firstnameFROM employees)ORDER BY 2, 1

In this tutorial, you have learned how to use MySQL UNION statement to combine data from multiple tables into a single result set.

Home/Basic MySQL Tutorial/ MySQL INNER JOINMySQL INNER JOINSummary:in this tutorial, you will learn how to useMySQL INNER JOINclause to select data from multiple tables based on join conditions.Introducing MySQL INNER JOIN clauseThe MySQL INNER JOIN clause matches rows in one table with rows in other tables and allows you to query rows that contain columns from both tables.The MySQL INNER JOIN clause an optional part of theSELECT statement. It appears immediately after theFROMclause.Before using MySQL INNER JOIN clause, you have to specify the following criteria: First, you have to specify the main table that appears in theFROMclause. Second, you need to specify the table that you want to join with the main table, which appears in theINNER JOINclause. Theoretically, you can join a table with many tables. However, for better query performance, you should limit the number of tables to join. Third, you need to specify the join condition or join predicate. The join condition appears after the keywordONof theINNER JOINclause. The join condition is the rule for matching rows between the main table and the other tables.The syntax of the MySQL INNER JOIN clause is as follows:123456SELECT column_listFROM t1INNER JOIN t2 ON join_condition1INNER JOIN t3 ON join_condition2...WHERE where_conditions;

Lets simplify the syntax above by assuming that we are joining two tablesT1andT2using theINNER JOINclause.For each record in theT1table, the MySQL INNER JOIN clause compares it with each record of theT2tableto check if both of them satisfy the join condition. When the join condition is matched, it will return that record that combine columns in either or bothT1andT2tables.Notice that the records on bothT1andT2tableshave to be matched based on the join condition. If no match found, the query will return an empty result set.The logic is applied if we join more than 2 tables.The following Venn diagram illustrates how the MySQL INNER JOIN clause works.

MySQL INNER JOIN Venn DiagramAvoid ambiguous column error in MySQL INNER JOINIf you join multiple tables that have the same column name, you have to use table qualifier to refer to that column in theSELECTclause to avoid ambiguous column error. For example, if both T1andT2tableshave the same column namedC;in theSELECTclause, you have to refer toCcolumn using the table qualifiers asT1.CorT2.C.To save time typing the table qualifiers, you can usetable aliasesin the query. For example, you can give theverylongtablenametable an aliasTand refer to its columns usingT.columninstead ofverylongtablename.column.Examples of using MySQL INNER JOIN clauseLets take a look at two tables:productsandproductlinestables in thesample database.

Now, if you want to get Theproduct codeandproduct namefrom theproductstable. Thetext descriptionof product lines from theproductlinestable.You need to select data from both tables and match rows by comparing theproductlinecolumn from theproductstable with theproductlinecolumn from theproductlinestable as the following query:12345SELECT productCode, productName, textDescriptionFROM products T1INNER JOIN productlines T2 ON T1.productline = T2.productline;

MySQL INNER JOIN with GROUP BY clauseWe can get the order number, order status and total sales from theordersandorderdetailstables using theINNER JOINclause with theGROUP BY clauseas follows:123456SELECT T1.orderNumber, status, SUM(quantityOrdered * priceEach) totalFROM orders AS T1INNER JOIN orderdetails AS T2 ON T1.orderNumber = T2.orderNumberGROUP BY orderNumber

In this tutorial, you have learned how to use MySQL INNER JOIN to query data from multiple tables. You have also learned how to use table qualifier to avoid ambiguous column error in MySQL INNER JOIN clause.

Home/Basic MySQL Tutorial/ MySQL LEFT JOINMySQL LEFT JOINSummary: in this tutorial, you will learn aboutMySQL LEFT JOINclause and how to apply it to query data from two or more database tables.Introducing to MySQL LEFT JOINThe MySQL LEFT JOIN clause allows you to query data from two or more database tables. TheLEFT JOINclause is an optional part of theSELECT statement, which appears after theFROMclause.Lets assume that we are going to query data from two tablesT1andT2. The following is the syntax of theLEFT JOINclause that joins the two tables:123SELECT T1.c1, T1.c2,... T2.c1,T2.c2FROM T1LEFT JOIN T2 ON T1.c1 = T2.c1...

When we join theT1table to theT2table using theLEFT JOINclause, if a row from the left tableT1matches a row from the right tableT2based on the join condition (T1.c1 = T2.c1), this row is included in the result set. In case the row in the left table does not match the row in the right table, the row in the left table is also selected and combined with a fake row from the right table. The fake row containsNULLvalues for all corresponding columns in theSELECTclause.In other words, theLEFT JOINclause allows you to select rows from the both left and right tables that match, plus all rows from the left table (T1) even there is no match found for them in the right table (T2).The following Venn diagram helps you visualize how the MySQL LEFT JOIN clause works. The intersection between two circles are rows that match in both tables, and the remaining part of the leftcircle are rows in theT1table that do not have matches in theT2table. All rows in the left table are included in the result set.

MySQL LEFT JOIN Venn DiagramNotice that the returned rows must also match the condition in theWHEREandHAVINGclauses if those clauses are available in the query.MySQL LEFT JOIN ExamplesMySQL LEFT JOIN clause joining 2 tables exampleLets take a look at thecustomersandorderstables.

In the database diagram above: Each order in theorderstable must belong to a customer in thecustomerstable. Each customer in thecustomerstable can have zero or more orders in theorderstable.TO find all orders that belong to each customer, you can use theLEFT JOINclause as follows:123456SELECT c.customerNumber, c.customerName, orderNumber, o.statusFROM customers cLEFT JOIN orders o ON c.customerNumber = o.customerNumber

The left table is thecustomerstherefore all customers are included in the result set. However, there are rows in the result set that have customer data but no order data e.g. 168, 169, etc. The order data in these rows are NULL. It means that those customers do not have any order in theorderstable.If you replace theLEFT JOINclause by theINNER JOINclause, you only get the customers who have orders in theorderstable.MySQL LEFT JOIN clause to find unmatched rowsTheLEFT JOINclause is very useful when you want to find the rows in the left table that do not match with the rows in the right table. To find the unmatched rows between two tables, you add aWHERE clauseto theSELECTstatement to select only rows whose column values in the right table contains theNULLvalues.For example, to find all customers who have not ordered any product, you can use the following query:1234567SELECT c.customerNumber, c.customerName, orderNumber, o.statusFROM customers cLEFT JOIN orders o ON c.customerNumber = o.customerNumberWHERE orderNumber IS NULL

In this tutorial, we have explained the MySQL LEFT JOIN clause and shown you how to apply it to query data from multiple database tables.

Home/Basic MySQL Tutorial/ MySQL Self JoinMySQL Self JoinSummary:in this tutorial, you will learn how to useMySQL self jointhat joins a table to itself using join statement.In the previous tutorial, you have learned how to join a table to the other tables usingINNER JOIN,LEFT JOINorRIGHT JOINstatement. However, there is a special case that you can join a table to itself, which is known as self join.You use self join when you want to combine records with other records in the same table. To perform the self join operation, you must use atable aliasto help MySQLdistinguish the left table from the right table of the same table.MySQL Self Join ExamplesLets take a look at theemployeestable in thesample database.In theemployeestable, we store not only employees data but also organization structure data. Thereportstocolumn is used to determine the manager ID of an employee.

In order to get the whole organization structure, we can join theemployeestable to itself using theemployeeNumberandreportsTocolumns. Theemployeestable has two roles: one isManagerand the other isDirect Report.12345SELECT CONCAT(m.lastname,', ',m.firstname) AS 'Manager', CONCAT(e.lastname,', ',e.firstname) AS 'Direct report' FROM employees eINNER JOIN employees m ON m.employeeNumber = e.reportstoORDER BY manager

In the above example, we only see employees who have manager. However, we dont see the top manager because his name is filtered out due to theINNER JOINclause. The top manager is the employee who does not have manager or his manager no. isNULL.Lets change theINNER JOINclause to theLEFT JOINclause in the query above to include the top manager. We also need to use theIFNULLfunction to display the top manager if the mangers name isNULL.12345SELECT IFNULL(CONCAT(m.lastname,', ',m.firstname),'Top Manager') AS 'Manager', CONCAT(e.lastname,', ',e.firstname) AS 'Direct report' FROM employees eLEFT JOIN employees m ON m.employeeNumber = e.reportstoORDER BY manager DESC

By using MySQL self join, we can display a list of customers who locate in the same city byjoiningthecustomerstable to itself.12345678SELECT c1.city, c1.customerName, c2.customerNameFROM customers c1INNER JOIN customers c2 ON c1.city = c2.city AND c1.customername c2.customerName ORDER BY c1.city

We joined thecustomerstable to itself with the following join conditions: c1.city = c2.cityto make sure that both customers have the same city c.customerName c2.customerNameto ensure that we dont get the same customer.In this tutorial, we have introduced you to MySQLselfjoin that allows you to join a table to itself by usingINNER JOINorLEFT JOINclauses.Home/Basic MySQL Tutorial/ MySQL HAVINGMySQL HAVINGSummary:in this tutorial, you will learn how to useMySQL HAVINGclause to specify a filter condition for groups of rows or aggregates.Introducing MySQL HAVING clauseThe MySQL HAVING clause is used in theSELECT statementto specify filter conditions for group of rows or aggregates.The MySQL HAVING clause is often used with theGROUP BYclause. When using with theGROUP BYclause, you can apply a filter condition to the columns that appear in the GROUP BY clause. If theGROUP BYclause is omitted, the MySQL HAVING clause behaves like theWHERE clause. Notice that the MySQL HAVING clause applies the condition to each group of rows, while theWHEREclause applies the condition to each individual row.Examples of using MySQL HAVING clauseLets take a look at an example of using MySQL HAVING clause.We will use theorderdetailstable in thesample databasefor the sake ofdemonstration.

We can use theMySQL GROUP BYclause to get order number, the number of items sold per order and total sales for each:12345SELECT ordernumber, SUM(quantityOrdered) AS itemsCount, SUM(priceeach) AS totalFROM orderdetailsGROUP BY ordernumber

Now, we can find which order has total sales greater than $1000. We use the MySQL HAVING clause on the aggregate as follows:123456SELECT ordernumber, SUM(quantityOrdered) AS itemsCount, SUM(priceeach) AS totalFROM orderdetailsGROUP BY ordernumberHAVING total > 1000

We can construct a complex condition in the MySQL HAVING clause using logical operators such asORandAND. Suppose we want to find which order has total sales greater than $1000 and contains more than 600 items, we can use the following query:123456SELECT ordernumber, sum(quantityOrdered) AS itemsCount, sum(priceeach) AS totalFROM orderdetailsGROUP BY ordernumberHAVING total > 1000 AND itemsCount > 600

Suppose we want to find all orders that has shipped and has total sales greater than $1500, we can join theorderdetailstable with theorderstable by using theINNER JOINclause, and apply condition on thestatuscolumn and thetotalaggregate as the following query:12345678SELECT a.ordernumber, SUM(priceeach) total, statusFROM orderdetails aINNER JOIN orders b ON b.ordernumber = a.ordernumberGROUP BY ordernumberHAVING b.status = 'Shipped' AND total > 1500;

The MySQL HAVING clause is only useful when we use it with the GROUP BY clause to generate the output of the high-level reports. For example, we can use the MySQL HAVING clause to answer some kinds of queries like give me all the orders in this month, this quarter and this year that have total sales greater than 10K.In this tutorial, you have learned how to use the MySQL HAVING clause together with the GROUP BY to specify filter condition on groups of records or aggregates.

Home/Basic MySQL Tutorial/ MySQL SubqueryMySQL SubquerySummary: in this tutorial, we will show you how to use theMySQL subqueryto write complex queries and explain the correlated subquery concept.A MySQL subquery is a query that is nested inside another query such asSELECT,INSERT,UPDATEorDELETE. A MySQL subquery is also can be nested inside another subquery. A MySQL subquery is also called an inner query, while the query that contains the subquery is called an outer query.Lets take a look at the following subquery that returns employees who locate in the offices in theUSA. The subquery returns alloffices codesof the offices that locate in the USA. The outer query selects the last name and first name of employees whose office code is in the result set returned from the subquery.

You can use a subquery anywhere an expression can be used. A subquery also must be enclosed in parentheses.MySQL subquery within a WHERE clauseMySQL subquery with comparison operatorsIf a subquery returns a single value, you can use comparison operators to compare it with the expression in theWHERE clause. For example, the following query returns the customer who has the maximum payment.12345678SELECT customerNumber, checkNumber, amountFROM paymentsWHERE amount = ( SELECT MAX(amount) FROM payments)

You can also use other comparison operators such as greater than (>), less than( ( SELECT AVG(amount) FROM payments)

MySQL subquery with IN and NOT IN operatorsIf a subquery returns more than one value, you can use other operators such asINorNOT INoperator in theWHEREclause. For example, you can use a subquery withNOT INoperator to find customer who has not ordered any product as follows:123456SELECT customernameFROM customersWHERE customerNumber NOT IN( SELECT DISTINCT customernumber FROM orders)

MySQL subquery with EXISTS and NOT EXISTSWhen a subquery is used withEXISTSorNOT EXISTSoperator, a subquery returns a Boolean value ofTRUEorFALSE. The subquery acts as an existence check.In the following example, we select a list of customers who have at least one order with total sales greater than 10K.First, we build a query that checks if there is at least one order with total sales greater than 10K:1234SELECT priceEach * quantityOrderedFROM orderdetailsWHERE priceEach * quantityOrdered > 10000GROUP BY orderNumber

The query returns 6 records so that when we use it as a subquery, it will returnTRUE; therefore the whole query will return all customers:12345678SELECT customerNameFROM customersWHERE EXISTS (SELECT priceEach * quantityOrderedFROM orderdetailsWHERE priceEach * quantityOrdered > 10000GROUP BY orderNumber)

If you replace theEXISTSbyNOT EXISTin the query, it will not return any record at all.MySQL subquery in FROM clauseWhen you use a subquery in theFROMclause, the result set returned from a subquery is used as a table. This table is referred to as aderived tableormaterialized subquery.The following subquery finds the maximum, minimum and average number of items in sale orders:12345678SELECT max(items), min(items), floor(avg(items))FROM(SELECT orderNumber, count(orderNumber) AS itemsFROM orderdetailsGROUP BY orderNumber) AS lineitems

Notice that the subquery returns the following result set that is used as a derived table for the outer query.

MySQL correlated subqueryIn the previous examples, we see the subquery itself is independent. It means that you can execute the subquery as a normal query. However a correlated subquery is a subquery that uses the information from the outer query, or we can say that a correlated subquery depends on the outer query. A correlated subquery is evaluated once for each row in the outer query.In the following correlated subquery, we select products whose buy price is greater than the average buy price of all products for a particularproduct line.1234567SELECT productname, buypriceFROM products AS p1WHERE buyprice > ( SELECT AVG(buyprice) FROM productsWHERE productline = p1.productline)

The inner query executes for every product line because the product line is changed for every row. Hence the average buy price will also change.In this tutorial, we have shown you how to use MySQL subquery and correlated subquery to write more complex queries.Home/Basic MySQL Tutorial/ MySQL UPDATE JOINMySQL UPDATE JOINSummary: in this tutorial, you will learn how to useMySQL UPDATE JOINstatement to perform cross-table update. We will show you step by step how to useINNER JOINclause andLEFT JOINclause with theUPDATEstatement.MySQL UPDATE JOIN syntaxYou often useJOINclauses to query records in a table that have (in case ofINNER JOIN) or do not have (in case ofLEFT JOIN) corresponding records in another table. In MySQL, you can use theJOINclauses in theUPDATE statementto perform cross-table update.The syntax of the MySQLUPDATE JOINis as follows:12345UPDATE T1, T2,[INNER JOIN | LEFT JOIN] T1 ON T1.C1 = T2. C1SET T1.C2 = T2.C2, T2.C3 = exprWHERE condition

Lets examine the MySQLUPDATE JOINsyntax in greater detail: First, you specify the main table (T1) and the table that you want the main table to join to (T2) after theUPDATEclause. Notice that you must specify at least one table after theUPDATEclause. The data in the table that is not specified after theUPDATEclause is not updated. Second, you specify a kind of join you want to use i.e., eitherINNER JOINorLEFT JOINand a join condition. Notice that theJOINclause must appear right after theUPDATEclause. Third, you assign new values to the columns in T1 and/or T2 tables that you want to update. Fourth, the condition in theWHEREclause allows you to limit the rows to update.If you follow theUPDATE statement tutorial, you notice that there is another way to update data cross-table using the following syntax:1234UPDATE T1, T2SET T1.c2 = T2.c2,T2.c3 = exprWHERE T1.c1 = T2.c1 AND condition

ThisUPDATEstatement works the same asUPDATE JOINwith implicitINNER JOINclause.It means you can rewrite the above statement as follows:12345UPDATE T1,T2INNER JOIN T2 ON T1.C1 = T2.C1SET T1.C2 = T2.C2,T2.C3 = exprWHERE condition

Lets take a look at some examples of using theUPDATE JOINstatement to having a better understanding.MySQL UPDATE JOIN examplesWe are going to use a new sample database in these examples. The sample database contains 2 tables: employeestable stores employee data with employee id, name, performance and salary. meritstable stores performance and merits percentage.The SQL script for creating and loading data in this sample database is as follows:1234567891011121314151617181920212223242526272829303132333435CREATE DATABASE IF NOT EXISTS empdb;-- create tablesCREATE TABLE merits (performance INT(11) NOT NULL,percentage FLOAT NOT NULL,PRIMARY KEY (performance));CREATE TABLE employees (emp_id INT(11) NOT NULL AUTO_INCREMENT,emp_name VARCHAR(255) NOT NULL,performance INT(11) DEFAULT NULL,salary FLOAT DEFAULT NULL,PRIMARY KEY (emp_id),CONSTRAINT fk_performanceFOREIGN KEY(performance) REFERENCES merits(performance));-- insert data for merits tableINSERT INTO merits(performance,percentage)VALUES(1,0), (2,0.01), (3,0.03), (4,0.05), (5,0.08);-- insert data for employees tableINSERT INTO employees(emp_name,performance,salary)VALUES('Mary Doe', 1, 50000),('Cindy Smith', 3, 65000),('Sue Greenspan', 4, 75000),('Grace Dell', 5, 125000),('Nancy Johnson', 3, 85000),('John Doe', 2, 45000),('Lily Bush', 3, 55000);

MySQL UPDATE JOIN example with INNER JOIN clauseSuppose you want to adjust the salary of employees based on their performance. The merits percentages are stored in themeritstable therefore you have to useUPDATE INNER JOINstatement to adjust the salary of employees in theemployeestable based on thepercentagestored in themeritstable. The link between theemployeesandmerittables isperformancefield. See the following query:123UPDATE employeesINNER JOIN merits ON employees.performance = merits.performanceSET salary = salary + salary * percentage

How the query works. We specify only theemployeestable afterUPDATEclause because wewant to update data in theemployeestable only. For each employee record in theemployeestable, the query checks the its performance value against the performance value in themeritstable. If it finds a match, it gets thepercentagein themeritstable and update thesalarycolumn in theemployeestable. Because we omit theWHEREclause in theUPDATEstatement, all the records in theemployeestable get updated.MySQL UPDATE JOIN example with LEFT JOINSuppose the company hires two more employees:123INSERT INTO employees(emp_name,performance,salary)VALUES('Jack William',NULL,43000),('Ricky Bond',NULL,52000);

Because these employees are new hires so their performance data is not available orNULL.To increase the salary for new hires, you cannot use theUPDATE INNER JOINstatement because their performance data is not available in themerittable. This is why theUPDATE LEFT JOINcomes to therescue.TheUPDATE LEFT JOINstatement basically updates a record in a table when it does not have a corresponding record in another table. For example, you can increase the salary for a new hire by 1.5% using the following statement:1234UPDATE employeesLEFT JOIN merits ON employees.performance = merits.performanceSET salary = salary + salary * 0.015;WHERE merits.percentage IS NULL

In this tutorial, we have shown you how to use MySQLUPDATE JOINwithINNER JOINandLEFT JOINto perform cross-table update.Home/Basic MySQL Tutorial/ MySQL ON DELETE CASCADE Deletes Data From Multiple TablesMySQL ON DELETE CASCADE Deletes Data From Multiple TablesSummary: in this tutorial, you will learn how to useMySQL ON DELETE CASCADEreferential action for a foreign key to delete data from child tables when you delete data from a parent table.In the previous tutorial, you learned how to delete data from multiple related tables by using a singleDELETE statement. However, MySQL provides a more effective way calledON DELETE CASCADEreferential action for a foreign key that allows you to delete data from child tables automatically when you delete the data from the parent table.MySQLON DELETE CASCADE ExampleLets take a look at an example of using MySQLON DELETE CASCADE.We have two tables namedbuildingsandrooms. Each building has one or more rooms. However, each room belongs to only one building. A room would not exist without a building.The relationship between thebuildingstable and theroomstable is one-to-many (1:N) as illustrated in the following database diagram:

When we delete a record from thebuildingstable, we want the records in theroomstable, which associates with the deleted building record to be removede.g., when we delete a record with building no. 2 in thebuildingstable as the following query:12DELETE FROM buildingsWHERE building_no = 2;

We want the records in theroomstable associated with the building number 2 to be removed as well.The following are steps that demonstrates how MySQLON DELETE CASCADEreferential action works.Step 1. Create thebuildingstable:123456CREATE TABLE buildings (building_no int(11) NOT NULL AUTO_INCREMENT,building_name varchar(255) NOT NULL,address varchar(355) NOT NULL,PRIMARY KEY (building_no)) ENGINE=InnoDB;

Step 2. Create theroomstable:1234567891011CREATE TABLE rooms (room_no int(11) NOT NULL AUTO_INCREMENT,room_name varchar(255) NOT NULL,building_no int(11) NOT NULL,PRIMARY KEY (room_no),KEY building_no (building_no),CONSTRAINT rooms_ibfk_1 FOREIGN KEY (building_no) REFERENCES buildings (building_no) ON DELETE CASCADE) ENGINE=InnoDB;

Notice that we put theON DELETE CASCADEclause at the end of the foreign key constraint definition.Step 3. Insert data into thebuildingstable:123INSERT INTO buildings(building_name,address)VALUES('ACME Headquaters','3950 North 1st Street CA 95134'),('ACME Sales','5000 North 1st Street CA 95134')

Step 4. Query data from thebuildingstable:1SELECT * FROM buildings;

We have two records in thebuildingstable.Step 5. Insert data into theroomstable:123456INSERT INTO rooms(room_name,building_no)VALUES('Amazon',1),('War Room',1),('Office of CEO',1),('Marketing',2),('Showroom',2)

Step 6. Query data from theroomstable:1SELECT * FROM rooms

We have 3 rooms that belong to building 1 and 2 rooms that belong to the building 2.Step 7. Delete the building with building no. 2:12DELETE FROM buildingsWHERE building_no = 2

Step 8. Query data fromroomstable:1SELECT * FROM rooms

As you see, all the records that refer tobuilding_no2 were deleted.Notice thatON DELETE CASCADEworks only with tables whosestorage enginessupport foreign keys e.g., InnoDB. Some table types do not support foreign keys such as MyISAM so you should choose appropriate storage engines for the tables that you plan to use the MySQLON DELETE CASCADEreferential action.Tips to find tables affected by MySQL ON DELETE CASCADE actionSometimes, it is useful to know which table is affect by the MySQLON DELETE CASCADEreferential action when you delete data from the parent table. You can query this data from thereferential_constraintsin theinformation_schemadatabase as follows:1234567USE information_schema;SELECT table_nameFROM referential_constraintsWHERE constraint_schema = 'database_name' ANDreferenced_table_name = 'parent_table' ANDdelete_rule = 'CASCADE'

For example, to find tables that associated with thebuildingstable with theCASCADEdelete rule in theclassicmodelsdatabase, you use the following query:1234567USE information_schema;SELECT table_nameFROM referential_constraintsWHERE constraint_schema = 'classicmodels' ANDreferenced_table_name = 'buildings' ANDdelete_rule = 'CASCADE'

In this tutorial, we have shown you step by step how to use the MySQLON DELETE CASCADEreferential action for a foreign key to delete data automaticallyfrom the child tables when you delete data from the parent table.Home/Basic MySQL Tutorial/ MySQL DELETE JOINMySQL DELETE JOINSummary: in this tutorial, well show you how to delete data from multiple tables by usingMySQLDELETEJOINstatement.In the previous tutorial, we showed you several ways to delete records from multiple tables by using: A singleDELETEstatement on multiple tables. A singleDELETEstatement on multiple tables where the child tables haveON DELETE CASCADEreferential actions for the foreign keys.This tutorial introduces to you a more flexible way to delete data from multiple tables by usingINNER JOINorLEFT JOINclause in theDELETEstatement.It is easier to follow this tutorial if you already have some knowledge of theINNER JOINandLEFT JOINclauses.MySQL DELETE JOIN with INNER JOINYou often use theINNER JOINclause in theSELECT statementto select records from a table that have corresponding records in other tables. To make it more convenient, MySQL also allows you to use theINNER JOINclause with theDELETEstatement to delete records from a table and also the corresponding records in other tables e.g., to delete records from bothT1andT2tables that meet a particular condition, you use the following statement:1234DELETE T1, T2FROM T1INNER JOIN T2 ON T1.key = T2.keyWHERE condition

Notice that you put table namesT1andT2betweenDELETEandFROM. If you omit theT1table, theDELETEstatement only deletes records in theT2table, and if you omit theT2table, only records in theT1table are deleted.The join conditionT1.key = T2.keyspecifies the corresponding records in theT2table that need be deleted.The condition in theWHEREclause specifies which records in theT1andT2that need to be deleted.MySQL DELETE JOIN with INNER JOIN exampleLets take a look at the following diagram.

Each office has one or more employees, however each employee only belongs to on office.Suppose you want to delete the office withofficeCode 5and you dont update or delete theofficeCodecolumn in theemployeestable, the data in the employees table would be invalid. To delete the office withofficeCode 5and also employee records that belong to the office, you can use theDELETEstatement with theINNER JOINclause.Lets check the offices and employees data before deleting the data.12SELECT * FROM officesWHERE officeCode = 5

12SELECT * FROM employeesWHERE officeCode = 5

Now, you can delete records associated withofficeCode5 from bothofficesandemployeestables:12345DELETE offices, employees FROM officesINNER JOIN employees ON employees.officeCode = employees.officeCodeWHERE offices.officeCode = 5

If you use theSELECTstatements above to query office and employee data withofficeCode5 in theofficesandemployeestables again, you will not see any row returned.MySQL DELETE JOIN with LEFT JOINYou often useLEFT JOINclause in theSELECTstatement to find records that exist in the left table and does not have corresponding records in the right table. You can also use theLEFT JOINclause in theDELETEstatement to delete record in a table (left table) that does not have corresponding record in another table (right table).The following syntax illustrates how to useDELETEstatement withLEFT JOINclause to delete records fromT1table that does not have corresponding records in theT2table:1234DELETE T1FROM T1 LEFT JOIN T2 ON T1.key = T2.key WHERE T2.key IS NULL

Note that you only putT1table after theDELETEkeyword, not bothT1andT2tables like you did with theINNER JOINclause.MySQL DELETE JOIN with LEFT JOIN exampleLets see the following database diagram:

Each customer has zero or more orders. However, each order belongs to one and only one customer.You can useDELETEstatement withLEFT JOINclause to clean up our customers master data. The following statement removes customers who do not have any order:1234DELETE customersFROM customersLEFT JOIN orders ON customers.customerNumber = orders.customerNumberWHERE orderNumber IS NULL;

Now, if we query customers who have not ordered any product by using the followingSELECTLEFT JOINquery:123456SELECT c.customerNumber,c.customerName,orderNumberFROM customers cLEFT JOIN orders o ON c.customerNumber = o.customerNumberWHERE orderNumber IS NULL;

You will not see any row returned. It means you have successfully deleted customers who have not ordered any products.In this tutorial, You have learn how to use the MySQL DELETE JOIN withINNER JOIN andLEFT JOINto delete data from multiple tables.

Home/Basic MySQL Tutorial/ MySQL TRUNCATE TABLEMySQL TRUNCATE TABLESummary: in this tutorial, you will learn how to use theMySQL TRUNCATE TABLEstatement to delete all data in a table.Introduction to MySQL TRUNCATE TABLE statementThe MySQLTRUNCATE TABLEstatement allows you to delete all data in a table. Therefore it is like aDELETEstatement without aWHERE clause. However in some cases, the MySQLTRUNCATE TABLEstatement is more efficient than theDELETEstatement.The syntax of the MySQLTRUNCATE TABLEstatement is as follows:1TRUNCATE TABLE table_name

You specify table name after theTRUNCATE TABLEclause to delete all data in the table.If you are using InnoDB tables, MySQL will check if there is anyforeign keyconstraint available in the tables before deleting data. If the table has any foreign key constraint, theTRUNCATE TABLEstatement deletes rows one by one. If the foreign key constraint hasDELETE CASCADEaction, the corresponding rows in the child tables are also deleted. If the foreign key constraint does not specify theDELETE CASCADEaction, theTRUNCATE TABLEdeletes rows one by one, and it will stop and issue an error when it encounters a row that is referenced by a row in a child table. If the table does not have any foreign key constraint, theTRUNCATE TABLEstatement drops the table and recreates a new empty one with the same definition, which is faster and more efficient than using theDELETEstatement especially for big tables.If you are using otherstorage engines, theTRUNCATE TABLEstatement just drops and recreates a new table.Notice that theTRUNCATE TABLEstatement resets auto increment value to 0 if the table has anAUTO_INCREMENTcolumn.In addition, theTRUNCATE TABLEdoes not use theDELETEstatement therefore theDELETE triggersassociated with the table will not be invoked.MySQL TRUNCATE TABLE examplesFirst, create a new table namedbooksfor the demonstration:123456CREATE DATABASE dbdemo;CREATE TABLE books( id int auto_increment primary key,title varchar(255) not null)ENGINE=InnoDB;

Second, populate data for thebookstable by using the followingstored procedure:1234567891011121314151617DELIMITER $$CREATE PROCEDURE load_book_data(IN num int(4))BEGIN DECLARE counter int(4) default 0; DECLARE book_title varchar(255) default ''; WHILE counter < num DO SET title = concat('Book title #',counter); SET counter = counter + 1; INSERT INTO books Values(book_title); END WHILE;END$$DELIMITER ;

Third, load 10000 rows into the books table. It will take a while.1CALL load_book_data(10000)

Fourth, use theTRUNCATE TABLEstatement to see how fast it performs in comparison with theDELETEstatement.1TRUNCATE TABLE books;

In this tutorial, we have shown you how to use the MySQLTRUNCATE TABLEstatement to delete all data from tables efficiently especially for large tables.

Home/Basic MySQL Tutorial/ MySQL TIMESTAMPMySQL TIMESTAMPSummary: in this tutorial, you will learn aboutMySQL TIMESTAMPand its features such as automatic initialization and automatic update to create auto-initialized and auto-updated columns for a table.Introduction to MySQL TIMESTAMPThe MySQLTIMESTAMPis a temporaldata typethat hold the combination of date and time. TheformatofTIMESTAMPcolumn isYYYY-MM-DD HH:MM:SSwhich is fixed at 19 characters.TheTIMESTAMPvalue has a range of 1970-01-01 00:00:01 UTC to 2038-01-19 03:14:07 UTC.When youinsertaTIMESTAMPvalue, MySQL converts it from your connections time zone to UTC for storage. When you query aTIMESTAMPvalue, MySQL converts the UTC value back to your connections time zone. Notice that this conversion does not occur for other temporal data type such asDATETIME.By default, the connection time zone is the MySQL database servers time zone. You can use a different time zone when you connect to MySQL database server.When youretrieveaTIMESTAMPvalue that were inserted by a client in a different time zone , you will get a value that is not the same as the value stored in the database. As long as you dont change the time zone, you can get the sameTIMESTAMPvalue that you store.MySQL TIMESTAMP time zone exampleLets look at an example to see how MySQL handlesTIMESTAMPvalues.First,created a new tablenamedtest_timestampthat has a TIMESTAMP column: t1;123CREATE TABLE IF NOT EXISTS test_timestamp ( t1TIMESTAMP);

Second, set session the time zone to +00:00 UTC by using theSET time_zonestatement.1SET time_zone='+00:00';

Third, insert aTIMESTAMPvalue into thetest_timestamptable .12INSERT INTO test_timestamp VALUES('2008-01-01 00:00:01');

Fourth, select theTIMESTAMPvalue from thetest_timestamptable.12SELECT t1FROM test_timestamp;

Fifth, set the sessions time zone to a different time zone and see what value we get back from the database server:1234SET time_zone ='+03:00';SELECT t1FROM test_timestamp;

As you see, we got a different value that is adjusted to the new time zone.Automatic initialization and automatic update featuresTheTIMESTAMPdata type provides a very useful feature that allows you to: Set the current timestamp for the inserted rows automatically if you dont specify value for the timestamp column. This timestamp column is called auto-initialized column. This feature of theTIMESTAMPis called automatic initialization. Set the current timestamp for the updated rows when the values in other column change. This timestamp column is known as auto-updated column. This feature of theTIMESTAMPis called automatic update.Lets take an example to have a better understanding how auto-initialized column and auto-updated column work.First, create a table namedtsthat has two timestamp columns:1234567CREATE TABLE ts(id INT AUTO_INCREMENT PRIMARY KEY,title VARCHAR(255) NOT NULL,created_on TIMESTAMP DEFAULT 0,changed_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP);

The data type of thecreated_oncolumn isTIMESTAMPwith the default value isCURRENT_TIMESTAMP. When you insert a new row into the ts table without specifying value for thecreated_oncolumn, thecreated_oncolumn will take the current timestamp as the default value.The data type of thechanged_oncolumn is theTIMESTAMPwith the default value isCURRENT_TIMESTAMP. In addition, it has a special attributeON UPDATE CURRENT_TIMESTAMP. This allows thechanged_oncolumn to take the current timestamp value as the default value when the values of other columns change e.g., title.Second, insert a new row into thetstable:12INSERT INTO ts(title)VALUES('Test MySQL timestamp');

Third, select data from thetstable:1SELECT * FROM ts;

Thecreated_onandchanged_oncolumn take the current timestamp as the default.Fourth, update the title column value123UPDATE tsSET title = 'Test MySQL timestamp update'WHERE id = 1;

Fifth, query data from the ts table again:1SELECT * FROM ts;

MySQL updates the value of thechanged_oncolumn to the current timestamp automatically when the value of thetitlecolumn changes by theUPDATEstatement.Note: since MySQL 5.6.5, theDATETIMEdata type also has automatic initialization and automatic update feature. In addition, theDEFAULT_CURRENT_TIMESTAMPandON UPDATE CURRENT TIMESTAMPattributes can be applied to multiple columns, not just 1 column in the previous versions.In this tutorial, we have introduced you to MySQLTIMESTAMPdata type and shown you how to use automatic initialization and automatic update features ofTIMESTAMP.

Home/Basic MySQL Tutorial/ MySQL ReplaceMySQL ReplaceSummary:in this tutorial, you will learn how to use theMySQL REPLACEstatement to insert or update data in database tables.Introduction to MySQL REPLACE statementThe MySQLREPLACEstatement is a MySQL extension to the SQL standard. The MySQLREPLACEstatement works like theINSERT statementwith the additional rules: If the record which you want to insert does not exist, the MySQLREPLACEinserts a new record. If the record which you want to insert already exists, MySQLREPLACEdeletes the old record first and then insert a new record.In order to use MySQLREPLACEstatement, you need to have at least bothINSERTandDELETEprivileges.Please dont confuse theREPLACEstatement with theREPLACEstring function.MySQL REPLACE statementsMySQL REPLACE INTO statementThe first form of theREPLACEstatement is similar to theINSERTstatement except the keywordINSERTis replaced by theREPLACEkeyword as follows:12REPLACE INTO table_name(column_name1,column_name2,)VALUES(value1,value2,)

For example, if you want to insert a new office into theofficestable, you use the following query:12REPLACE INTO offices(officecode,city)VALUES(8,'San Jose')

Notice that the default values of of the columns that does not appear in theREPLACEstatement will be inserted to the corresponding columns.If you want to update the office that we have inserted with the new citySan Mateo,you can use theREPLACEstatement as follows:12REPLACE INTO offices(officecode,city)VALUES(8,'San Mateo')

Two rows affected by the query above because the existing record was deleted and the new one was inserted.MySQL REPLACE acts like UPDATE statementThe second form of MySQLREPLACElike theUPDATEstatement as follows:123REPLACE INTO table_nameSET column_name1 = value1 ANDcolumn2 = value2

Notice that there is noWHERE clausein theREPLACEstatement. For example, if you want to update the office inSan Mateocity withofficecodevalue8, you use theREPLACEstatement as follows:123REPLACE INTO officesSET officecode = 8 andcity = 'Santa Cruz'

MySQL REPLACE INTO with SELECT statementThe third form of REPLACEis similar toINSERT INTO SELECTstatement:1234REPLACE INTO table_name1(column_name1,column_name2,)SELECT column_name1, column_name2FROM table_name2WHERE where_condition

Suppose if you want to copy theofficewithofficecodevalue 1, you use theREPLACE INTO SELECTstatement as the following query:1234567891011121314151617181920REPLACE INTO offices(officecode, city, phone, addressline1, addressline2, state, country, postalcode, territory)SELECT (SELECT MAX(officecode) + 1 FROM offices),city,phone,addressline1,addressline2,state,country,postalcode,territoryFROM officesWHERE officecode = 1

MySQL REPLACE usagesThere are several important points you need to know when you use theREPLACEstatement: If you are developing an application that potentially supports not only MySQL database, try to avoid using theREPLACEstatement because other database management systems may not support theREPLACEstatement. Instead, you can use the combination of theINSERTandDELETEstatements. If you are using theREPLACEstatement in the table that hastriggersand if the deletion of duplicate key happens, the triggers will be fired in the following sequence:BEFORE INSERT,BEFORE DELETE,AFTER DELETE,AFTER INSERT. You should use theUPDATEstatement in case you want to update data because it performs faster than theREPLACEstatement.In this tutorial, youve learned different forms of MySQL REPLACE statement to insert or update data in database tables.

Home/Basic MySQL Tutorial/ MySQL TransactionMySQL TransactionSummary: in this tutorial, you will learn aboutMySQL transactionand how to use MySQL COMMIT statement and MySQL ROLLBACK statement to manage transactions in MySQL.Introducing to MySQL TransactionTo understand what a transaction in MySQL is, lets take a look at an example of adding a new sale order in oursample database. The steps of adding a sale order are as described as follows: Get latest sale order number fromorderstable, and use the next sale order number as the new sale order number. Insert a new sale order intoorderstable for a given customer Insert new sale order items intoorderdetailstable Get data from both tableordersandorderdetailstables to confirm the changesNow imagine what would happen to your data if one or more steps above fail because of database failure such as table lock security? If the step of adding order items intoorderdetailstable failed, you would have an empty sale order in your system without knowing it. Your data may not be integrity and the effort you have to spend to fix it is tremendous.How do you solve this problem? Thats why the transaction processing comes to the rescue. MySQL transaction enables you to execute a set of MySQL operations to ensure that the database never contains the result of partial operations. In a set of operations, if one of them fails, the rollback occurs to restore the database. If no error occurred, the entire set of statements is committed to the database.Using MySQL TransactionLets review the most important MySQL transaction statements before we are using them for the adding sale order in the example above.To start a transaction you use theSTART TRANSACTIONstatement. To undo MySQL statements you use theROLLBACKstatement. Notice that there are several SQL statements you cannot useROLLBACKsuch as:1234567CREATE / ALTER / DROP DATABASECREATE /ALTER / DROP / RENAME / TRUNCATE TABLECREATE / DROP INDEXCREATE / DROP EVENTCREATE / DROP FUNCTIONCREATE / DROP PROCEDURE

To write the changes into the database within a transaction you use theCOMMITstatement. It is important to note that MySQL automatically commit the changes to the database by default. To force MySQL not to commit changes automatically, you need to use the following statement:1SET autocommit = 0;

MySQL transaction exampleIn order to use MySQL transaction, you first have to break your MySQL statements into logical portion and determine when data should be committed or rollback.Lets take a look an example of using MySQL transaction to add new sale order into our sample database above and add the transaction processing steps: Start a transaction usingSTART TRANSACTIONstatement. Get latest sale order number fromorderstable, and use the next sale order number as the new sale order number. Insert a new sale order intoorderstable for a given customer. Insert new sale order items intoorderdetailstable. Commit changes usingCOMMITstatement. Get data from both tableordersandorderdetailstables to confirm the changes.The following is the script that performs the above steps:12345678910111213141516171819202122232425262728293031323334353637-- start a new transactionstart transaction;-- get latest order numberselect @orderNumber := max(orderNUmber) from orders;-- set new order numberset @orderNumber = @orderNumber+ 1;-- insert a new order for customer 145insert into orders(orderNumber, orderDate, requiredDate, shippedDate, status, customerNumber)values(@orderNumber, now(), date_add(now(), INTERVAL 5 DAY), date_add(now(), INTERVAL 2 DAY), 'In Process',145);-- insert 2 order line itemsinsert into orderdetails(orderNumber, productCode, quantityOrdered, priceEach, orderLineNumber)values(@orderNumber,'S18_1749', 30, '136', 1),(@orderNumber,'S18_2248', 50, '55.09', 2); -- commit changescommit; -- get the new inserted orderselect * from orders a inner join orderdetails b on a.ordernumber = b.ordernumberwhere a.ordernumber = @ordernumber;

In this tutorial,youvelearned how to use MySQL transaction statements includingSTART TRANSACTION,COMMITandROLLBACKto manage transactions in MySQL to protect data integrity.

Home/Basic MySQL Tutorial/ MySQL Prepared StatementMySQL Prepared StatementSummary: in this tutorial, you will learn how to useMySQL prepared statementto make your queries execute faster and more secure.Introduction to MySQL Prepared StatementPrior MySQL version 4.1, the query is sent to the MySQL server in the textual format. In turn, MySQL returns the data to the client using textual protocol. MySQL has to parse the query fully and coverts the result set into a string before returning it to the client.The textual protocol has serious performance implication. To resolve this problem, MySQL added a new feature called prepared statement since version 4.1.The prepared statement takes advantage ofclient/server binary protocol. It passes query that contains placeholders (?) to the MySQL server as the following example:123SELECT * FROM products WHERE productCode = ?

When MySQL executes this query with differentproductcodevalues, it does not have to parse the query fully. As a result, this helps MySQL execute the query faster, especially when MySQL executes the query multiple times. Because the prepared statement uses placeholders (?), this helps avoid many variants of SQL injection hence make your application more secure.MySQL prepared statement usageIn order to use MySQL prepared statement, you need to use other three MySQL statements as follows: PREPARE Prepares statement for execution. EXECUTE Executes a prepared statement preparing by a PREPARE statement. DEALLOCATE PREPARE Releases a prepared statement.The following diagram illustrates how to use the prepared statement:

MySQL prepared statement exampleLets take a look at an example of using the MySQL prepared statement.12345678PREPARE stmt1 FROM 'SELECT productCode, productNameFROM productsWHERE productCode = ?';SET @pc = 'S10_1678';EXECUTE stmt1 USING @pc;DEALLOCATE PREPARE stmt1;

First we used thePREPAREstatement to prepare a statement for execution. We used theSELECTstatement to query product data from theproductstable based on a specified product code. We used question mark (?) as a placeholder for the product code.Next, we declared a product code variable@pcand set it values toS10_1678.Then, we used theEXECUTEstatement to execute the prepared statement with product code [email protected], we used theDEALLOCATE PREPAREto release the prepared statement.In this tutorial, we have shown you how to use MySQL prepared statement to execute a query with placeholders to improve the speed of the query and make your query more secure.

Home/Basic MySQL Tutorial/ MySQL Character SetMySQL Character SetSummary: in this tutorial, you will learn aboutMySQL character set. After the tutorial, you will know how to get all character sets in MySQL, how to convert strings between character sets and how to configure proper character sets for client connections.Introduction to MySQL character setA MySQL character set is a set of characters that are legal in a string. For example, we have an alphabet with letters fromatoz.We assign each letter a numbera = 1,b = 2, etc. The letterais a symbol, and the number1that associates with the letterais the encoding. The combination of all letters from a to z and theircorrespondingencodingsis a character set.Each character set has one or more collations that define a set of rules for comparing characters within the character set. Check it out theMySQL collationtutorial to learn about the collations in MySQL.MySQL supports various character sets that allow you to store almost every character in a string.To get all available character sets in MySQL database server, you use theSHOW CHARACTER SETstatement as follows:1SHOW CHARACTER SET;

The default character set in MySQL islatin1. If you want to store characters from multiple languages in a single column, you can use Unicode character sets, which isutf8orucs2.The values in theMaxlencolumn specify the number of bytes that a character in a character set holds. Some character sets contain single-byte characters e.g.,latin1,latin2,cp850, etc., whereas other character sets contain multi-byte characters.MySQL provides theLENGTHfunction to get a length of a string in bytes, and theCHAR_LENGTHfunction to get the length of a string in characters. If a string contains multi-bytes character, the result of theLENGTHfunction is greater than the result of theCHAR_LENGTH()function. See the following example:12SET @str = CONVERT('MySQL Character Set' USING ucs2);SELECT LENGTH(@str), CHAR_LENGTH(@str);

TheCONVERTfunction converts a string into a specific character set. In this example, it converts the character set of theMySQL Character Setstring intoucs2. Becauseucs2character set contains 2-byte characters, therefore the length of the@strstring in bytes is greater than its length in characters.Notice that some character sets contain multi-byte characters, but their strings may contain only single-byte characters e.g.,utf8as shown in the following statements:12SET @str = CONVERT('MySQL Character Set' USING utf8);SELECT LENGTH(@str), CHAR_LENGTH(@str);

However, if autf8string contains special character e.g.,inpinginostring; its length in bytes is different, see the following example:12SET @str = CONVERT('pingino' USING utf8);SELECT LENGTH(@str), CHAR_LENGTH(@str);

Converting between different character setsMySQL provides two functions that allow you to convert strings between different character sets:CONVERTandCAST.We have used theCONVERTfunction several times in the above examples.The syntax of theCONVERTfunction is as follows:1CONVERT(expression USING character_set_name)

TheCASTfunction is similar to theCONVERTfunction. It converts a string to a different character set:1CAST(string AS character_type CHARACTER SET character_set_name)

Take a look at the following example of using theCASTfunction:1SELECT CAST(_latin1'MySQL character set' AS CHAR CHARACTER SET utf8);

Setting character sets for client connectionsWhen an application exchanges data with a MySQL database server, the default character set islatin1. However, if the database stores Unicode strings inutf8character set, usinglatin1character set in the application would not be sufficient. Therefore, the application needs to specify a proper character set when it connects to MySQL database server.To configure a character set for a client connection, you can do one of the following ways: Issue theSET NAMEstatement after the client connected to the MySQL database server. For example, to set a Unicode character setutf8, you use the following statement:1SET NAMES 'utf8';

If the application supports the--default-character-setoption, you can use it to set the character set. For example,mysqlclient tool supports--default-character-setand you can set it up in the configuration file as follows:12[mysql]default-character-set=utf8

Some MySQL connectors allow you to set character set, for example, if you use PHP PDO, you can set the character set in the data source name as follows:1$dsn ="mysql:host=$host;dbname=$db;charset=utf8";

Regardless of which way you use, make sure that the character set used by the application matches with the character set stored in the MySQL database server.In this tutorial, you have learned about MySQL character set, how to convert strings between character sets and how to configure proper character sets for client connections.

Home/Basic MySQL Tutorial/ MySQL CollationMySQL CollationSummary: in this tutorial, you will learn aboutMySQL collationand how to set character sets and collations for the MySQL server, database, table and column.Introduction to MySQL collationA MySQL collation is a set of rules used to compare characters in a particularcharacter set. Each character set in MySQL can have more than one collation, and has at least one default collation. Two character sets cannot have the same collation.MySQL provides you with theSHOW CHARACTER SETthat allows you to get the default collations of character sets as follows:1SHOW CHARACTER SET;

The values of the default collation column specify the default collations for the character sets.By convention, a collation for a character set begins with the character set name and ends with_ci(case insensitive)_cs(case sensitive) or_bin(binary).To get all collations for a given character set, you use theSHOW COLLATIONstatement as follows:1SHOW COLLATION LIKE 'character_set_name%';

For example, to get all collations for thelatin1character set, you use the following statement:1SHOW COLLATION LIKE 'latin1%';

MySQL Collations for latin1 Character SetAs mentioned above, each character set has at a default collation e.g.,latin1_swedish_ciis the default collation for thelatin1character set.Setting character sets and collationsMySQL allows you to specify character sets and collations at four levels: server, database, table, and column.Setting character sets and collations at server LevelNotice MySQL useslatin1as the default character set therefore its default collation islatin1_swedish_ci. You can change these settings at server startup.If you specify only a character set at server startup, MySQL will use the default collation of the character set. If you specify both a character set and a collation explicitly, MySQL will use the character set and collation for all databases created in the database server.The following statement sets the utf8 character set and utf8_unicode_cs collation for the server via command line:1>mysqld --character-set-server=utf8 --collation-server=utf8_unicode_ci

Setting character sets and collations at database levelWhen you create a database, if you do not specify its character set and collation, MySQL will use the default character set and collation of the server for the database.You can override the default settings at database level by usingCREATE DATABASEorALTER DATABASEstatement as follows:123CREATE DATABASE database_nameCHARACTER SET character_set_nameCOLLATE collation_name

123ALTER DATABASE database_nameCHARACTER SET character_set_nameCOLLATE collation_name

MySQL uses the character set and collation at database level for all tables created within the database.Setting character sets and collations at table levelA database may contain tables with character sets and collations that are different from the default databases character set and collation.You can specify the default character set and collation for a table when you create the table by using theCREATE TABLEstatement or when you alter the tables structure by using theALTER TABLEstatement.1234CREATE TABLE table_name()CHARACTER SET character_set_nameCOLLATE collation_name

1234ALTER TABLE table_name()CHARACTER SET character_set_nameCOLLATE collation_name

Setting character set and collation at column levelA column of typeCHAR,VARCHARorTEXTcan have its own character set and collation that is different from the default character set and collation of the table.You can specify a character set and a collation for the column in the columns definition of eitherCREATE TABLEorALTER TABLEstatement as follows:123column_name [CHAR | VARCHAR | TEXT] (length)CHARACTER SET character_set_nameCOLLATE collation_name

These are the rules for setting the character set and collation: If you specify both a character set and a collation explicitly, the character set and collation are used. If you specify a character set and omit the collation, the default collation of the character set is used. If you specify a collation without a character set, the character set associated with the collation is used. If you omit both character set and collation, the default character set and collation are used.Lets take a look at some examples of setting the character sets and collations.Examples of setting character sets and collationsFirst, we create a new database with utf8 as the character set and utf8_unicode_ci as the default collation:123CREATE DATABASE mydbdemoCHARACTER SET utf8COLLATE utf8_unicode_ci;

Because we specify the character set and collation for themydbdemodatabase explicitly, themydbdemodoes not take the default character set and collation at server level.Second, we create a new table namedt1in themydbdemodatabase:1234USE mydbdemo;CREATE TABLE t1(c1 char(25));

We did not specify the character set and collation for thet1table; MySQL will check the database level to determine the character set and collation for thet1table. In this case, thet1table hasutf8as the default character set andutf8_unicode_cias the default collation.Third, for thet1table, we change its character set tolatin1and its collation tolatin1_german1_ci:123ALTER TABLE t1CHARACTER SET latin1COLLATE latin1_german1_ci;

Thec1column in thet1table haslatin1as the character set andlatin1_german1_cias the collation.Fourth, lets change the character set of thec1column tolatin1:123ALTER TABLE t2MODIFY c1 VARCHAR(25)CHARACTER SET latin1;

Now, thec1column haslatin2character set, but what about its collation? Is it inheriting thelatin1_german1_cicollation from the tables collation? No, because the default collation of thelatin1character set islatin1_swedish_ci, thec1column haslatin1_swedish_cicollation.In this tutorial, you have learned about MySQL collation and how to specify character sets and collations for MySQL serer, databases, tables and columns.

Principio del formularioIntroduccin a SQL gatilloResumen:En este tutorial, se le dar una breve descripcin degatillo SQL, sus ventajas y desventajas.Un disparador SQL es un conjunto de sentencias SQL almacenadas en el catlogo de base de datos.Un disparador SQL se ejecuta o desencadena siempre un evento asociado a una mesa se produce, por ejemplo, insertar, actualizar o borrar.Un disparador SQL es un tipo especial deprocedimiento almacenado.Es especial porque no se conoce directamente como un procedimiento almacenado.La principal diferencia entre un gatillo y un procedimiento almacenado es un disparador que se llama automticamente cuando un evento de modificacin de datos se realiza contra una mesa, mientras que un procedimiento almacenado se debe llamar explcitamente.Es importante comprender las ventajas y desventajas de SQL gatillo para que pueda usarla como corresponde.En las secciones siguientes, vamos a discutir sobre las ventajas y desventajas del uso de los factores desencadenantes de SQL.Ventajas del uso de los factores desencadenantes de SQL SQL desencadena proporcionar una forma alternativa para comprobar la integridad de los datos. Desencadenantes SQL pueden detectar errores en la lgica de negocio en la capa de base de datos. SQL desencadena proporcionar una forma alternativa para ejecutar tareas programadas.Mediante el uso de los factores desencadenantes de SQL, usted no tiene que esperar para ejecutar las tareas programadas debido a que los factores desencadenantes son invocados automticamenteantesodespus deque se haga un cambio en los datos de las tablas. Desencadenantes SQL son muy tiles para auditar los cambios de datos en tablas.Desventajas de usar disparadores SQL SQL se dispara slo puede proporcionar una validacin extendida y no puede sustituir a todas las validaciones.Algunas validaciones simples tienen que ser hechas en la capa de aplicacin.Por ejemplo, puede validar las entradas del usuario en el lado del cliente mediante el uso de JavaScript o en el lado del servidor utilizando lenguajes de script del lado del servidor, como JSP, PHP, ASP.NET, Perl, etc. Desencadenantes SQL se invocan y ejecutados de forma invisible de clientes-aplicaciones, por lo tanto es difcil de averiguar lo que sucede en la capa de base de datos. Desencadenantes SQL pueden aumentar la sobrecarga del servidor de base de datos.Los disparadores oprocedimientos almacenados?Se recomienda que si usted no tiene ninguna manera de conseguir el trabajo hecho conprocedimiento almacenado, piense gatillo SQL.Inicio/disparadores MySQL/ MySQL desencadenantes ImplementacinMySQL Implementacin de triggersResumen: En este tutorial, usted aprender acerca deMySQL desencadenaaplicacin.Adems, vamos a mostrar cmo MySQL almacena desencadenan definiciones y las limitaciones de los disparadores en MySQL.Introduccin a los factores desencadenantes de MySQLEn MySQL, un disparador es un conjunto de sentencias SQL que se invoca automticamente cuando se realiza un cambio en los datos de la tabla asociada.Un disparador se puede definir a invocar ya sea antes o despus de los datos se cambia porINSERT,ACTUALIZACINoBORRARdeclaraciones.MySQL le permite definir un mximo de seis disparadores para cada tabla. ANTES DE INSERTAR- activado antes de introducir datos en la tabla. DESPUS INSERT- activado despus de datos se insertan en la tabla. ACTUALIZACIN ANTES- activado antes de los datos de la tabla se actualiza. DESPUS DE ACTUALIZACIN- activado despus de datos de la tabla se actualiza. ANTES DE BORRAR- activa antes de extraer datos de la tabla. DESPUS DE ELIMINAR- activa despus de los datos se elimina de la tabla.Cuando se utiliza una instruccin que hace que el cambio de la mesa, pero no usaINSERT,DELETEoACTUALIZACINdeclaracin, no se invoca el gatillo.Por ejemplo, elTRUNCATEdeclaracin elimina toda la informacin de una tabla pero no invoca el gatillo asociado a esa tabla.Hay algunos estados que utilizan elINSERTdeclaracin detrs de las escenas comoREEMPLAZARdeclaracin yCARGA DE DATOScomunicado.Si utiliza estas declaraciones, se invocarn los activadores correspondientes asociados a las mesas, si disponibles.Los disparadores definidos por una mesa deben tener un nombre nico.Usted puede tener el mismo nombre que define gatillo para diferentes mesas pero no es recomendable.En la prctica, los nombres de los desencadenantes siguen la siguiente convencin de nomenclatura:1(BEFORE | AFTER)_tableName_(INSERT| UPDATE | DELETE)

MySQL disparadores AlmacenamientoMySQL almacena desencadena en un directorio de datos, por ejemplo,/ data / classicmodels /con los archivos llamadostablename.TRGytriggername.TRN: Eltablename.TRGarchivo de los mapas del gatillo para la tabla correspondiente. latriggername.TRNarchivo contiene la definicin de un disparador.Puede copia de seguridad de los factores desencadenantes de MySQL copiando los archivos de activacin a la carpeta de copia de seguridad.Tambin puede copia de seguridad de los disparadores utilizando elmysqldumpherramienta.MySQL desencadenantes LimitacionesDisparadores MySQL no tienen todas las caractersticas de SQL estndar sin embargo, hay algunas limitaciones que usted debe saber antes de utilizarlos en sus aplicaciones.Disparadores de MySQL no puede: UsoDEMOSTRACIN,carga de datos,TABLA DE CARGA,BACKUP DATABASE,RESTORE,FLUSHyRETURNdeclaraciones. Utilice declaraciones que confirmar o deshacer, implcita o explcitamente, comoCOMMIT,ROLLBACK,iniciar la transaccin,MESAS LOCK / UNLOCK,ALTER,CREATE,DROP,RENAME, etc. Utilicelas sentencias preparadascomoPREPARE,EXECUTE, etc. Utilice sentencias de SQL dinmico. Llamar a unprocedimiento almacenadoo una funcin almacenada.En este tutorial, le hemos mostrado cmo se implementan los disparadores en MySQL.Tambin discutimos sobre el almacenamiento de gatillo, as como las limitaciones del gatillo en MySQL.Inicio/disparadores MySQL/ Crear gatillo en MySQL

Crear trigger en MySQLResumen: En este tutorial, aprenders cmo creargatillo en MySQLutilizando elCREATE TRIGGERcomunicado.Usted debe seguir laintroduccin a los factores desencadenantes de SQLy taplicacin aparejador en MySQLprimero antes de seguir adelante con este tutorial.Sintaxis trigger MySQLCon el fin de crear un disparador se utiliza elCREATE TRIGGERcomunicado.A continuacin se muestra la sintaxis de laCREATE TRIGGERdeclaracin:123456CREATE TRIGGER trigger_name trigger_time trigger_event ON table_name FOR EACH ROW BEGIN ... END

Vamos a examinar la sintaxis anterior con ms detalle. Usted pone el nombre del disparador despus delCREATE TRIGGERcomunicado.El nombre del disparador debe seguir la convencin de nombres[Tiempo de disparo] _ [nombre de la tabla] _ [evento de disparo], por ejemplobefore_employees_update. Tiempo de activacin del disparador puede serANTESoDESPUES.Debe especificar el tiempo de activacin cuando se define un disparador.UtilizaANTESpalabra clave si desea procesar la accin antes del cambio se hace en la mesa yDESPUSsi necesita procesar accin despus de realizar el cambio. Evento de disparo puede serINSERT,ACTUALIZACINoDELETE.Este evento causas provocan que se invoca.Un disparador slo puede ser invocada por un evento.Para definir un disparador que se invoca por mltiples eventos, usted tiene que definir mltiples desencadenantes, uno para cada evento. Un disparador debe estar asociada con una tabla especfica.Sin un disparador mesa no existira, por tanto, tiene que especificar el nombre de la tabla despus de laENpalabra clave. Las sentencias de SQL se colocan entreCOMIENZOyFINbloque. LosOLDyNEWpalabras clave son muy tiles.ElVIEJOpalabra clave se refiere al registro existente antes de cambiar los datos y laNUEVApalabra clave se refiere a la nueva fila despus de cambiar los datos.Ejemplo trigger MySQLVamos a empezar creando un disparador en MySQL para auditar los cambios delos empleadosmesa.En primer lugar, tenemosempleadostabla en nuestrabase de datos MySQL de muestrade la siguiente manera:

En segundo lugar, creamos una nueva tabla denominadaemployees_auditmantener los cambios de los registros de los empleados.La siguiente secuencia de comandos crea elemployee_auditmesa.12345678 CREATE TABLE employees_audit ( id int(11) NOT NULL AUTO_INCREMENT, employeeNumber int(11) NOT NULL, lastname varchar(50) NOT NULL, changedon datetime DEFAULT NULL, action varchar(50) DEFAULT NULL, PRIMARY KEY (id) )

En tercer lugar, creamos unaACTUALIZACIN ANTESgatillo para ser invocado antes de que se realiza un cambio en elempleadosmesa.123456789101112DELIMITER $$CREATE TRIGGER before_employee_update BEFORE UPDATE ON employeesFOR EACH ROW BEGININSERT INTO employees_auditSET action = 'update', employeeNumber = OLD.employeeNumber,lastname = OLD.lastname,changedon = NOW(); END$$DELIMITER ;

Si usted echa un vistazo a el esquema, verbefore_employee_updategatillo bajo elempleadostabla de la siguiente man