Skip to content
Advertisement

Laravel: Multiple queries vs stored procedures

In my application, I need to show the log of the selected subscriber’s previous payments, except the current one. The log comes from the same table called payments.

Here is my code:

public function _paymentLog($token)
{
    # models
    $Self = new self();

    # fetching subscriber
    $subscriberId = $Self
        ->where('token', $token)
        ->select('subscriber_id')
        ->first()
        ->subscriber_id ?? null;

    if($subscriberId == null)
        return null;

    # returning
    return $Self
        ->where('subscriber_id', $subscriberId)
        ->where('token', '<>', $token)
        ->orderBy('id', 'DESC')
        ->get() ?? null;
}

Would it be a good idea to make a stored procedure instead of writing the logic in the application. As the stored procedure is inside the database and will run the queries faster. On the other hand, the application executes the first query, then check and then execute the final query, which I think is a time consuming method..?

Advertisement

Answer

The saving from a sproc will be the extra round-trip time. If your server is reasonably local, this is unlikely to be significant. If you were issuing many queries to retrieve a si glad data set, then a sproc would make sense.

Sprocs help a lot when:

1) You are throwing a lot of data to/from the server to compute the final data set (bandwidth and parsing savings)

2) When you have many queries to the server when you could send a single function call with a few parameters I stead (round trip time savings).

In this specific instance, it doesn’t look like you will save a lot, unless this function gets executed many, many times.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement