0d: 00h: 00m: 00s

🎁 Get 3 extra months of learning — completely FREE

That's 90 extra days to master new skills, build more projects, and land your dream job.

Become a PRO
Background Image

🎁 Get 3 extra months of learning completely FREE

Become a PRO
OTM Egytrans
PRO
2 weeks ago
Otmcountry asked

Can I use DISTINCT on one column but not on another in the same SQL query?

Kelish Rai
Expert
last week
Kelish Rai answered

Hello OTM Egytrans, really nice question.

In SQL, DISTINCT doesn’t belong to just one column once you write it — it applies to the entire set of selected columns together.

So:

SELECT DISTINCT col1
FROM your_table;

gives you unique values of col1.

But:

SELECT DISTINCT col1, col2
FROM your_table;

now treats each (col1, col2) pair as a single combination. SQL removes duplicate rows where both col1 and col2 are the same. It does not make col1 distinct while allowing col2 to vary freely in that same query.

That means there’s no direct way to say “make column 1 distinct, but don’t apply DISTINCT to column 2” in one simple SELECT DISTINCT col1, col2 statement.

If you want “distinct by column 1” and still show something from column 2, you usually:

  • either decide which row per col1 you want (for example, with MIN(col2) or MAX(col2) plus GROUP BY col1), or

  • use more advanced techniques (like window functions) depending on your database.

But the key idea is:
DISTINCT always works on the whole selected row, not just a single column unless you only select that one.

If you have further questions, I'm here to help.

SQL
This question was asked as part of the Learn SQL Basics course.