Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select the comparison of two columns as one column in Oracle

Tags:

sql

select

oracle

I cannot figure out how to add a column to my SELECT query indicating whether two columns contain the same data in Oracle.

I would like to write a query like:

select column1, column2, column1=column2 from table 

and, if I have this table:

+---------+---------+ | column1 | column2 | +---------+---------+ | value1  | value1  | | value2  | value3  | | value4  | value4  | +---------+---------+ 

get a result like:

+---------+---------+-----------------+ | column1 | column2 | column1=column2 | +---------+---------+-----------------+ | value1  | value1  | true            | | value2  | value3  | false           | | value4  | value4  | true            | +---------+---------+-----------------+ 

What is the correct syntax to do this?

like image 844
Vito De Tullio Avatar asked Jan 28 '11 11:01

Vito De Tullio


People also ask

How can I compare two columns of data in Oracle?

Compare columns in two tables and list out column names which are different. for ex:- create table t1(c1 number(2), c2 varchar2(10)); create table t2(c1 number(2), c2 varchar2(10)); insert into t1 values(1,'a'); insert into t2 values(1,'b'); result should be column c2 is different.

How do I compare two columns in the same table in SQL?

In SQL, problems require us to compare two columns for equality to achieve certain desired results. This can be achieved through the use of the =(equal to) operator between 2 columns names to be compared. For this article, we will be using the Microsoft SQL Server as our database.

What is SELECT * from dual?

Example: Oracle Query SELECT * FROM DUAL ; Output – X. Selecting from the DUAL table is useful for computing a constant expression with the SELECT statement. Because DUAL has only one row, the constant is returned only once.

Can we use like and in together in Oracle?

the LIKE operation is not permitted to be used with IN.


2 Answers

If you want to consider null values equality too, try the following

select column1, column2,     case       when column1 is NULL and column2 is NULL then 'true'         when column1=column2 then 'true'        else 'false'     end  from table; 
like image 185
vc 74 Avatar answered Sep 22 '22 14:09

vc 74


I stopped using DECODE several years ago because it is non-portable. Also, it is less flexible and less readable than a CASE/WHEN.

However, there is one neat "trick" you can do with decode because of how it deals with NULL. In decode, NULL is equal to NULL. That can be exploited to tell whether two columns are different as below.

select a, b, decode(a, b, 'true', 'false') as same   from t;       A       B  SAME ------  ------  -----      1       1  true      1       0  false      1          false   null    null  true   
like image 31
Ronnis Avatar answered Sep 18 '22 14:09

Ronnis