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.

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.
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:
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
2. Combine raw SQL with conditions
3. Use raw expressions for computed columns
4. Always validate user inputs if using raw queries
Never inject variables directly without sanitizing. Use bindings:
5. Use selectRaw()
with joins for better performance
6. Use aliases (as
) for clarity
7. Cache raw query results if they're expensive
What is the difference between selectRaw and dbRaw in Laravel
Feature | DB::raw() | selectRaw() |
---|---|---|
Type | Helper to write raw SQL expressions | Shortcut for raw SQL in select() |
Flexibility | Can be used in many places | Only used for SELECT |
Syntax | Slightly longer | Cleaner 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