Is it possible to grab the last n inserts in a relational table without using a Date field ?
For example in the table Author:
Author(authid, f_name, l_name)
Also, authid is not a natural number (eg. 1,2,3,4..) but a string (example: JohnM32015)
I am using MySQL.
If the authid is auto-increment then you can do
select * from author
order by authid desc
To get only a limited number of records use top n in SQL-Server or limit n in MySQL for instance.
A table doesn't have a guaranteed sort order. A query does, if it explicitly defines one. If, for example, your records have an incrementing authid value then the last N inserts would be the highest N values for that column. So you'd order by that column descending and take the top N:
SELECT * FROM Author ORDER BY authid DESC LIMIT 10
However you define "the last N", you specify that definition in your query in a descending sort order and take the top N records from that result.
If, as you say, you want the "most recent" 10 records, you would write your query just like the other answers say, but order by the field(s) that defines your case for "most recent". Like this:
SELECT * FROM MyTable ORDER BY <your date field(s)> DESC LIMIT 10;
Disclaimer: If you don't have data in the table to define whatever should be the "most recent" records (like a "DateInserted" field, or an auto-incrementing field), then you don't really have an easy way of doing this with SQL.
Related
I want to write a query to select a subset of a table, only starting from a given id.
I know about limit x, y, but x here is the number of the raw to start from. But in my case I want to start from a specific Id, no matter what its location inside the table.
What I mean is that the query below selects from row number 5, but I want it to select 10 records from row with id, say 213odin2d211d21:
SELECT * FROM my_table Limit 5, 10
I can't find a way to do this. Any help will be appreciated.
Note that, the Id here is a mix of strings and integers. So I can't do
SELECT * FROM <table> WHERE id > (id)
What you want to do is not possible. By default, records in the database are not ordered. Without ORDER BY you can't expect the server to return your queries in any particular order. Since you are saying, that you store some kind of digit/char identifier as your id, for which less then and greater then are not defined, it is not clear which records "follow" your specific record.
You will either have to:
Define another column to sort your records on, or
Define a behaviour for comparing your ids (What is "less then"? What is "greater then"?)
That being said, you can of course define that you want to sort your id just like sorting strings! In this case, you can use STRCMP() to compare two strings. Your query would look like this:
SELECT * FROM <table> WHERE STRCMP(id,?) = 1 ORDER BY id LIMIT 10
This will select the first 10 records, with id "greater than" ?.
I have an EAV table in SQL which as usual has several records for each ID. Each of these records has a numerical value in a column called 'weight' and I'm trying to sort this table so that for each ID the records are ranked in descending order of weight. This is going to be a one off process because I intend to make sure that data is sorted when it goes into the table in future.
Also is the normal protocol for doing something like this to SELECT all of the data, sort it the way you want, and then use the REPLACE command to replace the old data in the table?
I know that I can do this for one id by doing:
SELECT * FROM my_table WHERE id = 'X' ORDER BY weight DESC
but I need to somehow do this for each id in my table. How is this normally done?
you will ALWAYS return the data in the order you wish in this case:
SELECT * from theTable order by id, weight desc
you do not store the data in any particular order. (even if you try this will not matter).
Remove the WHERE clause and add id to ORDER BY. This way, your result set will be ordered first by id, and for each id, it will be ordered by weight.
SELECT * FROM my_table ORDER BY id, weight DESC
I am trying to create a search engine from a mysql datadase which displays information in order based on the value of one of the columns in the row, so if row x has a 'quantity' column
with an integer value of 10 any row y has a 'quantity'value of 20, row x should be echoed first so the greatest value is on top and the least on the bottom (no preference for equal values). or alliteratively find a way that the mysql table automatically orders the data this way. is there some kind of function that I could use. thanks
Use the ORDER BY clause Like this:
SELECT * FROM table ORDER BY quantity DESC
To return rows from a query in a specific order, use the ORDER BY clause. To get them returned from highest to lowest values, specify the DESC (descending) keyword. For example:
SELECT f.quantity
FROM foo f
ORDER BY f.quantity DESC
You are correct, there is no guarantee as to how the rows will be physically ordered when they are stored. Your ONLY guarantee is the ORDER BY clause.
How can I SELECT the last row in a MySQL table?
I'm INSERTing data and I need to retrieve a column value from the previous row.
There's an auto_increment in the table.
Yes, there's an auto_increment in there
If you want the last of all the rows in the table, then this is finally the time where MAX(id) is the right answer! Kind of:
SELECT fields FROM table ORDER BY id DESC LIMIT 1;
Keep in mind that tables in relational databases are just sets of rows. And sets in mathematics are unordered collections. There is no first or last row; no previous row or next row.
You'll have to sort your set of unordered rows by some field first, and then you are free the iterate through the resultset in the order you defined.
Since you have an auto incrementing field, I assume you want that to be the sorting field. In that case, you may want to do the following:
SELECT *
FROM your_table
ORDER BY your_auto_increment_field DESC
LIMIT 1;
See how we're first sorting the set of unordered rows by the your_auto_increment_field (or whatever you have it called) in descending order. Then we limit the resultset to just the first row with LIMIT 1.
You can combine two queries suggested by #spacepille into single query that looks like this:
SELECT * FROM `table_name` WHERE id=(SELECT MAX(id) FROM `table_name`);
It should work blazing fast, but on INNODB tables it's fraction of milisecond slower than ORDER+LIMIT.
on tables with many rows are two queries probably faster...
SELECT #last_id := MAX(id) FROM table;
SELECT * FROM table WHERE id = #last_id;
Almost every database table, there's an auto_increment column(generally id )
If you want the last of all the rows in the table,
SELECT columns FROM table ORDER BY id DESC LIMIT 1;
OR
You can combine two queries into single query that looks like this:
SELECT columns FROM table WHERE id=(SELECT MAX(id) FROM table);
Make it simply use: PDO::lastInsertId
http://php.net/manual/en/pdo.lastinsertid.php
Many answers here say the same (order by your auto increment), which is OK, provided you have an autoincremented column that is indexed.
On a side note, if you have such field and it is the primary key, there is no performance penalty for using order by versus select max(id). The primary key is how data is ordered in the database files (for InnoDB at least), and the RDBMS knows where that data ends, and it can optimize order by id + limit 1 to be the same as reach the max(id)
Now the road less traveled is when you don't have an autoincremented primary key. Maybe the primary key is a natural key, which is a composite of 3 fields...
Not all is lost, though. From a programming language you can first get the number of rows with
SELECT Count(*) - 1 AS rowcount FROM <yourTable>;
and then use the obtained number in the LIMIT clause
SELECT * FROM orderbook2
LIMIT <number_from_rowcount>, 1
Unfortunately, MySQL will not allow for a sub-query, or user variable in the LIMIT clause
If you want the most recently added one, add a timestamp and select ordered in reverse order by highest timestamp, limit 1. If you want to go by ID, sort by ID. If you want to use the one you JUST added, use mysql_insert_id.
You can use an OFFSET in a LIMIT command:
SELECT * FROM aTable LIMIT 1 OFFSET 99
in case your table has 100 rows this return the last row without relying on a primary_key
Without ID in one query:
SELECT * FROM table_name LIMIT 1 OFFSET (SELECT COUNT(*) - 1 FROM table_name)
SELECT * FROM adds where id=(select max(id) from adds);
This query used to fetch the last record in your table.
What's the most efficient way to select the last n number of rows in a table using mySQL? The table contains millions of rows, and at any given time I don't know how large the table is (it is constantly growing). The table does have a column that is automatically incremented and used as a unique identifier for each row.
SELECT * FROM table_name ORDER BY auto_incremented_id DESC LIMIT n
Actually the right way to get last n rows in order is to use a subquery:
(SELECT id, title, description FROM my_table ORDER BY id DESC LIMIT 5)
ORDER BY tbl.id ASC
As this way is the only I know that will return them in right order. The accepted answer is actually a solution for "Select first 5 rows from a set ordered by descending ID", but that is most probably what you need.
(Similar to "marco"s answer,)
my fav is the max()-function of MySQL too, in a simple one-liner, but there are other ways of sure:
SELECT whatever FROM mytable WHERE id > (SELECT max(id)-10 FROM mytable);
... and you get "last id minus 10", normally the last 10 entries of that table.
It's a short way, to avoid the a error 1111 ("Invalid use of group function") not only if there is a auto_increment-row (here id).
The max()-function can be used many ways.
Maybe order it by the unique id descending:
SELECT * FROM table ORDER BY id DESC LIMIT n
The only problem with this is that you might want to select in a different order, and this problem has made me have to select the last rows by counting the number of rows and then selecting them using LIMIT, but obviously that's probably not a good solution in your case.
Use ORDER BY to sort by the identifier column in DESC order, and use LIMIT to specify how many results you want.
You would probably also want to add a descending index (or whatever they're called in mysql) as well to make the select fast if it's something you're going to do often.
This is a lot faster when you have big tables because you don't have to order an entire table.
You just use id as a unique row identifier.
This is also more eficient when you have big amounts of data in some colum(s) as images for example (blobs). The order by in this case can be very time and data consuming.
select *
from TableName
where id > ((select max(id) from TableName)-(NumberOfRowsYouWant+1))
order by id desc|asc
The only problem is if you delete rows in the interval you want. In this case you would't get the real "NumberOfRowsYouWant".
You can also easily use this to select n rows for each page just by multiplying (NumberOfRowsYouWant+1) by page number when you need to show the table backwards in multiple web pages.
Here you can change table name and column name according your requirement . if you want to show last 10 row then put n=10,or n=20 ,or n=30 ...etc according your requirement.
select * from
(select * from employee
Order by emp_id desc limit n)
a Order by emp_id asc;