Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sanainfotech's avatar

The SQL SELECT DISTINCT Statement

Hi I want to run a query just give me value with no duplicate.

What would be the query in laravel 5 using eloquent.

SQL query:

SELECT DISTINCT column_name
FROM table_name;
SELECT DISTINCT `ad_advertiser` FROM `adverts`
0 likes
12 replies
tykus's avatar
tykus
Best Answer
Level 104

Fluent:

DB::table('table_name')->distinct()->get(['column_name']);

Eloquent:

MyModel::distinct()->get(['column_name']);
19 likes
sanainfotech's avatar

Hi @tykus_ikus

I want to populate distinct value from only one column of the table.

SELECT DISTINCT `ad_advertiser` FROM `adverts`
frezno's avatar
$query = DB::table('adverts')->distinct()->get(['ad_advertiser']);
sanainfotech's avatar

Hi @tykus_ikus

I would like to display distinct value and ignor any row with empty value How can I achieve in laravel 5 using model - elequent this as below

SELECT DISTINCT meta_value 
FROM `wp_postmeta` 
WHERE  meta_value != "";
tykus's avatar

Assumed you called you model Meta

Meta::distinct()->whereNotNull('meta_value')->get(['meta_value']);
3 likes
scottu's avatar

I did not see the correct answer - so here

DB::table('adverts')->distinct()->select('ad_advertiser')->get()

1 like
Alderwiereld's avatar

what happens when you want to fetch data from other columns while still maintaining a column value that is to be distinct

4 likes
gregrobson's avatar

@Alderwiereld DISTINCTwill return unique combinations of values. If you select three columns then DISTINCT will show unique combinations of the three columns (or unique "tuples" in database terminology).

If you want to use those unique values in another query then the easiest option is to put them in the FROM clause.

SELECT
    products.*
FROM
    -- Get all the distinct product_id's of ordered products.
    -- (i.e. only show each product once, regardless of how many
    -- times it has been ordered.
    (SELECT DISTINCT product_id FROM orders) AS purchased_products
    -- join back onto product table to show the full details of only
    -- those products that have been ordered.
    INNER JOIN products ON purchased_products.product_id = products.product_id

Obviously there are better ways than using DISTINCT for the query above, but it's the simplest way to demonstrate the concept.

1 like
myawat255's avatar

try groupBy function Like this:

tableName::select('column Name')->groupBy('ColumnName')->get();

1 like

Please or to participate in this conversation.