Grab a certain amount of database entries from a table - mysql

Is there a way to grab an exact amount of entries from a database example. For example say you had a table that just had an id and total visits for the columns. Say you wanted to grab exactly 20 entries and sort them by total visits. How would you go about this? I know how to sort the whole table, but would like to be able to grab the top twenty total visits and then sort them. Thanks
O and right now I am using sqlite, but I know in the future I will be using mysql also. Thanks

Try with:
SELECT * FROM TableName ORDER BY TotalVisits LIMIT 20

using limit to get the top 20,
and if you want to add another sort, add it after visit column
like :
SELECT * FROM mytable ORDER BY visits DESC
/*here put another order by field like date */
, date
LIMIT 20

Use ORDER - LIMIT clause
SELECT * FROM table ORDER BY field [ASC|DESC] LIMIT 20 OFFSET [offset value]

You need to use LIMIT, but you will need to put the whole thing in a subquery if you intend to re-sort the top 20 based on separate criteria. So
SELECT * from <table> order by <total visits column> LIMIT 20
will get you the top 20, but then to sort within that result you would do something like
SELECT * from
(SELECT * from <table> ORDER BY <total visits column> LIMIT 20)
ORDER BY <other criteria>

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants, with these exceptions:
With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):
SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15
To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:
SELECT * FROM tbl LIMIT 95,18446744073709551615;
With one argument, the value specifies the number of rows to return from the beginning of the result set:
SELECT * FROM tbl LIMIT 5; # Retrieve first 5 rows
In other words, LIMIT row_count is equivalent to LIMIT 0, row_count.
All on: http://dev.mysql.com/doc/refman/5.5/en/select.html better explnation for mysql, however sqlite works same way: http://www.sqlite.org/lang_select.html

Related

How to select rows above #

I'm currently trying to setup a query that only selects from a row number and upwards from it. I've tried to use the LIMIT method in this way:
SELECT name FROM names LIMIT 1500, *
Which I expected to select from row number 1500 till the table's rows ended, but got a MySQL error instead.
I then tried to use a conditional for the ID of the rows like so:
SELECT name FROM names WHERE id >= 1500
Which gave unpredictable behavior since there are rows that get deleted, so it's not taking the real row numbers.
I think offset will do what you want. Unfortunately, MySQL requires a LIMIT value, but you can just put in a ridiculous number:
SELECT name
FROM names
OFFSET 1499
LIMIT 999999999;
you could use a subquery
select name
from names
where id > (
select max(id)
from names
order by names
limit 1500
)

Return a subset of matching results in a MySQL query

I have a MySQL DB containing elements and keywords. If someone searches for an element by keyword they could get a huge number of hits. Rather than returning ALL elements that match, I'd like to do the equivalent of returning the nth group of m elements. This would allow me to display the first m matching elements, then get and display the next m matching elements, etc.
As a concrete example, imagine I have a DB of images and I search using the keyword "ball", and there are 500 total matches, I'd like to query the DB to return the first 50, then the second 50, etc. Assuming the order of the elements is deterministic (using ORDER BY), I don't know how to sub-select a subset of those matching elements.
Thanks for any help.
You can add a LIMIT condition to your query, which allows you to specify a number of results, and a result offset.
Example:
SELECT * FROM table WHERE keyword = 'ball' LIMIT 0, 50
Which would give you the first 50 results starting at result offset 0..
To get the next 50 you just change this to:
SELECT * FROM table WHERE keyword = 'ball' LIMIT 50, 50
Which gives you 50 results starting at result offset 50.
Normally when you're coding pagination (Offering pages 1, 2, 3 of a result set), you pass the offset you want to begin at in the URL, in order to run the same query but get results starting from a different offset.
SELECT keyword, otherfield from table
WHERE keyword LIKE '$keywordvar%'
ORDER BY whatever ASC
Then, use the LIMIT clause:
To limit your query to the first 50 use:
LIMIT 50;
To limit your query to the second 50 use:
LIMIT 50, 50;
To limit your query to the third 50 use:
LIMIT 100, 50;
You can change the values to either larger or smaller sets.
Your final query would then look something like:
SELECT keyword, otherfield from table
WHERE keyword LIKE '$keywordvar%'
ORDER BY whatever ASC
LIMIT 50;
Or if your not using wildcard searching and looking for specific keyword values:
SELECT keyword, otherfield from table
WHERE keyword = 'ball'
ORDER BY whatever ASC
LIMIT 50;

Query next 30 records by alphabetical order

