Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Yasir Bilal's avatar

How can this query be optimized, if possible?

Hello everyone

Please review my query and provide recommendations to optimize it further. Currently, the query takes approximately 7 seconds to execute against 1.4 million records.

The 7 second execution time for the query is not a big problem. The real issue arises when users apply different filters on the product page to filter product information.

The current issue is that due to the database structure when users select filters on the product page, the same query has to be executed three times to filter the data.

we have around 10m records that's why we can't change the database structure

query i create

$filterInfo = DB::table('product_info')
            ->select(DB::raw("GROUP_CONCAT(DISTINCT product_info.qty) as Qty,
                GROUP_CONCAT(DISTINCT product_info.finishing) as ProductFinshing,
                GROUP_CONCAT(DISTINCT  product_info.lamination) as ProductLamintion,
                GROUP_CONCAT(DISTINCT product_info.binding) as ProductEdge, 
                GROUP_CONCAT(DISTINCT product_info.printed) as ProductPrnted, 
                GROUP_CONCAT(DISTINCT product_info.fold) as ProductFold, 
                GROUP_CONCAT(DISTINCT product_info.cut) as ProductCut, 
                GROUP_CONCAT(DISTINCT product_info.spot) as ProductSpot, 
                GROUP_CONCAT(DISTINCT product_info.sets) as ProductSet, 
                GROUP_CONCAT(DISTINCT product_info.cover) as ProductCover"))
            ->where(
					array(
							'size' => "A5", 
							'paper' => "350gsm",
 							'printer' => "Double",
							 'id' => 1
					)
			);

GROUP_CONCAT and DISTINCT is used to get only unique value and then combine multiple values into a comma-separated list

When this query is executed three times due to the filter's page load, it takes approximately 21 to 25 seconds.

Please if you guys can share your point of view on this anyway i can make it work fast

0 likes
2 replies
Snapey's avatar

For slow moving data (like parsing the unique values in the database), this can be cached

Yasir Bilal's avatar

@Snapey, thank you for the reply. The problem I'm facing is that I have a total of 12 dropdowns, and the first 3 dropdowns are used to filter data for the remaining 9 dropdowns. If the user changes the value in the 4th dropdown, then the first 4 dropdowns are used to filter data for the remaining 8 dropdowns. In other words, each dropdown's options depend on the values selected in the previous dropdowns. Additionally, every time a dropdown value changes, new data needs to be populated in the dependent dropdowns. Due to this dynamic and interdependent nature of the dropdowns, it becomes challenging to implement caching

i hope i am able to explain the workflow

Please or to participate in this conversation.