Habitat
Habitat

Reputation: 709

SQL Query to return the first row and only the first row that satisfies a condition

I have a table of randomly generated keys that I want to use as registration keys for my website.

The table layout is as follows:

id|     regkey         |inUse

1 |nxwn362oe6jn4ses8psl|y
2 |nmin875euytoises7sil|n

I need to return the first row that satisfied the condition n for the inuse column.

How can I tailor my query to only pull one row? So far I obviously have:

Select `regkey` FROM `database` WHERE `inUse` = n 

but where do I go from here?

Thanks in advance

Upvotes: 3

Views: 1997

Answers (3)

Jens
Jens

Reputation: 69505

If you use mysql you can use limit:

Select `regkey` FROM `database` WHERE `inUse` = n order by id limit 1

if you use sql-server you can use top

Select top 1 `regkey` FROM `database` WHERE `inUse` = n order by id

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172628

In MYSQL it would be

Select `regkey` FROM `database` WHERE `inUse` = n limit 1

and in SQL server

Select top 1 `regkey` FROM `database` WHERE `inUse` = n 

Upvotes: 1

Abhik Chakraborty
Abhik Chakraborty

Reputation: 44874

You can use limit

Select regkey FROM database WHERE inUse = n limit 1

Upvotes: 1

Related Questions