getting subquery error in SQL

119 views Asked by At

Trying to insert into some table using my current table . Here is the structure of my current Temptable:

CustomerID  Name        Values      FakeName
1           John        10apples    10apples_20oranges_30bananas
1           John        20oranges   10apples_20oranges_30bananas
1           John        30bananas   10apples_20oranges_30bananas
2           Steve       15apples    15apples_25oranges_35bananas
2           Steve       25oranges   15apples_25oranges_35bananas
2           Steve       35bananas   15apples_25oranges_35bananas
3           Harvey      10apples    10apples_20oranges_30bananas
3           Harvey      20oranges   10apples_20oranges_30bananas
3           Harvey      30bananas   10apples_20oranges_30bananas

This is my peice of code that I am executing :

Insert into customer (FakeName,type,address)
select (select distinct FakeName from Temptable),
        2,
        xyz

 from customer c
 where c.fakename not in (select distinct Fakename from TempTable)

getting following error

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression

I want to insert distinct Fakenames from temptable to customer table , making sure if the fake name already exist then not to insert a duplicate fakename

2

There are 2 answers

5
Nick.Mc On BEST ANSWER

select distinct FakeName from Temptable is not a scalar, so you can't use it like that.

I think this is what you're after:

Insert into customer (FakeName,type,address)
select distinct 
        FakeName,
        2,
        xyz
 from Temptable c
 where c.fakename not in (select distinct Fakename from customer)
2
Gordon Linoff On

I think you want something like this:

Insert into customer (FakeName, type, address)
    select distinct tt.FakeName, 2, 'xyz'
    from temptable tt
    where not exists (select 1 from customer c where c.fakename = tt.fakename);

Notes:

  • xyz is undefined in your query (unless it is a column in customer, which seems unlikely).
  • not in will filter all rows if any name the subquery is NULL. I replaced it with not exists.
  • I am speculating that you want to avoid duplicate entries in customer, so I changed the subquery.
  • When using in/not in with a subquery, select distinct is redundant.