Tuesday, 23 August 2016

10 Most Popular Amazon AWS Storage and Database Services

If you are new to Amazon AWS, and looking at their offerings, it can be bit confusing, as they have lot of services.
If you are just looking to launch a virtual server on the cloud, it is relatively straight forward, and you can use Amazon’s EC2 service.
But, when it comes to storage and database for your virtual instance on the cloud, Amazon has multiple choices.
In this tutorial, we have listed the most popular storage and database services available from Amazon.

1. Amazon S3

  • Amazon S3 stands for SSS, which is Simple Storage Service.
  • This is an object storage. You can store any kind of files in S3.
  • The individual file size can be from 0 bytes to 5 TB.
  • For simple S3 file management, you can use Amazon S3 web interface.
  • For enterprise applications, you can use the REST APIs provided by Amazon from your application code to manage the files that are stored in S3.
  • In S3, amazon has the concept of buckets, and you can put multiple objects in a bucket.
  • For security, you can assign permissions at both bucket level and object level. You can also assign permission at user level.
  • One nice feature that S3 provides is that if you have a static website, you can just host it on Amazon S3. In that case, not only it stores your html file in S3 buckets, it will also indirectly act as webserver and serve your html content.
  • You can also enable versioning for objects that are stored in S3 buckets.

2. Amazon Glacier

  • Amazon Glacier is for archival purpose. Use this only on situations where you don’t want to retrieve the data frequently. For example, you can store backups in Glacier.
  • The storage cost of Glacier is way too less when compared to S3. But, you won’t be able to get to your data quickly, as the data retrieval process will take hours in glacier.
  • Glaicer is tightly integrated with S3 buckets, which is great when you want to move old data from S3 to Glacier for cost saving.
  • In S3, you can setup lifecycle management, and automatically move files that are older than X number of days from S3 to Glacier.
  • Similar to buckets in S3, in Glacier, you’ll create vaults to store the data. You can assign permissions on Vaults to restrict access.
  • For your enterprise data, you can use the REST API from your application to archive your data directly to Glacier. Glacier also provides API interface for Java and .NET SDK.
  • Keep in mind that while storage cost is very less in Glacier, there is a separate cost associated for data retrival.

3. Amazon EBS

  • Amazon EBS stands for Elastic Block Store. This is a block level storage that can be attached to the EC2 instance that you’ll spin-up in AWS.
  • One of the great advantages of EBS is that you can move it around from one EC2 instance to another EC2 instance without losing the data that is stored on the EBS.
  • There are three types of EBS storage:
    1. Magnetic volumes with maximum 40 MiB/s throughput; use this for low IO requirement applications
    2. General Purpose SSD with 160 MiB/s; use this for most database applications that requires good IO performance
    3. Provisioned IOPS SSD with 320 MiB/s; use this business critical application that requires heavy IO operations.
  • You can take backup (snapshot) of your EBS volume and store it directly on S3.
  • Amazon also provides the option of creating encyrpted EBS option, which is helpful when you want to encrypt your data at rest.
  • These EBS volumes can be exposed to your operating system which can be mounted appropriately. For example, on Linux EC2 instnace, it can be /dev/sdb (or /dev/xvdb), and on Windows it can be C: or D: drive.
  • You can also setup RAID on EC2 instance using EBS volumes.

4. EC2 Instance Store

  • Amazon EC2 Instance Store will use the disk that is directly attached to the host where the current EC2 instance is running.
  • But, be very careful when using an instance store, as this is a temporary storage.
  • Any data stored in the instance store will be lost when you restart the instance, or when an instance crashes for whatever reason.
  • You cannot detach an instance store and move it to another instance.
  • The size of the instance store volume that you can create depends on the instance type. For example, in m1.small, you can create a instance store volume of 160GB.
  • Some of the instance type (for example: C3, G2, HI1, I2, M3, and R) supports SSD instance storage.
  • Again, instance store is different than EBS. Use instance store only to store some temporary data that you can afford to lose.

5. AWS Storage Gateway

  • For most enterprise application, you’ll probably already have some kind of storage solution on your site.
  • In that case, using AWS storage gateway, you can connect your on-site storage infrastructure with AWS storage services using the gateway.
  • For this, you should install the AWS storage gateway software application, which comes as a VM in your datacenter.
  • Once this is connected to the AWS, from the AWS console, you can create three types of storage gateway volumes and mount it on the server in your datacenter:
    1. Gateway-cached volumes: This will use S3 to store your primary data, while keeping a copy of the frequently used data locally in your datacenter
    2. Gateway-Stored volumes: This will store the primary data locally in your datacenter, and in parallel it will backup the data to AWS S3 in the form of EBS snapshot.
    3. Gateway-Virtual Tape Library: This will replace your local physical tape library with virtual tape library using Amazon S3 storage of Glacier.

6. Amazon RDS

  • Amazon RDS stands for Relational Database Service. In RDS you’ll create a DB instance with a specific database, and select the type of compute and storage options based on your requirement.
  • The DB instance can be any of the most popular databases: MySQL, MariaDB, Oracle, SQL Server, PostgreSQL, or Aurora.
  • What RDS does is that it will automatically install the database, configure it, and perform the routine DB maintenance tasks like backup and patch applying.
  • You can manage your DB instance from the AWS management console.
  • The advantange of using RDS is that you don’t need to be a DBA to successfully run your enterprise application on a database.

7. DynamoDB

  • DynamoDB is Amazon’s version of NoSQL database (Similar to MongoDB).
  • DynamoDB also provides an option for users to download and install local copy on your server during your application and testing phase. When you are ready for deployment, you can move it to the Amazon DynamoDB environment.
  • AWS SDKs allow developers to access DynamoDB and manipulate the data from various programming languages including Java, .NET and PHP.
  • From the AWS management console, you can create DynamoDB tables, load data, create queries, and perform all typical NoSQL operations from the GUI directly.

8. Amazon SQS

  • Amazon SQS stands for Simple Queue Service.
  • This is a fully managed message queue service from Amazon.
  • Using SQS you can move your data or messages between different applications without having the applications to be always up and running.
  • SQS can be used to send messages between multiple AWS services including S3, EC2, DynamoDB. You can also use Java Message Services with SQS.
  • Using SQS, you can configure Dead Letter Queues, first-in-first-out (FIFO) access for your messages, etc.
  • The maximum visibility timeout for a message in the SQS queue is 12 hours.

9. ElastiCache

  • ElastiCache is Amazon’s in-memory caching system on the cloud. Currently this supports both Memcached and Redis.
  • Using this you’ll improve the application performance by caching I/O and CPU intensive queries in the memory for faster results.
  • When you are using ElastiCache, it is completely integrated with all other AWS services such as Amazon RDS, EC2, etc. Just like other AWS services, you can manage ElasticCache from both management console UI or using API.
  • You can also run ElastiCache cluster in your Amazon VPC (Virtual Private Cloud).

