Home > database >  SQL: get rows "under" chosen row
SQL: get rows "under" chosen row

Time:02-16

I have a table like that

id name
1 qwe
2 asd
3 sdf
4 xcv
5 try

and I need to select all rows "under" chosen name (i.e. name = 'asd'), and after that sort it by 'id' and limit to 2, so I'm seeking a result like:

id name
3 sdf
4 xcv

I tried to select it as SELECT * FROM TableName WHERE name < 'asd' ORDER BY id DESC LIMIT 2

However, "name < 'asd'" only means the rows where name-value is less than 'asd', so I get nothing because there are no values less than 'asd'. In my case, I need to select all rows "under" 'asd' name.

CodePudding user response:

try like below

select id,name from table_name
where id > ( select id from table_name where name='asd')
order by id
limit 2

demo link

CodePudding user response:

SELECT *
FROM TableName
WHERE id > (SELECT id FROM TableName WHERE name = 'asd')
ORDER BY id DESC
LIMIT 2;
  • Related