1

I have a table named Garden.

In the Garden table there is column named Fruit with thousands of rows and each row of Fruit has comma seperated values like Apple, Banana, Pear and so on.

I want the get the count of the number fruits in each row in Fruit column like if first row has Apple, Banana, Pear, then the count should return 3.

How to write a sql query for it.

I tried using regex but its not working.

2
  • Which DBMS are you using? "SQL" is just a query language, not the name of a specific database product. Please add the tag for the database product you are using postgresql, oracle, db2, sql-server, ... Commented May 11, 2018 at 6:10
  • 1
    Storing records as comma separated values in tables is a bad practice. Avoid it. Commented May 11, 2018 at 6:47

2 Answers 2

3

If you are using Oracle database then you can use REGEXP_COUNT regular expression.Find the below example:-

     create table garden( fruit varchar2(1000));

     insert into garden VALUES('apple,bananan,pear');
     insert into garden VALUES('orange,bananan');
     insert into garden VALUES('apple,bananan,pear,orange');

     select * from garden;

     output:-

     FRUIT
     ------------------
     apple,bananan,pear
     orange,bananan
     apple,bananan,pear,orange

Now you can use below query to get the count.

select REGEXP_COUNT(Fruit, ',')+1 as fruit_count from garden;

Sign up to request clarification or add additional context in comments.

1 Comment

I think this is the better solution for Oracle.
2

This will work:

select length(Fruit) - length(replace(Fruit, ',', '')) + 1 from Garden

This part len(Fruit) - len(replace(Fruit, ',', '')) returns how many commas are in your string and there are always one item more than commas, so we need to add 1.

3 Comments

I am ORACLE DBMS.Thanks for your reply.It is giving error as ORA-00904: "LEN": invalid identifier 00904. 00000 - "%s: invalid identifier"
@AbhinayKumar In Oracle the function is called LENGTH. Updated my answer and it will work now.
@AbhinayKumar You should accept the answer then (green tick below the score of an answer). And upvote optionally.

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.