10. Amazon RedShift

  • Amazon RedShift is a fully managed data warehouse solution for your enterprise business intelligence application.
  • Redshift provides access to your structured data from your own existing SQL-based clients by using either JDBC or ODBC.
  • When a huge query is executed on Redshift, it is distributed among multiple nodes for parallel operations.
  • Depending on your needs, you can control how many number of nodes you want in your RedShift. The number of nodes can be dynamically controlled from an API call depending on a particular query that you are planning to execute.
  • There are three advantages of RedShift:
    1. Column Data Storage; instead of storing your data in rows, it stores it by columns. Column-based systems are faster for data warehouse solutions
    2. Advanced compression; Similar data are stored sequentially in disk by using automatic advanced compression technique for faster data retrieval
    3. Massive Parallel Processing; Data and queries are distributed across multiple nodes for faster processing. The number of nodes can be easily controlled.

25 Essential MySQL Select Command Examples

Essential MySQL Select Command Examples

If you are using MySQL database, it is essential that you become comfortable with mysql command line.
In this tutorial we’ll explain how to use the MySQL select command with several practical examples.

1. Basic Select command Example

First, to connect to MySQL command line, do the following from your operating system prompt.
# mysql -u root -p
Password:
Next, view all available databases.
mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| thegeekstuff       |
| crm                |
| bugzilla           |
+--------------------+
8 rows in set (0.00 sec)
Use the database where you want to work on. In this example, I’m selecting “thegeekstuff” database, where the “employee” table is located, which is used as an example for all the select commands explained in this article.
mysql> USE thegeekstuff;
Database changed

mysql> DESC employee;
The basic usage of select command is to view rows from a table. The following select command example will display all the rows from the “employee” table.
mysql> SELECT * FROM employee;
+-----+--------+------------+--------+
| id  | name   | dept       | salary |
+-----+--------+------------+--------+
| 100 | Thomas | Sales      |   5000 |
| 200 | Jason  | Technology |   5500 |
| 300 | Sanjay | Technology |   7000 |
| 400 | Nisha  | Marketing  |   9500 |
| 500 | Randy  | Technology |   6000 |
| 501 | Ritu   | Accounting |   NULL |
+-----+--------+------------+--------+
6 rows in set (0.01 sec)
Or, select specific columns by specifying the column names (Instead of * which will give all columns).
mysql> SELECT name, salary FROM employee;
+--------+--------+
| name   | salary |
+--------+--------+
| Thomas |   5000 |
| Jason  |   5500 |
| Sanjay |   7000 |
| Nisha  |   9500 |
| Randy  |   6000 |
| Ritu   |   NULL |
+--------+--------+
6 rows in set (0.00 sec)

2. Select from Dual – Virtual Table

dual is a virtual table. This really doesn’t exist. But, you can use this table to perform some non-table activities.
For example, you can use select on dual table to perform arithmetic operations as shown below.
mysql> SELECT 2+3 FROM DUAL;
+-----+
| 2+3 |
+-----+
|   5 |
+-----+
1 row in set (0.00 sec)
You can also use dual table to view the current date and time. The now() function in MySQL is similar to the sysdate() function in Oracle database.
mysql> SELECT NOW() FROM DUAL;
+---------------------+
| now()               |
+---------------------+
| 2013-09-14 09:15:35 |
+---------------------+
1 row in set (0.00 sec)
When you don’t specify any table, MySQL will assume that you want to use dual. The following example are exactly same as the above. Just to avoid confusion, I recommend that you use “from dual” in these situation for better readability and clarity.
mysql> SELECT 2+3;
+-----+
| 2+3 |
+-----+
|   5 |
+-----+
1 row in set (0.00 sec)

mysql> SELECT NOW();
+---------------------+
| now()               |
+---------------------+
| 2013-09-14 09:16:45 |
+---------------------+
1 row in set (0.00 sec)

3. Basic WHERE Condition to Restrict Records

Instead of display all the records from a table, you can also use WHERE condition to view only recrods that matches a specific condition as shown below.
mysql> SELECT * FROM employee WHERE salary > 6000;
+-----+--------+------------+--------+
| id  | name   | dept       | salary |
+-----+--------+------------+--------+
| 300 | Sanjay | Technology |   7000 |
| 400 | Nisha  | Marketing  |   9500 |
+-----+--------+------------+--------+
2 rows in set (0.00 sec)
Similar to “greater than >” you can also use “less than=”, “not equal to !=” as shown below.
mysql> SELECT * FROM employee WHERE salary < 6000; mysql> SELECT * FROM employee WHERE salary  SELECT * FROM employee WHERE salary >= 6000;

mysql> SELECT * FROM employee WHERE salary = 6000;

mysql> SELECT * FROM employee WHERE salary != 6000;

4. Match Strings in WHERE Condition

The previous example displays how to restrict records based on numerical conditions. This example explains how to restrict records based on string values.
The exact match of strings works like numeric match using “equal to =” as shown below. This example will display all employees who belong to Technology department.
mysql> SELECT * FROM employee WHERE dept = 'Technology';
+-----+--------+------------+--------+
| id  | name   | dept       | salary |
+-----+--------+------------+--------+
| 200 | Jason  | Technology |   5500 |
| 300 | Sanjay | Technology |   7000 |
| 500 | Randy  | Technology |   6000 |
+-----+--------+------------+--------+
3 rows in set (0.00 sec)
Please note that this is case insensitive comparison. So, the following is exactly the same as above select command.
mysql> SELECT * FROM employee WHERE dept = 'TECHNOLOGY';
You can also use != to display all the employee who does not belong to Technology department as shown below.
mysql> SELECT * FROM employee WHERE dept != 'TECHNOLOGY';
You can also perform partial string match using % in the keywords. The following will display all employees whos last name begins with “John”.
mysql> SELECT * FROM employee WHERE name LIKE 'JOHN%';
The following will display all employees whos name ends with “Smith”.
mysql> SELECT * FROM employee WHERE name LIKE '%SMITH';
You can also give % at both beginning and end. In which case, it will search for the given keyword anywhere in the string. The following will display all employees who contain “John” in their name anywhere.
mysql> SELECT * FROM employee WHERE name LIKE '%JOHN%';

5. Combine WHERE Conditions Using OR, AND

You can also use OR, AND, NOT in WHERE condition to combine multiple conditions. The following example displays all employees who are in “Technology” department AND with salary >= 6000. This will display records only when both the conditions are met.
mysql> SELECT * FROM employee WHERE dept = 'TECHNOLOGY' AND salary >= 6000;
+-----+--------+------------+--------+
| id  | name   | dept       | salary |
+-----+--------+------------+--------+
| 300 | Sanjay | Technology |   7000 |
| 500 | Randy  | Technology |   6000 |
+-----+--------+------------+--------+
2 rows in set (0.00 sec)
The following is same as above, but uses OR condition. So, this will display records as long as any one of the condition matches.
mysql> SELECT * FROM employee WHERE dept = 'TECHNOLOGY' OR salary >= 6000;
+-----+--------+------------+--------+
| id  | name   | dept       | salary |
+-----+--------+------------+--------+
| 200 | Jason  | Technology |   5500 |
| 300 | Sanjay | Technology |   7000 |
| 400 | Nisha  | Marketing  |   9500 |
| 500 | Randy  | Technology |   6000 |
+-----+--------+------------+--------+
4 rows in set (0.00 sec)

