Do you have indexes set up on your search fields. Perhaps you need to drill down more.
Mar 15, 2025
9
Level 3
It takes a long time to perform count()
I have this in laravel:
// Getting the request filters
$cnaes = $request->input('cnae', []); // Selected CNAEs
$location = $request->input('location', []); // Location
$state = $request->input('state', ''); // State
$startDate = $request->input('startDate', ''); // Start date
$endDate = $request->input('endDate', ''); // End date
$status = $request->input('status', ''); // Status
$size = $request->input('size', ''); // Company size
$legalNature = $request->input('legalNature', []); // Legal nature
$capital = $request->input('capital', ''); // Share Capital
$mei = $request->input('mei', ''); // MEI option
// Start the query
$query = Establishment::query();
// Filtering by CNAE
if (!empty($cnaes)) {
$query->whereIn('cnae_principal', $cnaes);
}
// Filtering by location
if (!empty($location)) {
$query->whereIn('logradouro_municipio', $location);
}
// Filtering by state
if (!empty($state)) {
$query->where('logradouro_uf', $state);
}
$query->whereBetween('data_abertura_corrigida', [$startDate, $endDate]);
// Filtering by status
if (!empty($status)) {
$query->where('registration_status', $status);
}
// Filtering by size
if (!empty($size)) {
$query->whereHas('empresa', function($query) use ($size) {
$query->where('company_size', $size);
});
}
// Filtering by legal nature
if (!empty($legalNature)) {
$query->whereHas('empresa', function($query) use ($legalNature) {
$query->whereIn('legal_nature', $legalNature);
}); }
// Filtering by share capital
if (!empty($capital)) {
// Example: Filtering by capital ranges
if ($capital == '1') {
$query->whereHas('empresa', function($query) use ($capital) {
$query->where('capital_social_num', '<=', 10000);
});
} elseif ($capital == '2') {
$query->whereHas('empresa', function($query) use ($capital) {
$query->whereBetween('capital_social_num', [10001, 100000]);
});
} elseif ($capital == '3') {
$query->whereHas('empresa', function($query) use ($capital) {
$query->where('capital_social_num', '>', 100000);
});
}
}
if (!empty($mei)) {
$query->whereHas('empresa.simples', function ($query) use ($mei) {
$query->where('simples.opcao_pelo_mei', $mei);
});
}
// Returning the quantity or other data as needed
return response()->json(['quantidade' => $query->count()]);
the idea is to query the data according to the filters selected by the user. However, the database contains over 64 million records, and the way I'm doing it is extremely slow, since my intention is just to count the numbers. And in some cases, it seems that the more filters, the slower it gets (but not always), I don't understand this behavior.
Could anyone give me any suggestions for improvement?
note: All columns are properly indexed
Please or to participate in this conversation.