tags:

views:

48

answers:

1

How can I select a particular row from a table?

I want to do achieve something like the following:

select * from 
    (select * from tablename1 where type=1 order by id desc) 
where rownum = 5

select * from 
    (select * from tablename1 where type=1 order by id desc) 
where rownum = $variable
+3  A: 

Use the LIMIT keyword:

SELECT * FROM tablename WHERE (stuff...) LIMIT $rownum,1;

If you pass 2 numbers to LIMIT, it treats the first as an offset and the second as a number of results to return (whereas if you pass only 1 number, it just treats it as a number of results). Thus asking for LIMIT $rownum,1 you'll get back only one row, which is the one at position $rownum (keep in mind that rows are indexed starting from 0).

Amber
This is a MySQL keyword. What the OP posted above is PL/SQL syntax. SQL Server uses `row_number() over (order by col)`. And now you know.
Eric
Actually, what the OP posted was valid mysql syntax as well (at least, not counting the row number bit which is what they were asking about in the first place). Not to mention their comment stating they're using mysql.
Amber
@Dav: `rownum` is not a function in MySQL, and the OP posted that comment *after* mine. And I am not a time traveler. Yet. You get +1 for the now correct answer :)
Eric
thanks man it worked for for mysql . I was looking fo same
@Eric yes, but they were looking for something *like* what they posted - if they were looking for what the posted, why would they be asking here? :) Anywho, no worries.
Amber
@ dav,eric @brian i have posted one more questions on SQL plz help me. http://stackoverflow.com/questions/805169/random-row-from-mssql-db-using-dlinq