6. Combine column values using CONCAT in select

You can use CONCAT function in select commanda to combine values from multiple columns and display it. The following example combines name and department field (for display only) as shown below.
mysql> SELECT ID, CONCAT(NAME, ' FROM ', DEPT) AS NAME, SALARY FROM employee;
+-----+------------------------+--------+
| id  | name                   | salary |
+-----+------------------------+--------+
| 100 | Thomas from Sales      |   5000 |
| 200 | Jason from Technology  |   5500 |
| 300 | Sanjay from Technology |   7000 |
| 400 | Nisha from Marketing   |   9500 |
| 500 | Randy from Technology  |   6000 |
| 501 | Ritu from Accounting   |   NULL |
+-----+------------------------+--------+
6 rows in set (0.00 sec)

7. Count Total Number of Records

Use count(*) in select command to display the total number of records in a table.
mysql> SELECT COUNT(*) FROM employee;
+----------+
| count(*) |
+----------+
|        6 |
+----------+
1 row in set (0.00 sec)

8. Group By in Select Command

Group By commands will group records based on certain conditions. The following example displays the total number of employees in every department.
mysql> SELECT DEPT, COUNT(*) FROM employee GROUP BY DEPT;
+------------+----------+
| dept       | count(*) |
+------------+----------+
| Accounting |        1 |
| Marketing  |        1 |
| Sales      |        1 |
| Technology |        3 |
+------------+----------+
4 rows in set (0.00 sec)
Please note that when you use GROUP BY, you can use certain functions to get more meaningful output. IN the above example, we’ve used count(*) group by commands. Similarly you can use sum(), avg(), etc, when you specify GROUP BY.

9. Use HAVING along with GROUP BY

When you use GROUP BY, you can also use HAVING to restrict the records further.
In the following example, it displays only the departments where the number of employee is more than 1.
mysql> SELECT COUNT(*) AS CNT, DEPT FROM employee GROUP BY DEPT HAVING CNT > 1;
+-----+------------+
| CNT | dept       |
+-----+------------+
|   3 | Technology |
+-----+------------+
1 row in set (0.00 sec)

10. Define Alias using ‘AS’ Keyword

Instead of display the column name as specified in the table, you can use your own name in the display using AS keyword.
In the following example, even though the real column name is ID, it is displayed as EMPID.
mysql> SELECT ID AS EMPID, NAME AS EMPNAME, DEPT AS DEPARTMENT FROM employee;
+-------+---------+------------+
| EMPID | EMPNAME | DEPARTMENT |
+-------+---------+------------+
|   100 | Thomas  | Sales      |
|   200 | Jason   | Technology |
|   300 | Sanjay  | Technology |
|   400 | Nisha   | Marketing  |
|   500 | Randy   | Technology |
|   501 | Ritu    | Accounting |
+-------+---------+------------+
6 rows in set (0.00 sec)
Please note that the AS keyword is optional. The following example is exactly the same as the above.
mysql> SELECT id empid, name empname, dept department FROM employee;

11. Left Join in SELECT command

In the following example, the select command combines two tables. i.e employee and department. For combining these, it uses the common column between these two tables dept. The “Location” column shown in the output is from the department table.
mysql> SELECT employee.*, department.location FROM employee LEFT JOIN department ON ( employee.dept = department.dept );
+-----+--------+------------+--------+----------+
| id  | name   | dept       | salary | Location |
+-----+--------+------------+--------+----------+
| 100 | Thomas | Sales      |   5000 | USA      |
| 200 | Jason  | Technology |   5500 | USA      |
| 300 | Sanjay | Technology |   7000 | India    |
| 400 | Nisha  | Marketing  |   9500 | India    |
| 500 | Randy  | Technology |   6000 | UK       |
| 501 | Ritu   | Accounting |   NULL | USA      |
+-----+--------+------------+--------+----------+
You can also use table alias name in the JOIN command as shown below. In this example, I’ve used “E” as alias for employee table, and “D” as alias for department table. This makes the select command smaller and easier to read.
mysql> SELECT E.*, d.location FROM employee AS E LEFT JOIN department AS D ON ( e.dept = d.dept );
Note: Join itself is a huge topic, which we will discuss in detail as a separate tutorial.

12. Performance Analysis using EXPLAIN

When your select query is slow, or behaving in a way you don’t understand, use the EXPLAIN command, which will display additional details that MySQL is using internally to execute the query. This might give you some insight on the performance of your MySQL select command.
mysql> EXPLAIN SELECT E.*, D.LOCATION FROM employee AS E LEFT JOIN DEPARTMENT AS D ON ( E.DEPT = D.DEPT );
+----+-------------+-------+--------+---------------+---------+---------+-----------------+------+-------+
| id | select_type | table | type   | possible_keys | key     | key_len | ref             | rows | Extra |
+----+-------------+-------+--------+---------------+---------+---------+-----------------+------+-------+
|  1 | SIMPLE      | PS    | ALL    | NULL          | NULL    | NULL    | NULL            |    6 |       |
|  1 | SIMPLE      | P     | eq_ref | PRIMARY       | PRIMARY | 3       | acme.E.dept     |    1 |       |
+----+-------------+-------+--------+---------------+---------+---------+-----------------+------+-------+
2 rows in set (0.00 sec)

13. Force Select Query to use an INDEX

While executing a select query, and joining two tables, MySQL will decide how to use any available Indexes on the tables effectively. The following are few ways of dealing with indexes in SELECT command.
  • USE INDEX (list_of_indexes) – This will use one of the indexes specified to query the records from the table.
  • IGNORE INDEX (list_of_indexes) – This will use the indexes specified to query the records from the table.
  • FORCE INDEX (index_name) – This will force MySQL to use the given index even when MySQL thinks a better and faster way of querying the records are available.
Before you decide to use any one of the above, you should really understand the impact of these commands, as if you don’t use these properly, it will slow down your select command.
The following examples forces MySQL to use the employee_emp_nm_idx for this query.
mysql> SELECT * FROM employee FORCE INDEX (EMPLOYEE_EMP_NM_IDX) WHERE NAME LIKE 'JOHN%';
To display all available indexes on a particular table, use the “show index” command. The following example displays all indexes available on employee table.
mysql> SHOW INDEX FROM PROFILES;
+----------+------------+-------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| Table    | Non_unique | Key_name                | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
+----------+------------+-------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| employee |          0 | PRIMARY                 |            1 | id          | A         |         156 |     NULL | NULL   |      | BTREE      |         |
| employee |          0 | employee_emp_nm_idx     |            1 | name        | A         |         156 |     NULL | NULL   |      | BTREE      |         |
+----------+------------+-------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+

14. Sort Records using ORDER BY

