Laravel SQL Tricks: When and How to Use selectRaw() vs DB::raw() with example

When working with complex queries in Laravel, understanding the difference between selectRaw() and DB::raw() can significantly boost your productivity and code readability. In this article, we’ll break down both methods, provide actionable tips, and show real-world use cases to write cleaner, more efficient queries in Laravel.

Laravel SQL Tricks: When and How to Use selectRaw() vs DB::raw() with example Image

What is DB::raw() in Laravel?

DB::raw() allows you to write raw SQL expressions inside Laravel’s query builder. It’s incredibly flexible and can be used in where(), orderBy(), select(), groupBy(), and more.

DB::table('orders')
    ->select(DB::raw('SUM(total_amount) as total_sales'))
    ->where('status', 'completed')
    ->get();

Best Use: When you need raw SQL anywhere in your query.


What is selectRaw() in Laravel?

selectRaw() is a shortcut for writing raw select statements. Instead of wrapping your SQL with DB::raw(), you can write directly:

DB::table('orders')
    ->selectRaw('SUM(total_amount) as total_sales')
    ->where('status', 'completed')
    ->get();

 Best Use: When your raw SQL is used in the SELECT clause only.


Tips to Use selectRaw() and DB::raw() Effectively

1. Use selectRaw() for clean aggregate functions

User::selectRaw('COUNT(*) as total_users, status')
    ->groupBy('status')
    ->get();

2. Combine raw SQL with conditions

User::where(DB::raw('DATE(created_at)'), '=', now()->toDateString())->get();

3. Use raw expressions for computed columns

Product::selectRaw('price * quantity as total_value')->get();

4. Always validate user inputs if using raw queries

Never inject variables directly without sanitizing. Use bindings:

DB::table('users')
    ->whereRaw('email = ?', [$email])
    ->get();

5. Use selectRaw() with joins for better performance

DB::table('orders')
    ->join('users', 'orders.user_id', '=', 'users.id')
    ->selectRaw('users.name, COUNT(orders.id) as total_orders')
    ->groupBy('users.name')
    ->get();

6. Use aliases (as) for clarity

DB::table('posts')->selectRaw('COUNT(*) as published_count')->get();

7. Cache raw query results if they're expensive

$report = Cache::remember('sales_report', now()->addMinutes(30), function () {
    return DB::table('sales')->selectRaw('SUM(amount) as total')->first();
});

 

What is the difference between selectRaw and dbRaw in Laravel

FeatureDB::raw()selectRaw()
TypeHelper to write raw SQL expressionsShortcut for raw SQL in select()
FlexibilityCan be used in many placesOnly used for SELECT
SyntaxSlightly longerCleaner for raw SELECT queries

Final Thoughts

Laravel gives you powerful tools like DB::raw() and selectRaw() for building dynamic, raw queries while keeping your code clean and expressive. Mastering them helps you:

  • Write complex SQL without raw database connections

  • Optimize performance

  • Keep queries readable and maintainable

Do you Like?