1

I'm curious what the runtime cost of sorting a small set of elements returned by a MySQL query is in PHP in contrast to sorting them in MySQL.

Reason I can't sort them in MySQL is because of the groups of data being returned, (actually 2 queries and then bringing data together PHP side).

Thanks!

3 Answers 3

3

There will be no difference for ten elements. But generally you should always sort in MySQL, not PHP. MySQL is optimized to make sorting fast and has the appropriate data structures and information.

PS: Depending on the nature of the data you want to combine: Look at JOINs, UNIONs and subqueries. They'll probably do it.

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah I didnt think it would matter for so few elements. The bigger question I guess is "whats the cost of UNION in MYSQL", I tend to shy away from them and subqueries in the name of performance.
@csjohn: fairly minimal. the cost of the two individual queries and (default) eliminating dupes, so no more expensive than 2 queries + select distinct on the whole results.
2

My opinion:

The overhead is negligible in either case. Optimize your productivity and do whichever is easier for you. The computer is there to help you, not vice versa.

If you really want to optimize the host, have you considered letting the client do it in javascript?

I'd probably do it in SQL too, but mainly to keep the logic in one place (increase cohesion, reduce coupling).

1 Comment

I like the cut of your jib. I can't do that in this particular case, but I do indeed like to offload work to the clients.
1

you could combine the queries with a union and then sort it with mysql

Q1
UNION
Q2
ORDER BY X

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.