Note: desc will short by descending. If you don’t give anything, it is ascending.
The following records will order the records in alphabetical order based on dept column.
mysql> SELECT * FROM employee ORDER BY DEPT;
+-----+--------+------------+--------+
| id  | name   | dept       | salary |
+-----+--------+------------+--------+
| 501 | Ritu   | Accounting |   NULL |
| 400 | Nisha  | Marketing  |   9500 |
| 100 | Thomas | Sales      |   5000 |
| 200 | Jason  | Technology |   5500 |
| 300 | Sanjay | Technology |   7000 |
| 500 | Randy  | Technology |   6000 |
+-----+--------+------------+--------+
6 rows in set (0.01 sec)
Please note that by default it will sort by ascending order. If you want to sort by descending order, specify the keyword “DESC” after “ORDER BY” as shown below.
mysql> SELECT * FROM employee ORDER BY DEPT DESC;
+-----+--------+------------+--------+
| id  | name   | dept       | salary |
+-----+--------+------------+--------+
| 200 | Jason  | Technology |   5500 |
| 300 | Sanjay | Technology |   7000 |
| 500 | Randy  | Technology |   6000 |
| 100 | Thomas | Sales      |   5000 |
| 400 | Nisha  | Marketing  |   9500 |
| 501 | Ritu   | Accounting |   NULL |
+-----+--------+------------+--------+
6 rows in set (0.00 sec)
You can also order by multiple columns as shown below.
mysql> SELECT * FROM employee ORDER BY DEPT, SALARY DESC;

15. Limit the Number of Records

Instead of displaying all the records you can just limit how many records mysql should display using the LIMIT as shown below.
Limit format:
LIMIT start_record, number_of_records
The following example will start from record number 0 (which is the 1st record), and display 3 records from there.
mysql> SELECT * FROM employee LIMIT 0,3;
+-----+--------+------------+--------+
| id  | name   | dept       | salary |
+-----+--------+------------+--------+
| 100 | Thomas | Sales      |   5000 |
| 200 | Jason  | Technology |   5500 |
| 300 | Sanjay | Technology |   7000 |
+-----+--------+------------+--------+
3 rows in set (0.00 sec)
The following will start from record number 1 (which is the 2nd record), and display 3 records from there.
mysql> SELECT * FROM employee LIMIT 1,3;
+-----+--------+------------+--------+
| id  | name   | dept       | salary |
+-----+--------+------------+--------+
| 200 | Jason  | Technology |   5500 |
| 300 | Sanjay | Technology |   7000 |
| 400 | Nisha  | Marketing  |   9500 |
+-----+--------+------------+--------+
3 rows in set (0.00 sec)
You can also omit the start_record, in which case, it will always start from record number 0 (i.e first record).
In the following example, we’ve specified only one value. So, this will start from record number 0, and display 3 records from there.
mysql> SELECT * FROM employee LIMIT 3;
+-----+--------+------------+--------+
| id  | name   | dept       | salary |
+-----+--------+------------+--------+
| 100 | Thomas | Sales      |   5000 |
| 200 | Jason  | Technology |   5500 |
| 300 | Sanjay | Technology |   7000 |
+-----+--------+------------+--------+
3 rows in set (0.00 sec)

16. Limit the Number of Records with OFFSET

Limit OFFSET format:
LIMIT number_of_records OFFSET start_record
You can also use the keyword OFFSET, where you’ll specify the start record after the keyword OFFSET.
The following will display total of 3 records. Since the offset is specified as 1, it will start from the 2nd record.
mysql> SELECT * FROM employee LIMIT 3 OFFSET 1
+-----+--------+------------+--------+
| id  | name   | dept       | salary |
+-----+--------+------------+--------+
| 200 | Jason  | Technology |   5500 |
| 300 | Sanjay | Technology |   7000 |
| 400 | Nisha  | Marketing  |   9500 |
+-----+--------+------------+--------+
3 rows in set (0.00 sec)

17. Get Unique Values from a Column

To display all unique values from a column, use DISTINCT.
The following example will display all the unique dept values from the employee table.
mysql> SELECT DISTINCT DEPT FROM employee;
+------------+
| dept       |
+------------+
| Sales      |
| Technology |
| Marketing  |
| Accounting |
+------------+

18. Sum of all Values in a Column

To add all the values from a column, use SUM() function.
The following example will display the sum of salary column for all the employees who belong to Technology department.
mysql> SELECT SUM(SALARY) FROM employee WHERE DEPT = 'TECHNOLOGY';
+-------------+
| sum(salary) |
+-------------+
|       18500 |
+-------------+
1 row in set (0.01 sec)

19. Average of all Values in a Column

To average all the values from a column, use AVG() function.
The following example will display the average salary of each and every department. This combines GROUP BY with AVG() function.
mysql> SELECT DEPT,AVG(SALARY) FROM employee GROUP BY DEPT;
+------------+-------------+
| dept       | avg(salary) |
+------------+-------------+
| Accounting |        NULL |
| Marketing  |   9500.0000 |
| Sales      |   5000.0000 |
| Technology |   6166.6667 |
+------------+-------------+
4 rows in set (0.03 sec)

20. SELECT within SELECT command

The example shown below is very lame. There is no reason to do it this way. But, this shows you how you can use select command. In this example the “AS ACTION” gives an alias name to the select subquery. You need to specify an alias in this example. The “ACTION” is just a name. You can change this to anything you like.
mysql> SELECT * FROM (SELECT * FROM employee) AS ACTION WHERE ID

21. Save the Select Output to a File

Using SELECT INTO, you can save the output of a select command into a file.
Instead of displaying the output on the screen, the following select command example will store the output of the select command into the /tmp/employee.txt file.
mysql> SELECT * INTO OUTFILE '/tmp/employee.txt' FROM employee;
Query OK, 6 rows affected (0.00 sec)

# cat /tmp/employee.txt
100     Thomas  Sales   5000
200     Jason   Technology      5500
300     Sanjay  Technology      7000
400     Nisha   Marketing       9500
500     Randy   Technology      6000
501     Ritu    Accounting      \N
You can also store the output into a comma delimited file by specifying the “FIELDS TERMINATED BY” as shown in the example below.
mysql> SELECT * INTO OUTFILE '/tmp/employee1.txt'   FIELDS TERMINATED BY ',' FROM employee;
Query OK, 6 rows affected (0.00 sec)

# cat /tmp/employee1.txt
100,Thomas,Sales,5000
200,Jason,Technology,5500
300,Sanjay,Technology,7000
400,Nisha,Marketing,9500
500,Randy,Technology,6000
501,Ritu,Accounting,\N

22. Execute a Procedure on the Data Set

You can also call a MySQL procedure that will process the data from the output of the select command.
The following example will execute the procedure salary_report() on the output of the given select command.
mysql> SELECT ID, SALARY FROM employee PROCEDURE SALARY_REPORT();

23. Display a Random Record from a table

