I have a DB filled with 100k products, here is my query
$products = DB::table('product')
->leftJoin('product_description', 'product_description.product_id', 'product.product_id')
->leftJoin('product_to_category','product_to_category.product_id','product.product_id')
->select(self::$select_fields)
->where('product_description.language', $language)
->groupBy('product.product_id');
if (!empty($filter->keyword)) {
$products->where('product_description.title','LIKE','%'. $filter->keyword .'%');
}
if (!empty($filter->category_id)) {
$products->where('product_to_category.category_id','=',$filter->category_id);
}
if (!empty($filter->range)) {
$range= explode(',',$filter->range);
$products->whereBetween('product.price', [$range[0], (!empty($range[1]))? $range[1] : $range[0]]);
}
return $products->orderBy('product.product_id','DESC')->where('product.status',1)->limit(50);
This query loads in 12.6 seconds. If i remove ->orderBy('product.product_id','DESC')
, the query runs in 0.800ms.
In my Database I have index keys on product_description.product_id , product_to_category.product_id and product.id is set to primary
I've seen around that orderBY desc slows down alot with big databases, is there a workaround, i need to order it by DESC because i want the "Latest" uploaded, I've tried setting it on "created_at" column but it's about the same
EDIT
I tried without Laravel, basically the speed is about the same, ordering by DESC slows down the query, is there a solution to this in general or basically DESC is just slow and it should be avoided with BIG databases?