Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP vs MySQL Performance ( if , functions ) in query

I just see this artice

i need to know what's is best berformance in this cases

if statment in query

SELECT *,if( status = 1 , "active" ,"unactive") as status_val FROM comments

VS

<?php
    $x = mysql_query("SELECT * FROM comments");

     while( $res = mysql_fetch_assoc( $x ) ){
       if( $x['status'] == 1 ){
             $status_val = 'active';
        }else{
             $status_val = 'unactive';
        }
     }
  ?>

Cut 10 from string

SELECT * , SUBSTR(comment, 0, 10) as min_comment FROM comments

VS

<?php
    $x = mysql_query("SELECT * FROM comments");

     while( $res = mysql_fetch_assoc( $x ) ){
       $min_comment = substr( $x['comment'],0,10 ) ;
     }
  ?>

etc ????? and When i use MYSQL functions or PHP functions ?

like image 522
Mona Abdelmajeed Avatar asked Nov 01 '12 11:11

Mona Abdelmajeed


Video Answer


3 Answers

It depends. From a network point of view, in the first VS, PHP wins and in the second VS, MYSQL wins. That's because you send less data via socket. And thus the script becomes faster.

like image 75
ioan Avatar answered Oct 12 '22 22:10

ioan


Here is a nice description of your question: Doing calculations in MySQL vs PHP

In case of the second example the speed issue can be significant. First of all you do not know how big are your comments, so in case of

$x = mysql_query("SELECT * FROM comments");

 while( $res = mysql_fetch_assoc( $x ) ){
   $min_comment = substr( $x['comment'],0,10 ) ;
 }

you ask your server to return you everything (here I mean the whole length of the comment) and this can be significant. Multiplying by the number of rows in the table it can be quite big size of data, which you have to transfer between php and sql. In the second case this SELECT * , SUBSTR(comment, 0, 10) as min_comment FROM comments this will be already done on the server and will not require additional memory.

In case of the first example, I think it is also better to do it on sql side, because you will still need to do additional loop afterwards. Apart from this, people who will be reading your code might be confused why exactly do you need that code.

like image 41
Salvador Dali Avatar answered Oct 13 '22 00:10

Salvador Dali


In that case, using MySQL functions keeps you from looping in PHP and saves you a lot of code.

In other cases they have no alternative : for instance, when you use them in the WHERE part.

In terms of performance, the difference is trivial in most cases : use the simplest solution.

like image 36
theredled Avatar answered Oct 12 '22 23:10

theredled