Attilah
Attilah

Reputation: 17930

PL/SQL 'select in' from a list of values whose type are different from the outer query

I have the following tables :

Table1 ( Col1 : varchar2, Col2 : number, Col3 : number)
Table2 ( Col1 : number, Col2 : varchar2, Col3 : varchar2)

I want to run a query like this :

select distinct Col2 from Table1 where Col1 in 
(
   select Col1 from Table2
)

Table1.Col1 is of type varchar2 while Table2.Col1 is of type number. so, I need to do some casting, it seems but it fails to succeed.

The problem is that any attempts to run the query returns the following error :

  ORA-01722: invalid number
  01722. 00000 -  "invalid number"
  *Cause:    
  *Action:

Table1.Col1 contains some null values.

Upvotes: 0

Views: 2993

Answers (2)

p.campbell
p.campbell

Reputation: 100577

Your error ORA-01722 is because you're trying to put varchar2 values in an IN clause for an int column.

You've got to ensure that you're supplying int values in that IN clause. Give the same datatypes.

Upvotes: 0

Justin Cave
Justin Cave

Reputation: 231671

Something like

SELECT distinct col2
  FROM table1
 WHERE col1 IN (SELECT to_char(col1)
                  FROM table2)

should work. Depending on the relative size of the two tables, it may be more efficient to do an EXISTS instead

SELECT distinct col2
  FROM table1 t1
 WHERE EXISTS( SELECT 1
                 FROM table2 t2
                WHERE to_char(t2.col1) = t1.col1 );

Upvotes: 4

Related Questions