tags:

views:

1812

answers:

6

Which do you think is faster in a php script:

$query = "SELECT... FROM ... ORDER BY first_val";

or

while($row = odbc_fetch_array($result))
    $arrayname[] = array( "first_key" => $row['first_val'],
                          "second_key" => $row['second_val'],
                          etc...
                         );

sort($arrayname);
+10  A: 

It depends on so many factors that I don't even know what to begin with.

But as a rule, you perform sorting on database side.

Indexes, collations and all this, they help.

Quassnoi
+1. Pitching your code against database just leads to heartbreaks.
Learning
+1, but try karim79's answer (timing tests) just to be sure.
altermativ
Actually, there are cases when the client side sort is faster, and I even used this in one of my applications. Timing tests will fail on ellipses in the SELECT and FOR clause, and we don't know what to substitute for them.
Quassnoi
+2  A: 

If the ordered field is indexed, I'd say probably the SQL query. If not, I'm not sure, but I can't imagine it will be overly noticeable either way unless you're dealing with an absurdly large number of rows.

orthod0ks
+2  A: 

ORDER BY will almost always be faster.

Ward Werbrouck
+3  A: 

Which do you think is faster in a php script:

The ORDER BY doesn't execute in the PHP script -- it executes in the database, before data is retrieved by the PHP script. Apologies if this seems pedantic, I just want to make sure you understand this.

Anyway, the reason I would use ORDER BY is that the database has access to indexes and cached pages from the database. Sorting in PHP sorts the data set in memory of course, but has no access to any index.

Bill Karwin
Thanks for the clarification...I do understand, just tried to give ya'll a little context.
W_P
+2  A: 

In my opinion, nothing beats actually timing the thing so you really, really know for sure:

$time_start = microtime(true);

// Try the ORDER BY and sort($array) variants here

$time_end = microtime(true);
$time = $time_end - $time_start;

echo "It took $time seconds";
karim79
+2  A: 

If there's a LIMIT on the first query, and the set of rows the query would match without the LIMIT is much larger than the LIMIT, then ORDER BY on the query is DEFINITELY faster.

That is to say, if you need the top 50 rows from a 10,000 row table, it's much faster to have the database sort for you, and return only those top 50 rows, than it is to retrieve all 10,000 rows and sort them yourself in PHP. This is probably representative of the vast majority of what will happen in real-world applications

If there are any cases at all in which sorting in PHP is even comparable, they're few and far between.

Additionally, SQL sorting is much more powerful -- it's trivial to sort on multiple columns, subqueries, the return values of aggregate functions etc.

Frank Farmer