Skip to content
Advertisement

SQL Use column value in another column

What I’m trying to do is best described as mad-libs within SQL where there is one column that acts like a “template” that will end with all the values from the other columns inserted into the correct position.

An example of what a sample table might look like is below. The final query should return: 1. Yesterday, I saw 20 Angry Cats Bouncing 20 sweaters around the park. 2. It would be so Hilarious if Fish could Run while on a 7.5 year mission to the moon.

ID | Noun | Adjective | Verb     | Number | Sentence
===================================================
1  | Cat  | Angry     | Bouncing | 20     | Yesterday, I saw [Number] [Adjective] [Noun]s [Verb] [Number] sweaters around the park.
2  | Fish | Hilarious | Run      | 7.5    | It would be so [Adjective] if [Noun] could [Verb] while on a [Number] year mission to the moon.

This is a silly example, much like mad-libs are in real life. Nevertheless, it demonstrates what is trying to be accomplished.

Advertisement

Answer

You would use replace() and replace() again:

select t.*,
       replace(replace(replace(replace(sentence, '[noun]', noun
                                      ), '[verb]', verb
                              ), '[Adjective]', Adjective
                      ), '[Number]', number
               ) as filled_in
from t;
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement