Alicia Sykes
Alicia Sykes

Reputation: 7107

How to fetch one of each record from table with an SQL query?

I have table containing information about a series of x number of quizzes. It includes a field for ID, Name, Subject and Level.

I would like to be able to fetch all the subjects once, so not the duplicates, because some quizzes will have the same subject.

I am then going to populate a drop down menu with this result and allow user to use it to filter their search results - if I can!

What I am stuck on is the SQL query, and I would be so grateful for any suggestions, thanks in advance!

Upvotes: 0

Views: 168

Answers (5)

Matt
Matt

Reputation: 1242

Assuming Subject is a text field containing something like Math or English.

select distinct subject from quizzes 

Or for db's that lake distinct

select subject from quizzes group by subject

It is 'proper' however if you normalize subject/level into its own table since that information is probably repeated over and over for each quiz.

Upvotes: 1

keyboardP
keyboardP

Reputation: 69372

This will bring back everything from the subject column, but without the duplicates.

SELECT DISTINCT Subject FROM myTableName

You may find that you may be better off having a separate Subject table instead of having everything in one big table.

Upvotes: 1

Erwin Brandstetter
Erwin Brandstetter

Reputation: 657617

SELECT subject FROM tbl GROUP BY subject;

Does the same as DISTINCT in this case.

Upvotes: 1

Shyju
Shyju

Reputation: 218812

If you are looking for subjects without duplicate values

SELECT DISTINCT Subject FROM YourTable

Upvotes: 1

fge
fge

Reputation: 121760

distinct is what you want:

select distinct subject from thetable;

Add an order by if you need/want to.

Upvotes: 1

Related Questions