Mysql – search for something in the first 1000 records in the table

MySQL

If I do the following MySQL query

select * from table where name Like '%john%' limit 5;

that mean the query will search all the mysql database table and return only the top 5 results that match the query where condition.

BUT, what if want to just search the top 1000 records in the database table that match the where condition and return only the first 5 rows , because I have 1,000,000 records in the table and i just want to search in the first 1000 records, what should i use?

this is the wanted query in human readable:

search the top 1000 records from the table which have the name like john and return only the top 5 records that match.

what is the corresponding in MySQL

Best Answer

You could use something like this:

SELECT *
FROM (
  SELECT *
  FROM your_table
  ORDER BY ...
  limit 1000
) s
WHERE name LIKE '%john%'
ORDER BY ...
LIMIT 5