Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL multiple SETs in one UPDATE?

Tags:

sql

sql-update

I have a SQL field like so:

FIELD_A  
  cat     
  dog 
  bird
  mole
  dog

I want to UPDATE

  • all dog to pug
  • all bird to owl
  • all cat to angora.

Apparently, the SQL UPDATEstatement only allows one SET condition at a time.

How can I write a query to accomplish the above operation all at once?

like image 889
Ben Avatar asked Mar 03 '11 08:03

Ben


People also ask

Can you do multiple sets in SQL update?

We use the SQL UPDATE syntax to modify or update existing data in a table or view in SQL Server. We can use this statement to modify a single unit of data field as well as multiple sets of data fields based on our requirements.

Can we update multiple tables in a single update statement?

For instance, updating 2 different tables together in a single query/statement. This involves the use of the BEGIN TRANSACTION clause and the COMMIT clause. The individual UPDATE clauses are written in between the former ones to execute both the updates simultaneously.

How do you update multiple items in SQL?

There are a couple of ways to do it. INSERT INTO students (id, score1, score2) VALUES (1, 5, 8), (2, 10, 8), (3, 8, 3), (4, 10, 7) ON DUPLICATE KEY UPDATE score1 = VALUES(score1), score2 = VALUES(score2);

Can we update multiple tables using update command?

In SQL Server, we can join two or more tables, but we cannot update the data of multiple tables in a single UPDATE statement.


2 Answers

UPDATE AnonymousTable
   SET Field_A = (CASE Field_A
                  WHEN 'dog'  THEN 'pug'
                  WHEN 'bird' THEN 'owl'
                  WHEN 'cat'  THEN 'angora'
                  ELSE Field_A END)
 WHERE Field_A IN ('dog', 'bird', 'cat'); 

With the WHERE clause, the ELSE clause in the CASE expression is optional or redundant - but including the ELSE gives you reliability. One of the more serious mistakes is not to cover that 'none of the above' alternative and find that everything that wasn't mentioned is set to NULL.

like image 183
Jonathan Leffler Avatar answered Oct 22 '22 03:10

Jonathan Leffler


with CASE clause you can accomplish this. here an example

http://www.java2s.com/Code/SQLServer/Select-Query/UseCASEintheUPDATEstatement.htm

like image 30
adt Avatar answered Oct 22 '22 05:10

adt