I have created a database in MySQL. When I try to get all the records for a table, the last-added records are displayed last. How can I efficiently display the latest records first, without using a datetime column? Adding a datetime column would mean reinitializing all tables, which seems too troublesome to me.
How can I efficiently display the latest records first, without using
a datetime column?
If you have an auto increment ID column you could try ordering by the record ID in descending order.
e.g.
SELECT * FROM my_table ORDER BY id DESC;
To follow on from the previous answer many ORMs inster CreatedAt and UpdatedAt columns. Slap an ORDER BY CreatedAt DESC and there you have it in the order you want and it's independent of the Id you use.
does you table have a index? then you could
SELECT * FROM table ORDER BY index DESC
Use ORDER BY on an appropriate (time-ordered) column. As stated above, you can use an auto-incremented primary key, however this doesn't allow you to select a date range.
FWIW, it's not difficult to add timestamp columns to existing tables, and you gain the ability to return rows within a range of dates.
Approximate syntax:
ALTER TABLE `table_name`
ADD COLUMN `created_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;
ALTER TABLE `table_name`
ADD INDEX `created_time` (`created_time`);
Related
I want to display the logs to recent activities page ordered by date. Now I was trying to execute this to my mysql
"SELECT * FROM tracking_log.editlog, tracking_log.deletelog, tracking_log.loginlog, tracking_log.logoutlog ORDER BY time ASC";
but it always says
Column 'time' in order clause is ambiguous
all of the tables have a time column, format by datetime (0000-00-00 00:00:00)
How am I going to fetch them ordered by time?
Thanks in advance!
By which table's time column you want to order?
Assuming you want to order the result set by tracking_log.editlog.time column then the query would look like below:
SELECT
*
FROM tracking_log.editlog, tracking_log.deletelog,
tracking_log.loginlog, tracking_log.logoutlog
ORDER BY tracking_log.editlog.time ASC;
Just in case if all of the time columns in the respective table don't contain NOT NULL values at the same time then you need to use COALESCE I guess.
Query using COALESCE
SELECT
*
FROM tracking_log.editlog, tracking_log.deletelog,
tracking_log.loginlog, tracking_log.logoutlog
ORDER BY
COALESCE(tracking_log.editlog.time , tracking_log.deletelog.time, tracking_log.loginlog.time,tracking_log.logoutlog.time) ASC;
'tracking_log' is your database name, and you're selecting multiple tables from that database, so you need to specify from which table you want to order 'time' by:
select * from tracking_log.editlog, tracking_log.deletelog ORDER BY tracking_log.editlog.time ASC
or whichever table from your database you want to use 'time' from. This will fix the error but won't return any results because you have multiple tables in a SELECT clause without anything relating them together.
You'll need to specify some common columns on which you want to return results rather than getting the wildcard and then UNION the tables to aggregate the results. For example, if you have common columns userID, description and time in all your tables, you could do the following:
(SELECT userID, description, time FROM tracking_log.editlog)
UNION
(SELECT userID, description, time FROM tracking_log.deletelog)
ORDER BY time
I have one Sql Query to get all the informations from my table.
I created an list using an foreach.
And i want to order this list, by the last updated row.
Like this
$query - "SELECT * FROM table ORDER BY last_updated_row";
//call Query here
And when i updated a certain row, i want to put this row on the top of the list
I heard about time_stamp, can i use time_stamp for that?
how can i do that?
Thanks
Assuming your using MySQL your table needs to be like this
CREATE TABLE table (
last_updated_row TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
That will give the row a create time stamp and update it on each update statement which effects the row
http://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html
You can use just about any date/datetime/timestamp column in a table to sort by if needed. The only catch is you need to actually have it in the table.
Any of the above will allow sorts by ascending/descending order, but need to be maintained when inserting/updating a row.
Assuming you have the following structure:
table - someTable
id someVale updateTime
1 54634 ......
2 65138 ......
3 94141 ......
4 84351 ......
It doesn't matter what type of column updateTime is - whether it is a date, a datetime, a timestamp, a simple order by updateTime will work.
But you need to make sure that each insert/update you make to that row updates the column so that the sort will be true.
I have a table A which has a auto increment serial number field SLNO. When i insert values in table it will increment automatically like 1,2,3,4... etc. But when i delete a row from the table the order get break. ie, if delete row with serial number 2 then the serial number field will 1,3,4. But I want to maintain a continuous order like 1,2,3 even delete rows. Is there any way to maintain this order, like using trigger or somthing
A primary auto-increment key is only for uniquely identifying a record. Just leave it be.
Don't misuse the primary key as indicator of your record order. If you need specific order of your records then use an extra column for that. For instance a timestamp column.
If you need a specific order of your records use a timestamp column with a default value of current_timestamp. That way it will be inserted automatically.
ALTER TABLE your_table
ADD column inserted_timestamp TIMESTAMP default current_timestamp;
SQLFiddle demo
You should leave it as it is.
However, if you do really need, you can "recalculate" the primary key, the index:
set #pk:=0;
update
your_table
set pk=#pk:=#pk+1
order by pk;
add a column that will speicfy that is deleted
example:
1 - deleted already
0 - not deleted
and add where deleted = 0 in your select query
primary key column 2 column3 ..... deleted
1 1
2 0
3 0
4 1
5 0
Storing an number of a record would make deletes inefficient. Instead you can rely on existing SLNO indexes you already have, that should be enough for all use cases that come up to my mind.
If you SELECT whatever ORDER BY SLNO LIMIT ... OFFSET k, then returned rows have IDs k, k+1, k+2, ...
If you want to get an id of a record knowing its SLNO:
SELECT COUNT(SLNO) FROM A WHERE SLNO <= thatnumber
If you want to get thatnumber'th record:
SELECT * FROM A ORDER BY SLNO LIMIT 1 OFFSET thatnumber
You can do by alter the table and delete primary key then again create primary key.
But why you need this. If you have use this key as foreign key in other table. Then you lost all the data.
I need to create an InnoDB table that I will use to add data to and constantly fetch the most recent 10 rows added to it. To avoid having to do an ORDER BY with every SELECT query to get those last 10 rows, I would like to have the table itself ordered by the Primary Key in DESC order so that I can skip the ORDER BY entirely and just do a SELECT ... LIMIT 10, which should automatically pull the most recent 10 rows added to the table.
How can I do that? Is it as simple as adding ORDER BY [PRIMARYKEY] DESC to the CREATE TABLE query? Will the table continue to be sorted in DESC order even after INSERTing new rows?
A RDBMS never provides any guarantees on the order of the rows in any of the tables it manages. The only way to get a specific order is to ask for one. For the case of MySQL, the rows happens to be sorted by the primary key in ascending order often time when that key is in auto increment mode, but it's not a guaranteed property.
Use ORDER BY on your queries to get the desired result.
On the other hand, the ordering will be faster if the primary key type is BTREE (which is the default on most engine).
The sorting direction isn't yet used on MySQL 5.5.
What SQL query would I use to display the newest entry?
Details:
id is the primary field. I have other fields but that are not related to when they were added.
ORDER BY SomeColumn DESC
LIMIT 1
or
use the MAX() function
Since you didn't give any details about your table it is hard to answer
SELECT * from yourTable ORDER BY `id` DESC LIMIT 1;
Another (better) way would be to have a "date_added" column (date_added TIMESTAMP DEFAULT CURRENT_TIMESTAMP) so you could order by that column descending instead. Dates are more reliable than ID-assignment.
not sure if this is what your looking for but I use mysql_insert_id() after inserting a new row
The auto incremented ID columns are not always the latest records inserted, I've remember really painful experience with this behavior. Conditions where specific, it was mysql 4.1.x at the time and there was almost 1 million records, where 1 out of 3 deleted everiday, and others re inserted in the next 24hours. It made a huge mess when I realize ordering them via ID was not ordering them by age....
Since then, I use a specific column for doing age related sorts, and populating these fields with date = NOW() at each row insert.
Of course it will work to found the latest record as you want, doing an ORDER BY date DESC LIMIT 0,1on your query
SELECT Primary_Key_Field FROM table ORDER BY Primary_Key_Field DESC LIMIT 1
Replace Primary_Key_Field and table obviously :)