Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP Integrating PHP with Databases Limiting Records in SQL Filtering Data by Category

Nested 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

Hi 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!