Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping column values in Oracle

Tags:

sql

logic

oracle

I was solving one of the puzzles and came across swapping column values using DML queries:

SELECT * FROM TEMP_TABLE;
ID1, ID2
--------
20, 15
20, 15
20, 15

Solution is mathematical calculation:

UPDATE TEMP_TABLE SET ID1=ID1+ID2;
UPDATE TEMP_TABLE SET ID2=ID1-ID2;
UPDATE TEMP_TABLE SET ID1=ID1-ID2;

Now, I am trying to figure out whether this can be applied to Strings or not, please suggest.

SELECT * FROM TEMP_TABLE_NEW;
ID1, ID2
--------
ABC, XYZ
ABC, XYZ
ABC, XYZ
like image 907
Nikhil Joshi Avatar asked Feb 17 '14 11:02

Nikhil Joshi


People also ask

How do I swap data between two columns in SQL?

SET Col1 = Col2, Col2 = Col1; When you run above update statement, the values of the columns will be swapped in SQL Server. There is no need for temporary column, variable or storage location in SQL Server.


2 Answers

There's no need to have three update statements, one is sufficient:

UPDATE temp_table_new 
SET    id1 = id2, 
       id2 = id1; 
like image 89
René Nyffenegger Avatar answered Sep 28 '22 01:09

René Nyffenegger


CREATE TABLE Names
(
F_NAME VARCHAR(22),
L_NAME VARCHAR(22)
);

INSERT INTO Names VALUES('Ashutosh', 'Singh'),('Anshuman','Singh'),('Manu', 'Singh');

UPDATE Names N1 , Names N2 SET N1.F_NAME = N2.L_NAME , N1.L_NAME = N2.F_NAME 
WHERE N1.F_NAME = N2.F_NAME;

SELECT * FROM Names;
like image 27
Ashutosh SIngh Avatar answered Sep 27 '22 23:09

Ashutosh SIngh