0

I have an idea for a SQL query but I'm not sure if this is even possible. Let's imagine I have a table with 3 columns:

IDNUMBER, PARAGRAPH, ANIMAL 
  • IDNUMBER is just a key identifier number.

  • PARAGRAPH is always going to have a big block of text, and sometimes it will mention an animal in the paragraph.

  • ANIMAL will always have a set small value like "Dog" or "Monkey".

Is there a way, for each IDNUMBER, to take the value in the Animal column and use that value for a string search of the corresponding Paragraph column? I'm not sure if I would need to assign the Animal value to some sort of string variable for each loop? This is much more of conceptual question at this point because I'm not sure if this is even possible in SQL, but something like:

SELECT
    idnumber, paragraph, animal
FROM 
    zootable
WHERE 
    paragraph NOT LIKE ('%currentAnimalValue%')

Sorry this one is so hand-wavy, I'm just looking for a sanity check on this one. Thanks for any help/wisdom you can provide! :)

7
  • 1
    what is your dbms? Commented Dec 8, 2016 at 21:33
  • Does each paragraph relate to the animal in the table? Commented Dec 8, 2016 at 21:34
  • I work mostly in Teradata and Oracle SQL Developer, so either of those would be good. Commented Dec 8, 2016 at 21:37
  • 2
    I agree with the below answer. I just wanted to add that you need to be careful with wildcards. For instance if you had a paragraph that had the word pants in it and the animal was ants. Commented Dec 8, 2016 at 21:45
  • 1
    I suggest you change the schema, one table for animals, one for paragraphs Commented Dec 9, 2016 at 0:48

2 Answers 2

4

Do you mean something like this?

select t.*
from t
where t.paragraph not like '%' || t.animal || '%' ;

Some databases use concat(), +, or & for string concatenation.

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

1 Comment

I am amazed at how quickly you guys cracked that! Thank you so much this is getting added to the Favorites library!! :)
2

Gordon's answer may produce some incorrect matches.

Eg: 'panda' like '%pandas%' returns True. 'ant' like '%pant%' returns True

To avoid this you should use regexp (in Oracle) to consider word boundaries (assuming paragraph column is space-separated).

For matches use:

select * from t 
where regexp_like(paragraph,'(^|\s)'||animal||'(\s|$)')

For non-matches use

select * from t 
where not regexp_like(paragraph,'(^|\s)'||animal||'(\s|$)')

Comments

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.