Laravel Query Builder: Select Distinct Records

Updated: January 16, 2024 By: Guest Contributor Post a comment

Introduction

Laravel, as a modern PHP framework, offers an elegant, expressive database query builder that eases the tasks of interacting with your database. Among its numerous capabilities, one notably powerful feature is the ability to pull distinct records out of a database. This tutorial will explore how to utilize the query builder to retrieve distinct records, delving from the fundamental concepts to more nuanced implementations.

Understanding the concept of ‘distinct’ operations is vital. Essentially, a ‘distinct’ query is used when you want to fetch unique records from a database table, removing any duplicate entries based solely on the columns you’ve specified.

Getting Started with Distinct

Firstly, to make any query in Laravel, you must use the Eloquent model or the database facade. We’ll focus on the latter in this tutorial. Before jumping into code examples, ensure you’ve set up a Laravel project and have a database with some records to work with.

Basic Distinct Query

$uniqueUsers = DB::table('users')
               ->distinct()
               ->get();

This piece of code queries the ‘users’ table and retrieves a collection of user records without duplicates. Here, the distinctness is determined based on all columns.

Distinct With Specific Columns

$uniqueEmails = DB::table('users')
                  ->distinct()
                  ->get(['email']);

With the modification above, the database now selects distinct records based solely on the ’email’ column, ignoring other fields that may have duplicate values.

Counting Distinct Records

Sometimes, we don’t need the records themselves but an actual count of distinct entries. The query builder handles this scenario smoothly.

$countDistinctUsers = DB::table('users')
                      ->distinct()
                      ->count('id');

This returns the count of unique user IDs in your ‘users’ table.

Combine Distinct With Other Clauses

Laravel’s Query Builder allows for chaining other methods with the distinct() clause, providing a more selective query.

Distinct With Where Clause

$activeUsers = DB::table('users')
                ->distinct()
                ->where('status', 'active')
                ->get(['country']);

Now, we’re selecting distinct user countries, but only for users with an ‘active’ status by including a ‘where’ clause.

Distinct Along with Ordering

$orderedDistinctUsers = DB::table('users')
                        ->distinct()
                        ->orderBy('created_at', 'desc')
                        ->get(['city']);

In this query, we’re fetching unique cities the users belong to, and we’re ordering the records based on the ‘created_at’ timestamp.

Aggregating Distinct Records

When it comes to aggregating data, such as summing up values, you can still adhere to fetching distinct values.

Summing Distinct Values

$sumDistinctSales = DB::table('sales')
                    ->distinct()
                    ->sum('amount');

The query above will sum distinct sale amounts, ensuring that no duplicate sale records skew your summation.

Joining Tables with Distinct

In real-world scenarios, you’ll often need to join tables and retrieve distinct values to avoid duplicate data due to relationships.

Distinct With Join

$distinctProducts = DB::table('orders')
                     ->join('order_details', 'orders.id', '=', 'order_details.order_id')
                     ->distinct()
                     ->get(['order_details.product_id']);

Now, we fetch distinct ‘product_id’ values from a joined ‘order_details’ table, only selecting unique instances of products across different orders.

Advanced Usage of Distinct

For more complex scenarios, Laravel allows for raw expressions, which can be very handy when dealing with distinct queries.

Distinct With Raw Expressions

$usersWithUniqueStatus = DB::table('users')
                          ->selectRaw('DISTINCT(status)')
                          ->get();

This code utilizes a raw SQL expression to fetch unique user statuses, which can sometimes give more control over the outcome.

Conclusion

In this tutorial, we’ve explored the diverse applications of the distinct clause in Laravel’s query builder. Through basic to advanced examples, it’s clear that distinct can play a crucial role in data retrieval for real-world applications, ensuring clarity and preventing data duplication.