Let say I retrieve my list of data...
First
$Query = mysql_query("SELECT * FROM data ORDER BY name ASC LIMIT 0,30");
From there I am using AJAX/jQuery to to append an additional 30 records. Which I need to call another file where the query will pick up where I left off.
Second
$Query = mysql_query("SELECT * FROM data WHERE name < '".mysql_real_escape_string($_GET['lastRecord'])."' ORDER BY name ASC LIMIT 0,30");
My question is, if I have the first query order the first 30 by name, how can I write the second query to pick up where I left off in that order?
Change the LIMIY like this - LIMIT 30, 30
BTW, you tagged this as jQuery and it isn't.
This option is good for short tables, but in a long tables this will give bad performance.
Every query (like that) you execute will do full table scan with filesort which takes some time.
I think you need to read the table once, and put the result in a temporary table (already sorted) with some index column and then use WHERE index BETWEEN $number AND ($number+30).
You don't need to add a WHERE clause to your query, you just need to use LIMIT to slice out the chunks of results you want. Limit is used to limit your MySQL query results to those that fall within a specified range. You can use it to show the first X number of results, or to show a range from X - Y results. The syntax is Limit X, Y where X is the starting point and Y is the number of records to retrieve.
For example:
$Query = mysql_query("SELECT * FROM data ORDER BY name ASC LIMIT 90,30");
would retrieve 30 records beginning with the 91st (records are zero indexed).
The first number in the LIMIT clause is the offset, starting at 0. So, your first query is correctly LIMIT 0, 30 to get the first 30.
Simply increase the offset by 30 to start at record 31, so to get 30 more do LIMIT 30, 30.
For the third page, it would be LIMIT 60, 30, etc.
If you need a page x of n type display, issue a COUNT(*) first to get the total number of rows, but understand that the actual rows and row count may change if rows are being inserted or deleted between calls.

How does MySQL process ORDER BY and LIMIT in a query?

I have a query that looks like this:
SELECT article FROM table1 ORDER BY publish_date LIMIT 20
How does ORDER BY work? Will it order all records, then get the first 20, or will it get 20 records and order them by the publish_date field?
If it's the last one, you're not guaranteed to really get the most recent 20 articles.
It will order first, then get the first 20. A database will also process anything in the WHERE clause before ORDER BY.
The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).
With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):
SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15
To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:
SELECT * FROM tbl LIMIT 95,18446744073709551615;
With one argument, the value specifies the number of rows to return from the beginning of the result set:
SELECT * FROM tbl LIMIT 5; # Retrieve first 5 rows
In other words, LIMIT row_count is equivalent to LIMIT 0, row_count.
All details on: http://dev.mysql.com/doc/refman/5.0/en/select.html
Just as #James says, it will order all records, then get the first 20 rows.
As it is so, you are guaranteed to get the 20 first published articles, the newer ones will not be shown.
In your situation, I recommend that you add desc to order by publish_date, if you want the newest articles, then the newest article will be first.
If you need to keep the result in ascending order, and still only want the 10 newest articles you can ask mysql to sort your result two times.
This query below will sort the result descending and limit the result to 10 (that is the query inside the parenthesis). It will still be sorted in descending order, and we are not satisfied with that, so we ask mysql to sort it one more time. Now we have the newest result on the last row.
select t.article
from
(select article, publish_date
from table1
order by publish_date desc limit 10) t
order by t.publish_date asc;
If you need all columns, it is done this way:
select t.*
from
(select *
from table1
order by publish_date desc limit 10) t
order by t.publish_date asc;
I use this technique when I manually write queries to examine the database for various things. I have not used it in a production environment, but now when I bench marked it, the extra sorting does not impact the performance.
You could add [asc] or [desc] at the end of the order by to get the earliest or latest records
For example, this will give you the latest records first
ORDER BY stamp DESC
Append the LIMIT clause after ORDER BY
If there is a suitable index, in this case on the publish_date field, then MySQL need not scan the whole index to get the 20 records requested - the 20 records will be found at the start of the index. But if there is no suitable index, then a full scan of the table will be needed.
There is a MySQL Performance Blog article from 2009 on this.
You can use this code
SELECT article FROM table1 ORDER BY publish_date LIMIT 0,10
where 0 is a start limit of record & 10 number of record
LIMIT is usually applied as the last operation, so the result will first be sorted and then limited to 20. In fact, sorting will stop as soon as first 20 sorted results are found.
Could be simplified to this:
SELECT article FROM table1 ORDER BY publish_date DESC FETCH FIRST 20 ROWS ONLY;
You could also add many argument in the ORDER BY that is just comma separated like: ORDER BY publish_date, tab2, tab3 DESC etc...

MySQL skip first 10 results

Is there a way in MySQL to have the first 10 result from a SELECT query skipped?
I'd like it to work something like LIMIT.
Use LIMIT with two parameters. For example, to return results 11-60 (where result 1 is the first row), use:
SELECT * FROM foo LIMIT 10, 50
For a solution to return all results, see Thomas' answer.
There is an OFFSET as well that should do the trick:
SELECT column FROM table
LIMIT 10 OFFSET 10
OFFSET is what you are looking for.
SELECT * FROM table LIMIT 10 OFFSET 10
From the manual:
To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:
SELECT * FROM tbl LIMIT 95,18446744073709551615;
Obviously, you should replace 95 by 10. The large number they use is 2^64 - 1, by the way.
LIMIT allow you to skip any number of rows. It has two parameters, and first of them - how many rows to skip
To skip first 10 rows use OFFSET 10, but LIMIT is also required,
If you want to get all the rows and only skip first 10 rows try using a big number like 999999999 or as per your choice
SELECT * FROM table LIMIT 999999 OFFSET 10
select * from table where id not in (select id from table limit 10)
where id be the key in your table.
If your table has ordering by id, you could easily done by:
select * from table where id > 10