How to Retrieve Raw SQL Queries Using Laravel and Doctrine Query Builders

When you're developing an application and working with database queries, sometimes you need to see the exact SQL query your query builder is generating. This can be extremely helpful for debugging and optimization. In this article, we'll go over how to do this with a few different tools and techniques.

Overview

Being able to see the raw SQL generated by your query builder is a common need during development. This guide will show you how to extract raw SQL queries in various scenarios and with different query builders.

Methods for Extracting Raw SQL

Using Laravel's Query Builder

Laravel's Eloquent ORM makes it easy to get the raw SQL query. Here's how you can do it:

Basic Query To get the raw SQL of a query:

$query = DB::table('users')->where('id', 1);
$sql = $query->toSql();
echo $sql;

This will output:

select * from `users` where `id` = ?

With Bindings If your query has bindings (parameters), you can merge them with the raw SQL to see the complete query:

$query = DB::table('users')->where('id', 1);
$sql = $query->toSql();
$bindings = $query->getBindings();

$fullSql = vsprintf(str_replace('?', '%s', $sql), $bindings);
echo $fullSql;

You will then have the entire SQL query since the placeholders (?) will be replaced with the real binding values.

Using Query Builder for Doctrine

If you are using Doctrine, you may use the following method to get the raw SQL:

Accessing SQL

$qb = $this->createQueryBuilder('u')
           ->where('u.id = :id')
           ->setParameter('id', 1);

$sql = $qb->getQuery()->getSQL();
echo $sql;

This will produce the Doctrine query's raw SQL output.

Things to Keep in Mind

When dealing with raw SQL queries, here are a few tips to keep in mind:

Safety

It is imperative to avoid logging or displaying raw SQL queries in production situations since this may reveal confidential data and leave your application open to SQL injection attacks.

Performance

Generating and logging raw SQL can affect your app's performance. Use these techniques mainly for debugging and development.

Compatibility

Different query builders and ORMs have their own ways of getting raw SQL. Be sure to check the documentation for the tools you're using.

Conclusion

Seeing the raw SQL created by your query builder is a valuable tool for developers. Whether you're using Laravel, Doctrine, or another query builder, understanding how to extract and analyse raw SQL may help you diagnose and optimise database interactions.

For further information and particular use cases, consult the official documentation for your query builder or ORM.

References

Similar Articles