Using the rand command you can display a random record from a table. This can be helpful in situations similar to where you are displaying some random tip of the day from a table.
mysql> SELECT * FROM employee ORDER BY RAND() LIMIT 1;
+-----+-------+------------+--------+
| id  | name  | dept       | salary |
+-----+-------+------------+--------+
| 200 | Jason | Technology |   5500 |
+-----+-------+------------+--------+
1 row in set (0.00 sec)
The same command executed next time, will give a different record as shown below.
mysql> SELECT * FROM employee ORDER BY RAND() LIMIT 1;
+-----+--------+-------+--------+
| id  | name   | dept  | salary |
+-----+--------+-------+--------+
| 100 | Thomas | Sales |   5000 |
+-----+--------+-------+--------+
1 row in set (0.00 sec)
You can also pass the current date and time as salt using the now() function to rand command as shown below.
mysql> SELECT * FROM employee ORDER BY RAND(NOW()) LIMIT 1;
+-----+-------+-----------+--------+
| id  | name  | dept      | salary |
+-----+-------+-----------+--------+
| 400 | Nisha | Marketing |   9500 |
+-----+-------+-----------+--------+
1 row in set (0.00 sec)

24. High Priority Select Command

When you use high_priority keyword in select statement, it will give that particular select statement higher priority than any update to the table.
Be very careful when you use this command, as you might slow down other updates. Use this only in situations where you need to get a record very quickly. Also make sure the select command you are giving itself is very well optimized before you execute it.
mysql> SELECT HIGH_PRIORITY * FROM employee WHERE ID = 100;

25. Consistent Read in Select Command

If you want a consistent read. i.e When you are selecting rows from a table, if you don’t want any other process to modify the values, you need to enable a share lock mode when you are reading the records.
If you don’t understand the impact of how these works, you might put yourself in a difficult situation if you try to use these on a large table.
The following command will not allow other MySQL sessions to modify the records that are queried by this select statement until it reads all these records.
mysql> SELECT * FROM employee WHERE ID = 100 LOCK IN SHARE MODE;
Please note that you can also do “FOR UPDATE” as shown below, which will block other sessions from doing “SELECT … LOCK in SHARE MODE” until this transaction is over.
mysql> SELECT * FROM employee WHERE ID = 100 FOR UPDATE;

12 Essential MySQL Insert Command Examples

Essential MySQL Insert Command Examples

One of the common MySQL operation is to insert records into a table.
This tutorial explains how to use MySQL insert command with several practical and useful examples.
The following example will connect to devdb database with username devuser and password mysecretpwd
# mysql -u devuser -pmysecretpwd devdb
mysql>
For this tutorial, we’ll insert values into employee table. This is the structure of the employee table.
mysql> desc employee;
+--------+-------------+------+-----+---------+----------------+
| Field  | Type        | Null | Key | Default | Extra          |
+--------+-------------+------+-----+---------+----------------+
| id     | int(11)     | NO   | PRI | NULL    | auto_increment |
| name   | varchar(20) | YES  |     | NULL    |                |
| dept   | varchar(10) | YES  |     | NULL    |                |
| salary | int(10)     | YES  |     | NULL    |                |
+--------+-------------+------+-----+---------+----------------+

1. Basic Insert Command Example

The following command will insert three new records into employee table. In this example, after the “values”, specify the values for all the columns in the table.
INSERT INTO employee VALUES(100,'Thomas','Sales',5000);
SELECT * FROM employee;

2. Insert Values only for Selected Columns

If you want to insert values only to selected columns, you should specify the column names in the insert command.
The following will insert two records only for columns id and name.
INSERT INTO employee(id,name) VALUES(200,'Jason');
For the “dept” and “salary” column, we didn’t specify any values for this particular records. So, we’ll see NULL as the value in our select command output. Please note that this is not the string “NULL”, the select command just displays the string “NULL” to indicate that the column value is really null.
mysql> SELECT * FROM employee;
+-----+--------+-------+--------+
| id  | name   | dept  | salary |
+-----+--------+-------+--------+
| 100 | Thomas | Sales |   5000 |
| 200 | Jason  | NULL  |   NULL |
+-----+--------+-------+--------+
2 rows in set (0.00 sec)

3. Insert Set Example

Instead of using “values” keyword in your select command, you can also use “set” keyword in your select command as shown below.
The following insert command is exactly same as the previous example. But, instead of value, this is using set.
mysql> INSERT INTO employee SET id=300, name='Mayla';

mysql> select * from employee;
+-----+--------+-------+--------+
| id  | name   | dept  | salary |
+-----+--------+-------+--------+
| 100 | Thomas | Sales |   5000 |
| 200 | Jason  | NULL  |   NULL |
| 300 | Mayla  | NULL  |   NULL |
+-----+--------+-------+--------+

4. Insert Records Based on Rows from Another Table

In this example, we’ll use INSERT … SELECT method, which will select the rows from another table, and insert it into our table.
The following example will take all the records from contractor table and insert it into employee table.
INSERT INTO employee SELECT * FROM contractor;
You can also use various “where” condition in the select command to only pick selected records from contractor table and insert into employee table as shown below.
INSERT INTO employee SELECT * FROM contractor WHERE salary >= 7000;
Note: If you are used to Oracle database, you’ll use “insert into employee AS select * from contractor”. Please note that mysql doesn’t use the “AS” keywords in this context.

5. Insert Selected Columns Values From Another Table

You can also pick only selected column values of rows from another table and insert it into your table.
The following example will take the values of “id” and “name” for ALL the rows in the contractor table and insert it into employee table.
INSERT INTO employee(id,name) SELECT id,name FROM contractor;
Just like the previous example, you can also use where condition and limit the records.
INSERT INTO employee(id,name) SELECT id,name FROM contractor WHERE salary >= 7000;
Please note that if the record already exist for the primary key (which is id) in the employee table, you’ll get the following error message. The following error indicates that the employee id “100” already exists in the employee table.
ERROR 1062 (23000): Duplicate entry '100' for key 'PRIMARY'

6. Insert Records to a Specific Partition

If you have created the table using partition by range, then you can specify the partition in your insert command as shown below.
The following example will insert records into the employee table in partition p1
INSERT INTO employee PARTITION (p1) VALUES(100,'Thomas','Sales',5000);
Please note that the row already exists in that particular partition. For example, in this example p1, you’ll get the following error message:
ERROR 1729 (HY000): Found a row not matching the given partition set
Note: This will work only on MySQL 5.6 and above.

7. Insert Records to Multiple Partition in a Table

You can also insert records into multiple partitions using a single insert statement.
The following insert statement will insert the record with id “100” to partition p1, and record with id “200” to partition p2.
INSERT INTO employee PARTITION (p1, p2) VALUES(100,'Thomas','Sales',5000), (200,'Jason','Technology',5500);
Please note that in the above example, if for some reason, MySQL is unable to insert one of the records into a partition, the entire insert statement will fail, and both the records will not be inserted.
Again, this will work only on MySQL 5.6 and above.

8. Ignore Error Message During Insert

For some reason, if you want to ignore the error message thrown by MySQL during insert statement, you can use insert ignore.
For example, the following command will throw an error message, as the record already exists in the table.
mysql> INSERT INTO employee VALUES(100,'Thomas','Sales',5000);
ERROR 1062 (23000): Duplicate entry '100' for key 'PRIMARY'
To ignore the above error message, you can use “insert ignore” (instead of just insert) as shown below. Please note that this will still not insert the record into the table, as there is a primary key on id column. But, this will simply ignore the error message.
mysql> INSERT IGNORE INTO employee VALUES(100,'Thomas','Sales',5000);
Query OK, 0 rows affected (0.00 sec)

9. Default Values in Insert

If the MySQL is running in strict mode, and when we don’t specify default values, it will throw error message.
However if strict mode is not enabled (which is default), and when you do an insert command and don’t specify a value fora column, it will use the default value for that particular column data types.
For example, in the bonus table, both the column values are set to “not null”.
mysql> DESC bonus;
+--------+---------+------+-----+---------+-------+
| Field  | Type    | Null | Key | Default | Extra |
+--------+---------+------+-----+---------+-------+
| id     | int(11) | NO   |     | NULL    |       |
| amount | int(11) | NO   |     | NULL    |       |
+--------+---------+------+-----+---------+-------+
Let us insert a record into this table for id column.
INSERT INTO bonus(id) VALUES(100);
When you do a select command, you’ll notice that the amount column is automatically set to implicit default value of 0.
SELECT * FROM bonus;
+-----+--------+
| id  | amount |
+-----+--------+
| 100 |      0 |
+-----+--------+
If you don’t specify for both id and amount, both will be set to 0 automatically as shown below. i.e When values are not specified, MySQL will use the DEFAULT values.
INSERT INTO bonus VALUES();

mysql> select * from bonus;
+-----+--------+
| id  | amount |
+-----+--------+
|   0 |      0 |
+-----+--------+
Note: You can also use the keyword “DEFAULT” in the values as shown below, which will achieve the above output as above.
INSERT INTO bonus VALUES(DEFAULT,DEFAULT);
For string column, the default value is empty string. Also, please note that when numeric column has AUTO_INCREMENT set, then the default value will be the next value of the appropriate sequence.

10. Expression in Insert Values

In the following example, for the bonus value, we’ve specified “5000+id” as value. So, this will add the employee id value to the bonus value and insert the final value into the bonus column as shown below.
You can use “+”, “-“, “*”, or any other valid MySQL expression operator in the values. In the following example, it is using “50*2” for id column. So, the id that will be inserted is “100”
You can also refer to the values of other columns. In the following example, it uses “5000+id” for bonus column. So, this will take the value of id column (which is 100), and add it to 5000. So, final bonus value is “5100” as shown below.
mysql> INSERT INTO employee VALUES(50*2,'Thomas','Sales',5000+id);

mysql> select * from employee;
+-----+--------+-------+--------+
| id  | name   | dept  | salary |
+-----+--------+-------+--------+
| 100 | Thomas | Sales |   5100 |
+-----+--------+-------+--------+

11. Make Insert a Low Priority (or High Priority) Activity

For storage engine that supports table locking (for example, MyISAM), you can specify the priority of your insert.
For example, this insert statement will delay the insert (make it low priority) until there are no reads on the table.
INSERT LOW_PRIORITY INTO employee VALUES(100,'Thomas','Sales',5000);
You can also specify high priority as shown below, which will behave opposite to the low priority inserts.
INSERT HIGH_PRIORITY INTO employee VALUES(100,'Thomas','Sales',5000);
Please keep in mind that if your database is read intensive and if you specify a low_priority insert statement, your insert might not go through for a very long time.
Also, please note that this is little different than “INSERT … DELAYED”, which is deprecated starting from MySQL 5.6.6. So, don’t use “insert … delayed” anymore.

12. When Duplicate is Found, Update a Column Value

During insert, if there is a duplicate key, it will fail as shown below, as the id “100” already exist in the table.
mysql>  INSERT INTO employee VALUES(100,'Thomas','Sales',5000);
ERROR 1062 (23000): Duplicate entry '100' for key 'PRIMARY'

mysql> select * from employee;
+-----+--------+-------+--------+
| id  | name   | dept  | salary |
+-----+--------+-------+--------+
| 100 | Thomas | Sales |   5000 |
+-----+--------+-------+--------+
However, you can do some update to that particular record (when a duplicate is found) using the “ON DUPLICATE KEY UPDATE” as shown below.
As shown in the following example, when the insert failed (because of duplicate key), we are updated the salary column by adding 500 to its value.
mysql> INSERT INTO employee VALUES(100,'Thomas','Sales',5000) on DUPLICATE KEY UPDATE salary=salary+500;

mysql> select * from employee;
+-----+--------+-------+--------+
| id  | name   | dept  | salary |
+-----+--------+-------+--------+
| 100 | Thomas | Sales |   5500 |
+-----+--------+-------+--------+
Please note that in the above example, while inserting, even though it updated only one record, the output will say “2 rows affected”.

11 Essential MySQL Update Command Examples

Essential MySQL Update Command Examples

One of the most common MySQL operation is to change an existing value of a record in a table.
In this article, we’ll explain how to use MySQL update command along with some helpful examples.
The following are covered in this tutorial:
  1. Update All Rows
  2. Update Only Selected Rows
  3. Update Column Value with Expression
  4. DEFAULT keyword usage in Update
  5. Update Multiple Columns at the Same Time
  6. Using LIMIT clause in Update
  7. Multiple Table Update (using Inner Join)
  8. Multiple Table Update (Using Left Join)
  9. Return Updated Value (or Pre-Update Value)
  10. Combine CASE or IF statement with Update
  11. Why use ORDER by Clause with Update?
For this tutorial, we’ll use the following employee table as an example. This is the structure of this example table.
mysql> DESC employee;
+--------+-------------+------+-----+---------+----------------+
| Field  | Type        | Null | Key | Default | Extra          |
+--------+-------------+------+-----+---------+----------------+
| id     | int(11)     | NO   | PRI | NULL    | auto_increment |
| name   | varchar(20) | YES  |     | NULL    |                |
| dept   | varchar(10) | YES  |     | Sales   |                |
| salary | int(10)     | YES  |     | NULL    |                |
+--------+-------------+------+-----+---------+----------------+
Currently the employee table has the following records.
mysql> SELECT * FROM employee;
+-----+--------+------------+--------+
| id  | name   | dept       | salary |
+-----+--------+------------+--------+
| 100 | Thomas | Sales      |   5000 |
| 200 | Jason  | Technology |   5500 |
| 300 | Mayla  | Technology |   7000 |
| 400 | Nisha  | Marketing  |   9500 |
| 500 | Randy  | Technology |   6000 |
| 501 | Ritu   | Accounting |   NULL |
+-----+--------+------------+--------+

1. Update All Rows

