Simple Eloquent query taking too long time to execute Simple Eloquent query taking too long time to execute laravel laravel

Simple Eloquent query taking too long time to execute


first of all you are using 2 queries into one.

This is the first query:

$currencies = Currency::where('sys_name', 'openexchangerates')            ->orderBy('currency')            ->get();  

And this is another:

\DB::raw('DISTINCT currency_code_from AS currency')

In order to use both queries into one, you should use this:

$currencies = Currency::selectRaw('DISTINCT currency_code_from AS currency')            ->where('sys_name', 'openexchangerates')            ->orderBy('currency')            ->get();   

I hope this way will decrease the executing time.


Just leaving this answer as it might be useful for the people who already tried applying indexing and query optimization, but didn't manage to reduce time significantly.

I have managed to reduce query loading time from 1.76 s to 0.127 s.

I have solved the problem by using some "walkaround". Since the currency rate is changing everyday for every single available currency, I am just getting the biggest currency_rate_batch_id, and getting all the currencies associated with this id (allows me to quickly get all distinct currencies).

However, I will apply indexing (as @Josh suggested) and avoid double queries throughout the project (as suggested by @Nicolas).


As @Nikolas said changing from select(DB::raw.. to selectRaw(... will help with the speed.

The other thing that you will want to check is your indexing on the main columns of your table.

I am assuming that you are using Mysql and so look at the below docs on indexing

https://dev.mysql.com/doc/refman/5.5/en/optimization-indexes.html

Having indexes on the key columns of tables can make a big difference to the speed of queries

The Docs have details about adding indexes through migrations here:

https://laravel.com/docs/5.5/migrations#indexes