Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMatt Nickolls
9,895 PointsNested vs unnested Replace Query
Hi all
In relation to the nested replace removing the prepositions Would it make any difference to the output if rather than using:
"SELECT media_id, title, category, img FROM Media WHERE category = ?"); ORDER BY REPLACE( REPLACE( REPLACE(title, 'The ',' ') 'An ', ' '),'A ', ' '))";
We used unnested replaces like this:
REPLACE (title, 'The ', ' '); REPLACE( title, 'An ', ' ' ); REPLACE( title, 'A ', ' ' );
Just can't wrap my head around why we need to nest them.
Thanks for your time.
1 Answer
Peter Vann
36,427 PointsHi Matt!
I hope I can make this make sense.
You are ordering by title, which you only reference once, in the innermost REPLACE, which filters out "The" in the ORDER BY sorting.
Then, the same title (void of "The") is passed to the next/parent REPLACE to filter out "An".
Then, the same title (void of both "The" and/or "An") is passed to the next/parent REPLACE to filter out "A".
In the end, you end up sorting by each catalog item's title, ignoring any "The", "An", and/or "A" that could be in it.
Another way to think of it is that the result of the innermost REPLACE becomes the first argument in the parent REPLACE, etc. all the way up the REPLACE nesting chain.
To visualize in JavaScript, it would be similar to this:
var title = "The An A Catalog Title";
title = title.replace("The ", "");
title = title.replace("An ", "");
title = title.replace("A ", "");
console.log(title);
Which will log:
Catalog Title
title being what each title would look like to the ORDER BY sort
Does that make sense?
More info:
https://bertwagner.com/posts/how-to-eliminate-ugly-nested-replace-functions/
I hope that helps.
Stay safe and happy coding!