In the following basic example, this update command will set the value of dept column to Technology for all the rows in the employee table.
mysql> UPDATE employee SET dept='Technology';
Query OK, 3 rows affected (0.02 sec)
Rows matched: 6  Changed: 3  Warnings: 0
The output of UPDATE command will have the following two lines:
  • Line 1: This will say “Query OK” if the query was executed. If there is a syntax error, it will display it here. Even when it didn’t update any record, this line will still say “Query OK” as long as there were no syntax error and the statement was clean. This line will also display how many records were updated by this query (for example: 3 rows affected). Finally, this will also show how long it took for MySQL to execute the query (for example: 0.02 seconds).
  • Line 2: This will say how many records where matched by the condition of the update statement. In this example, there is no WHERE condition to restrict the number of records that should be considered for the update (so, it says: Rows matched: 6). Next, this will show how many records were really updated (for example: Changed: 3). Finally, it will display how many warnings where there during update. Pretty much in most cases, you’ll see Warnings as 0 when everything worked properly.
Here are the updated records after the above update command.
mysql> SELECT * FROM employee;
+-----+--------+------------+--------+
| id  | name   | dept       | salary |
+-----+--------+------------+--------+
| 100 | Thomas | Technology |   5000 |
| 200 | Jason  | Technology |   5500 |
| 300 | Mayla  | Technology |   7000 |
| 400 | Nisha  | Technology |   9500 |
| 500 | Randy  | Technology |   6000 |
| 501 | Ritu   | Technology |   NULL |
+-----+--------+------------+--------+

2. Update Only Selected Rows

Instead of updating all the records you can selectively update certain records based on WHERE condition.
The following example will update the employee table and assign all employee who have a salary of greater than or equal to 7000 to Marketing department.
mysql> UPDATE employee SET dept='Marketing' WHERE salary >=7000;
Query OK, 2 rows affected (0.01 sec)
Rows matched: 2  Changed: 2  Warnings: 0
There were only two records that matched the above WHERE condition which got updated as shown below.
mysql> SELECT * FROM employee;
+-----+--------+------------+--------+
| id  | name   | dept       | salary |
+-----+--------+------------+--------+
| 100 | Thomas | Technology |   5000 |
| 200 | Jason  | Technology |   5500 |
| 300 | Mayla  | Marketing  |   7000 |
| 400 | Nisha  | Marketing  |   9500 |
| 500 | Randy  | Technology |   6000 |
| 501 | Ritu   | Technology |   NULL |
+-----+--------+------------+--------+
We discussed a lot about the various practical WHERE conditions in our MySQL select command tutorial. It is very helpful to understand how to use the WHERE clause effectively during UPDATE statement

3. Update Column Value with Expression

When you assign a value to a column after the SET, you don’t always have to specify static values. You can also use expressions as shown below.
The following is a very simple expression, where it increments the salary value by 500 for all the employees in Technology department.
mysql> UPDATE employee SET salary=salary+500 WHERE dept='Technology';
Query OK, 3 rows affected (0.01 sec)
Rows matched: 4  Changed: 3  Warnings: 0
There were only 4 records that matched the above WHERE condition. But only three records were updated as shown below, as one of the employee records who belongs to Technology department had NULL value in salary field. So, the above salary+500 expression also became NULL, and it didn’t update that particular record.
mysql> SELECT * FROM employee;
+-----+--------+------------+--------+
| id  | name   | dept       | salary |
+-----+--------+------------+--------+
| 100 | Thomas | Technology |   5500 |
| 200 | Jason  | Technology |   6000 |
| 300 | Mayla  | Marketing  |   7000 |
| 400 | Nisha  | Marketing  |   9500 |
| 500 | Randy  | Technology |   6500 |
| 501 | Ritu   | Technology |   NULL |
+-----+--------+------------+--------+

4. Update Column Values to DEFAULT

Instead of specifying a static value or an expression, you can also use the keyword “DEFAULT” when you are assigning a value to a column after the SET.
If you look the output of the “DESC employee” shown below, you’ll see there is a column called Default. As you see there, the salary has a DEFAULT value of NULL. The dept has a DEFAULT value of Sales.
mysql> DESC employee;
+--------+-------------+------+-----+---------+----------------+
| Field  | Type        | Null | Key | Default | Extra          |
+--------+-------------+------+-----+---------+----------------+
| id     | int(11)     | NO   | PRI | NULL    | auto_increment |
| name   | varchar(20) | YES  |     | NULL    |                |
| dept   | varchar(10) | YES  |     | Sales   |                |
| salary | int(10)     | YES  |     | NULL    |                |
+--------+-------------+------+-----+---------+----------------+
First, let us update the salary column to the default using DEFAULT keyword as shown below.
mysql> UPDATE employee SET salary=DEFAULT;
Query OK, 5 rows affected (0.03 sec)
Rows matched: 6  Changed: 5  Warnings: 0
Next, update the department column to default value using DEFAULT keyword as shown below.
mysql> UPDATE employee SET dept=DEFAULT;
Query OK, 6 rows affected (0.00 sec)
Rows matched: 6  Changed: 6  Warnings: 0
As you see from the following output, we can see that the above DEFAULT keyword took the corresponding default values from the employee table definition, and used them to update it. Department column got updated to Sales and salary updated to NULL as shown below.
mysql> SELECT * FROM employee;
+-----+--------+-------+--------+
| id  | name   | dept  | salary |
+-----+--------+-------+--------+
| 100 | Thomas | Sales |   NULL |
| 200 | Jason  | Sales |   NULL |
| 300 | Mayla  | Sales |   NULL |
| 400 | Nisha  | Sales |   NULL |
| 500 | Randy  | Sales |   NULL |
| 501 | Ritu   | Sales |   NULL |
+-----+--------+-------+--------+

5. Update Multiple Columns at the Same Time

In a single update statement, you can also update the values for more than one column as shown below.
In the following example, we are assigning values to both salary and dept column for all the records where the employee id is greater than 300.
mysql> UPDATE employee SET salary=5000, dept='Marketing' WHERE id > 300;
Query OK, 3 rows affected (0.04 sec)
Rows matched: 3  Changed: 3  Warnings: 0
As you see from the following output, the above update command updated two column values for the last three records which matched the above WHERE condition.
mysql> SELECT * FROM employee;
+-----+--------+-----------+--------+
| id  | name   | dept      | salary |
+-----+--------+-----------+--------+
| 100 | Thomas | Sales     |   NULL |
| 200 | Jason  | Sales     |   NULL |
| 300 | Mayla  | Sales     |   NULL |
| 400 | Nisha  | Marketing |   5000 |
| 500 | Randy  | Marketing |   5000 |
| 501 | Ritu   | Marketing |   5000 |
+-----+--------+-----------+--------+

6. Limit How many records to be Updated

We can also use LIMIT option to limit how many records should be updated.
Even if the where condition matched more records, the update statement will update only the 1st X number of records specified by the LIMIT value.
In the following example, we are assigning the salary of all the records to 6500, as we don’t have a where condition. But, we are using LIMIT 3. This means that it will update the salary only the first three records for the matching condition.
mysql> UPDATE employee SET salary=6500 LIMIT 3;
Query OK, 3 rows affected (0.01 sec)
Rows matched: 3  Changed: 3  Warnings: 0
As you see from the following output, only the 1st three records where updated by the above command.
mysql> SELECT * FROM employee;
+-----+--------+-----------+--------+
| id  | name   | dept      | salary |
+-----+--------+-----------+--------+
| 100 | Thomas | Sales     |   6500 |
| 200 | Jason  | Sales     |   6500 |
| 300 | Mayla  | Sales     |   6500 |
| 400 | Nisha  | Marketing |   5000 |
| 500 | Randy  | Marketing |   5000 |
| 501 | Ritu   | Marketing |   5000 |
+-----+--------+-----------+--------+
One thing to keep in mind is that LIMIT 3 doesn’t really mean that update will keep going until it updates 3 records. Instead, the update statement will stop executing as soon as it has processed first 3 rows that matched the where condition irrespective of whether those records were really updated or not.

