SQL UPDATE Statement



SQL Update Statement :

  1. In SQL we can use update statement to update the existing records or any field of the database.
  2. In SQL update statement we must use where condition otherwise the complete database will be altered by UPDATE statement.

SQL UPDATE Syntax :

UPDATE table_name
SET column1 = value1,
    column2 = value2,
    ...
WHERE 
    column_name = some_value;

In the above syntax we want to update the column1 with the value value1. Where condition is used to select the appropriate record to be updated.

Demo Database :

Consider the following demo table -

+----+----------+-----+-----------+----------+
| ID | ENAME    | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Kota      |  2000.00 |
|  2 | Raj      |  23 | Delhi     |  1500.00 |
|  3 | Anand    |  21 | Karachi   |  2000.00 |
|  4 | Saurabh  |  25 | Mumbai    |  6500.00 |
|  5 | Poonam   |  29 | Bhopal    |  8500.00 |
|  6 | Komal    |  23 | Pune      |  4500.00 |
|  7 | Omkar    |  24 | Indore    | 10000.00 |
+----+----------+-----+-----------+----------+

SQL UPDATE Statement :

UPDATE employee
SET ENAME ='Raman',ADDRESS='Pune'
WHERE ID = 1;

In this example we are going to update the record having ID = 2 with the Ename = “Raman” and Address = “Pune”.

+----+----------+-----+-----------+----------+
| ID | ENAME    | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Raman    |  32 | Pune      |  2000.00 |
|  2 | Raj      |  23 | Delhi     |  1500.00 |
|  3 | Anand    |  21 | Karachi   |  2000.00 |
|  4 | Saurabh  |  25 | Mumbai    |  6500.00 |
|  5 | Poonam   |  29 | Bhopal    |  8500.00 |
|  6 | Komal    |  23 | Pune      |  4500.00 |
|  7 | Omkar    |  24 | Indore    | 10000.00 |
+----+----------+-----+-----------+----------+

Above result will be obtained after the update statement execution.

Precaution to be take :

Please make sure that you are selecting particular record or record set using where condition. You should avoid using below query -

UPDATE employee
SET ENAME ='Raman',ADDRESS='Pune';

it will results into -

+----+----------+-----+-----------+----------+
| ID | ENAME    | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Raman    |  32 | Pune      |  2000.00 |
|  2 | Raman    |  23 | Pune      |  1500.00 |
|  3 | Raman    |  21 | Pune      |  2000.00 |
|  4 | Raman    |  25 | Pune      |  6500.00 |
|  5 | Raman    |  29 | Pune      |  8500.00 |
|  6 | Raman    |  23 | Pune      |  4500.00 |
|  7 | Raman    |  24 | Pune      | 10000.00 |
+----+----------+-----+-----------+----------+

It will update all the records of the database.