3

Are there any performance concerns of note when using MySQL's CONCAT() function in a select query? Is it faster/slower/negligible to do a simple select, and format strings for a view using PHP after the result set from the database is returned? Or is a more complicated SQL query with multiple calls to CONCAT() that returns a string already formatted for the view a better approach?

ie is this:

select CONCAT(lastname, ', ', firstname) from people;

Faster/Slower/No difference from this:

<?php
    $query = 'Select lastname, firstname from people';
    ...

    $name = $data['lastname'] . ', ' . $data['firstname']; //OR
    $name = sprintf("%s, %s", $data['lastname'], $data['firstname']);
?>
Sam Heuck
  • 585
  • 5
  • 15

2 Answers2

2

You're better off in almost all cases by doing filtering and data massaging with the SQL engine versus on the web server.

LJ Wilson
  • 14,445
  • 5
  • 38
  • 62
  • I know this is old, but why? Can you provide some link? – Francisco Presencia Nov 17 '12 at 17:05
  • 1
    Well, some searching will provide sources, but the main difference is that the SQL engine doesn't have to instantiate objects and already knows the schema of the data. If you do this on the web-server (using PHP, C# or whatever), you will lose these benefits. While realistically, this wouldn't even be noticeable unless you were doing lots of this, it is still best practice to do this kind of work in SQL – LJ Wilson Nov 17 '12 at 22:02
1

Unless you are planning to do hundreds of thousands such operations at once, it will not matter where you do the string concatenation from a performance point of view. The possible time savings will be so minuscule, they will probably not even be measurable.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088