7. Multiple Table Update (using Inner Join)

You can also combine two tables during update. You can also update values from two tables at the same time using a single update statement.
In this example, we’ll use the following benefits table along with our existing employee table.
mysql> SELECT * from benefits;
+------------+-------+
| dept       | bonus |
+------------+-------+
| Sales      |  1000 |
| Technology |  NULL |
| Marketing  |   800 |
+------------+-------+
The following update statement will increment the value of salary column from employee table to the value specified in the benefits table for the corresponding dept column.
This means that we have to combine both employee and benefits table during the UPDATE as shown below. Use the common field between these two tables in the WHERE clause. In this example, the common field is dept.
Also, right after the UPDATE keyword, specify the name of both the tables as shown below. After the SET keyword you can specify either one or more column name that needs to be updatd from either one table, or both the table.
mysql> UPDATE employee,benefits 
    -> SET employee.salary=employee.salary+benefits.bonus 
    -> WHERE employee.dept=benefits.dept and benefits.bonus is not null;
Query OK, 4 rows affected (0.01 sec)
Rows matched: 4  Changed: 4  Warnings: 0
Please note that in the above update statement we are using inner join.
The following is the output after the above update statement was executed. As you see below, the salary of the employee got incremented based on the values from the above benefits table.
mysql> SELECT * FROM employee;
+-----+--------+------------+--------+
| id  | name   | dept       | salary |
+-----+--------+------------+--------+
| 100 | Thomas | Sales      |   7500 |
| 200 | Jason  | Sales      |   7500 |
| 300 | Mayla  | Technology |   6500 |
| 400 | Nisha  | Technology |   5000 |
| 500 | Randy  | Marketing  |   5800 |
| 501 | Ritu   | Marketing  |   5800 |
+-----+--------+------------+--------+

8. Multiple Table Update (Using Left Join)

Similar to the previous example inner join, we can also use left join.
When we are using inner join, we don’t specify the keyword “inner join”, as that is the default while combining multiple tables.
However when using left join, we should explicitly specify “left join” as shown below.
mysql> UPDATE employee LEFT JOIN benefits on employee.dept = benefits.dept
    -> SET employee.salary = employee.salary+500 
    -> WHERE benefits.bonus is null;
Query OK, 2 rows affected (0.03 sec)
Rows matched: 2  Changed: 2  Warnings: 0
Here is the output after the above update.
mysql> SELECT * FROM employee;
+-----+--------+------------+--------+
| id  | name   | dept       | salary |
+-----+--------+------------+--------+
| 100 | Thomas | Sales      |   7500 |
| 200 | Jason  | Sales      |   7500 |
| 300 | Mayla  | Technology |   7000 |
| 400 | Nisha  | Technology |   5500 |
| 500 | Randy  | Marketing  |   5800 |
| 501 | Ritu   | Marketing  |   5800 |
+-----+--------+------------+--------+

9. Return Updated Value (or Pre-Update Value)

In MySQL, in the update command, there is no direct way of getting the new updates value.
For example, in PostgreSQL, we can use something like this: “UPDATE table_name SET column_name = expression WHERE condition RETURNING column_name. In MySQL, we don’t have the RETURNING concept as part of MySQL update command.
But, you can do the following to get the return value inside your procedure, package, function, or from command line.
mysql> UPDATE employee SET salary = salary+500 WHERE id=400;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> SELECT salary AS tmp_salary FROM employee WHERE id=400;
+------------+
| tmp_salary |
+------------+
|       5500 |
+------------+
In the above example, after the update is done, the tmp_salary variable will has the updated salary for employee id
If you like to get the value of the Salary before the update was done, obviously you just have to switch the sequence of the above two statements. In which case, you’ll first the SELECT and then the UPDATE.
Or, you can use “@” as part of the UPDATE statement and get the pre-updated value as shown below.
UPDATE employee SET salary = salary+500 WHERE id=400 
  AND @tmp_salary := salary
In the above update command, after the update is done, the tmp_salary variable will has the pre-updated salary for employee id 400. As you see here, even though the salary value is already updated to 6000. The tmp_salary variable that was used in the above UPDATE command still has the value of 5500.
mysql> SELECT * FROM employee WHERE id = 400;
+-----+-------+------------+--------+
| id  | name  | dept       | salary |
+-----+-------+------------+--------+
| 400 | Nisha | Technology |   6000 |
+-----+-------+------------+--------+

mysql> SELECT @tmp_salary;
+-------------+
| @tmp_salary |
+-------------+
|        5500 |
+-------------+

10. Combine CASE or IF statement with Update

You can also use conditional updates using MySQL conditional commands like CASE, IF, etc. This is helpful to simplify your updates.
Instead of using multiple updates, you might just be using single UPDATE command that combines all your cases.
For example, let us say we have the following three update statement that updates the salary field based on the value from dept field.
UPDATE employee SET salary = salary+1000 WHERE dept = 'Sales';
UPDATE employee SET salary = salary+500 WHERE dept = 'Technology';
UPDATE employee SET salary = salary+800 WHERE dept = 'Marketing';
You can combine all of the above three UPDATE statement into one single UPDATE statement using the CASE condition as shown below.
UPDATE employee SET salary = 
  CASE dept
   WHEN 'Sales' THEN salary+1000
   WHEN 'Technology' THEN salary+500
   WHEN 'Marketing' THEN salary+500
   ELSE salary 
  END;
Just like CASE, you can also use IF condition to update the column value accordingly.

11. ORDER By Clause with Update

You can use ORDER BY value during update. ORDER BY clause definitely make sense during SELECT statement. But, why do we need ORDER BY during update.
Let us say you have a UNIQUE id on employee table’s id field.
When you execute the following command to increment the employee ID by 100, you might get an DUPLICATE error message.
mysql> UPDATE contractor set id=id+100;
ERROR 1062 (23000): Duplicate entry '200' for key 'PRIMARY'
This is because when it is trying ti update the value of id from 100 to 200, there is already an existing record with id as 200. The ID field also has a UNIQUE constrain, in this case it is the PRIMARY key. So, we are getting the above error.
For this, we have to execute the following command with ORDER BY id desc.
mysql> UPDATE employee SET id=id+100 order by id desc;
Query OK, 6 rows affected (0.01 sec)
Rows matched: 7  Changed: 7  Warnings: 0
In the above case, it will first start with the maximum employee id, update that record, and then move on to the next. This way, it will never have a scenario of duplicate value during the update process.