I have the below syntax where I sorted the the date order, my default is autocommit enabled, however when I reopen the table it is not sorted again, is there some other syntax I should write to the below to make it permanent?
Thanks
SELECT *
FROM stock_price.spy1996
ORDER BY Date ASC;
You are misunderstanding several very important concepts in SQL.
First, changes to the database occur (generally) through UPDATE, INSERT, and DELETE. These are the changes that are committed.
Second, SELECT does not change the database.
Third, SQL tables represent unordered sets. If you want the results from a query to be in a particular order, then you have to use an ORDER BY clause.
If you like, you can implement a view that does this automatically:
CREATE VIEW v_spy_1996 as
SELECT *
FROM stock_price.spy1996
ORDER BY Date ASC;
Then when you query from the view, you will not have to repeat the ORDER BY.
Related
There are many solutions in stackoverflow itself where the objective was to read the last n rows of the table using either an auto-increment field or timestamp: for example, the following query fetches the last ten records from a table named tab in the descending order of the field values named id which is an auto increment field in the table:
Select * from tab order by id desc limit 10
My question is: Is there any alternative way without having to get an auto increment field or timestamp to accomplish the task to get the same output?
Tips: The motivation to ask this question comes from the fact that: as we store records into tables and when query the database with a simple query without specifying any criteria like :
Select * from tab
Then the order of the output is same as the order of the records as inserted into the table. So is there any way to get the records in the reverse order of what they were entered into the database?
Data in mysql is not ordered- you don't have any guarantee on the order of the records you'll get unless you'll specify order by in your query.
So no, unless you'll order by timestamp, id, or any other field, you can't get the last rows, simply because there's no 'last' without the order
In the SQL world, order is not an inherent property of a set of data.
Thus, you get no guarantees from your RDBMS that your data will come
back in a certain order -- or even in a consistent order -- unless you
query your data with an ORDER BY clause.
So if you don't have the data sorted by some id or some column then you cannot track the data based on its sorting. So it is not guaranteed how MYSQL will store the data and hence you cannot get the last n records.
You can also check this article:
Caveats
Ordering of Rows
In the absence of ORDER BY, records may be returned in a different
order than the previous MEMORY implementation.
This is not a bug. Any application relying on a specific order without
an ORDER BY clause may deliver unexpected results. A specific order
without ORDER BY is a side effect of a storage engine and query
optimizer implementation which may and will change between minor MySQL
releases.
So I have an unordered table movement that has columns timestamp,x,and y. I want to order by timestamp, and change and save the table to have the all rows ordered by timestamp.
I wanted to use UPDATE TABLE but I'm unsure on how the query would look... for example, I have this:
UPDATE movement
SET ?????
ORDER BY timestamp;
I don't want to set anything, I just want to change the order of the table. I need to do this for another query that I'm going to write, but the fact is that this table is very large and I need to break up things in steps so that the performance isn't terrible later. So how would I do this? I found this SO post that addressed a similar question, but I was wondering if there was another way to do it rather than use another table, because as I said, this table is very large(millions of rows) and recopying the table would take a long time.
Tables don't inherently have an order; you don't have to update them into any particular order.
What you do is choose the order of what you SELECT from the table. Then it can be in any order you choose!
Example:
SELECT * FROM movement
ORDER BY timestamp;
But then somewhere else maybe you want to:
SELECT * FROM movement
ORDER BY timestamp DESCENDING;
You can't use ORDER BY in UPDATE statement. ORDER BY should be used with SELECT statement only. Again, there is no need of having the records stored in particular order cause you can just display the records in particular order with a SELECT statement like
select * from movement
order by timestamp
Relational database tables represent unordered sets. There is no syntax for sorting a table, simply because there is no such concept as the order of rows in a table. When you issue a query without an explicit order by clause, the database may return the rows to you in any order it may see fit, which might be influenced by the order they were inserted and written to disk, their presence in some memory cache, indexes, or a host of other implementation details.
If you want to query the table's rows sorted by their timestamp, just explicitly state it in the order by clause:
SELECT *
FROM `movement`
ORDER BY `timestamp`
It is actually possible. This is in MySQL format... Update is for editing already existing information. If you want to make more direct changes, use ALTER or MODIFY according to syntax.
ALTER TABLE movement
ORDER BY timestamp;
This is a simple question about efficiency specifically related to the MySQL implementation. I want to just check if a table is empty (and if it is empty, populate it with the default data). Would it be best to use a statement like SELECT COUNT(*) FROM `table` and then compare to 0, or would it be better to do a statement like SELECT `id` FROM `table` LIMIT 0,1 then check if any results were returned (the result set has next)?
Although I need this for a project I am working on, I am also interested in how MySQL works with those two statements and whether the reason people seem to suggest using COUNT(*) is because the result is cached or whether it actually goes through every row and adds to a count as it would intuitively seem to me.
You should definitely go with the second query rather than the first.
When using COUNT(*), MySQL is scanning at least an index and counting the records. Even if you would wrap the call in a LEAST() (SELECT LEAST(COUNT(*), 1) FROM table;) or an IF(), MySQL will fully evaluate COUNT() before evaluating further. I don't believe MySQL caches the COUNT(*) result when InnoDB is being used.
Your second query results in only one row being read, furthermore an index is used (assuming id is part of one). Look at the documentation of your driver to find out how to check whether any rows have been returned.
By the way, the id field may be omitted from the query (MySQL will use an arbitrary index):
SELECT 1 FROM table LIMIT 1;
However, I think the simplest and most performant solution is the following (as indicated in Gordon's answer):
SELECT EXISTS (SELECT 1 FROM table);
EXISTS returns 1 if the subquery returns any rows, otherwise 0. Because of this semantic MySQL can optimize the execution properly.
Any fields listed in the subquery are ignored, thus 1 or * is commonly written.
See the MySQL Manual for more info on the EXISTS keyword and its use.
It is better to do the second method or just exists. Specifically, something like:
if exists (select id from table)
should be the fastest way to do what you want. You don't need the limit; the SQL engine takes care of that for you.
By the way, never put identifiers (table and column names) in single quotes.
The default ordering ID of records in mysql is ASC (i.e. Rows that i insert goes down the table) but we'll be using only the latest information from the table (i.e. Rows that are below).
Will there be any performance improvements if we change the default ordering to DESC (i.e New records goes to the top of the table) and frequent information will be queried from top of the table.
I think it would be the opposite.
I'm basing this comment on how I understand indexes to work in SQL Server-I'll try to revise later if I get a chance to read up more on how they work in MySQL.
There could be a slight performance advantage to insert your rows in the same order as your index is sorted, versus inserting them in the opposite order.
If you insert in the same order, and your next row to insert is always greater in sort order than existing rows then you will always find the next available empty spot (when one exists) in your last page of rows data.
If you do the opposite, always have your next insert row lesser in sort order than existing rows then you will probably always have a collision in your first page of rows data and the engine will do a tad bit more work to shift the position of rows if the page has room for it.
As for your order by clause in the select statement:
1) there's nothing in the SQL standard about indexes, and nothing that guarantees your result set ordering except for the ORDER BY clause. Normally queries in SQL Server that use just one index will see results returned in the order of the index. But if the isolation level changes to "read uncommitted" (chaos?) then it will return rows in more likely in the order it finds them in memory or on disk which is not necessarily the order you want.
2) If the order by in your select statement is based on the exact same column criteria as the index, then your database server should perform the same with either the index order, or the opposite of the index order. This is pretty straightforward except perhaps if you have a multi-column index with mixed ASC-DESC declarations for different columns. You get away with equal performance with order by equal to index order and with order by equal to inverse index order where the inverse index order is determined by substituting the ASC and DESC declarations (explicit and implicit) in the index declaration with DESC and ASC in the order by clause.
Any performance change would be on querying the records, not inserting one.
For queries, I doubt this will have much affect as database queries by keys usually have similar speeds.
It also depends on your data so I would run some tests.
I'm dealing with a legacy database table that has no insertion date column or unique id column, however the natural order of insertion is still valid when examined with a simple SELECT * showing oldest to newest.
I'd like like to fetch that data with pagination but reverse the order as if it was ORDER BY date DESC
I've thought about wrapping the query, assigning a numeric id to the resulting rows and then do an ORDER BY on the result but wow that seems crazy.
Is there a more simple solution I am overlooking?
I cannot add columns to the existing table, I have to work with it as is.
Thanks for any ideas!
Use #rownum in your query to number each row and then order by the #rownum desc. Here's an example.
select #rownum:=#rownum+1 ‘rank’, p.* from player p, (SELECT #rownum:=0) r order by score desc limit 10;
Finally, beware that relying on the current order being returned long-term isn't recommended.
If you're writing an application to process the data, another approach might be to run your current query, then iterate over the returned records from last to first.
If you have too many records, then you may wish to instead use a view. This is a Database object which can be used to combine data from different tabls, or present a modified view of a single table, amongst other things. In this case, you could try creating a view of your table and add a generated ID column. You could then run SELECT statements against this view ordering by the new column you have added.
However be aware of the advice from another poster above: the order in which rows are returned without an ORDER BY clause is arbitrary and may change without notification. It would be best to amend your table if at all possible.
mySQL CREATE VIEW syntax