0

I have a table customer as described below.

customer_id number customer_name varchar(30) city varchar(20)

columns. When the below query run in Oracle db

SELECT customer_id, city FROM customer WHERE city IN ('abc', 'def', 'ghi')

I'm getting the output as shown below. Table doesn't have record for ghi

customer_id, city 1, abc 2, def

I'm trying to form the output something as below.

customer_id, city 1, abc 2, def null, ghi

Though no record for ghi in table, want to display it in SELECT query output with rest of the column value as null.

Much appreciate help in writing sql for this scenario.

9
  • you can. But, why do you want that ? Also, which database are you using ? Commented Oct 2, 2017 at 14:42
  • I'm using Oracle 10 Commented Oct 2, 2017 at 14:43
  • You didn't asnwered why do you need that ? Commented Oct 2, 2017 at 14:43
  • IN doesnt generate a list.. customer IN ('abc', 'def', 'ghi') works like customer = 'abc' OR customer = 'def' OR customer = 'ghi' Commented Oct 2, 2017 at 14:45
  • 1
    That is not your query, if you are getting any input from it. Why? Because the query you wrote is syntactically incorrect. The IN condition needs to be in a WHERE clause, but there is no WHERE clause in your query. Commented Oct 2, 2017 at 14:47

1 Answer 1

5

You need a derived table containing all possibilities. Either you have one, like a city table and then you can do:

SELECT t.customer_id,s.city
FROM city_table s
LEFT JOIN customer t
 ON(s.id = t.city) 
WHERE s.city IN ('abc', 'def', 'ghi')

Or generate the values your self:

SELECT t.customer_id,s.city
FROM (SELECT 'abc' as id FROM DUAL
      UNION ALL 
      SELECT 'def' FROM DUAL
      UNION ALL
      SELECT 'ghi' FROM DUAL) s
LEFT JOIN customer t
 ON(s.id = t.city) 
WHERE s.id IN('abc', 'def', 'ghi')
Sign up to request clarification or add additional context in comments.

12 Comments

But, there is no record
@Ravi and? The city table will populate it, and you commented to fast :S there's already an edit.
@sagi who says it will always be 'ghi?'
No one, that's why I gave two options. If options one is not possible, then there's no other way to do it then option two. @isaace
Not that I can think of. What you can do, is create a table with all the values need to be checked, and compare against it. @SriramM
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.