MySQL: Use CONCAT to include text in SELECT results

The CONCAT function in MySQL allows SELECT statements to act like printf commands by mingling text and query results together.


For example, to generate a quick list of links in HTML from a table ‘links’ with the columns ‘url’ (http://www.tech-recipes.com) and ‘title’ (Tech-Recipes) so that the output looks like:

Tech-Recipes

use a select statement like:

SELECT CONCAT('<a href="', url, '">', title, '</a><br />') FROM links;

The CONCAT function simply joins the comma-separated list of strings and expressions (in this case column results from the query: url and title). As with any SELECT statement, the result set can be varied with the use of an optional WHERE clause and other valid SQL syntax.

 

About Quinn McHenry

Quinn was one of the original co-founders of Tech-Recipes. He is currently crafting iOS applications as a senior developer at Small Planet Digital in Brooklyn, New York.
View more articles by Quinn McHenry

The Conversation

Follow the reactions below and share your own thoughts.

5 Responses to “MySQL: Use CONCAT to include text in SELECT results”

  1. March 31, 2009 at 12:41 am, mark said:

    sux. the formatting is screwed by the CMS…also the descriptive text is ultra-terse…

    Reply

  2. April 25, 2009 at 10:09 am, axinos said:

    and it still has not been fixed! ;-(

    please fix the recipe or remove it – not to waste the time of your fellow/following chefs ;-)

    Reply

    • April 25, 2009 at 4:17 pm, Quinn McHenry said:

      Oops! Sorry about that! It’s been fixed now. We had to fix hundreds of posts when we migrated to a new CMS, but this one escaped detection! Thanks for pointing it out.

      Reply

  3. May 13, 2011 at 9:44 am, Thieuhuann said:

    It wrong

    Reply

  4. February 19, 2014 at 5:21 am, suvarna said:

    is it possible for concatinating of two text values;

    Reply

Leave a Reply