How to Concantenate Strings

A word of warning about concatenating with sql, if the data used is one that is created by a user where query strings are created dynamically, there could be a possibility of an sql injection. This method is best used for outputting information you have in a database. For example, let’s say you have a products table and you want to concatenate the product name and price.

SELECT CONCAT (productName, ” , ” , price) FROM products;

The output would be: XBOX, $399

You can see the power in this function. We could just as well add some text modifiers:

SELECT CONCAT (productName, ” , “”Buy it Now,” , price) FROM products;

The output would be: XBOX, Buy it Now, $399

The Concat operator is used mainly by mysql. Other database engines such as Oracle use the “||” operator.

Bookmark it and Share These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • ThisNext
  • BlinkList
  • Bumpzee
  • De.lirio.us
  • Furl
  • Ma.gnolia
  • NewsVine
  • Reddit
  • Spurl
  • StumbleUpon
  • Technorati
  • YahooMyWeb
How to Use the Trim FunctionHow to Use sql Aggregate Functions

3 Comments so far

  1. […] the price we concatenated with a string? What if we wanted to see the average price of all our the products in our products table? SELECT […]

  2. […] running more complex queries, such as concatenating strings, often times you may need to trim whitespace from the […]

  3. João Almeida on October 7th, 2008

    Is it possible to use the CONCAT function to define the name of the table in a SELECT ?
    For example:

    SELECT id, name FROM (CONCAT(’table’,(SELECT number FROM tablenumber),’series’))

    I need to do something that the table name depends on an other SELECT, unfortunatly my problem is that I can only use one query to do it.

    And thoughts!?
    Thanks in advanced

Leave a reply