I'm new to SQL and I don't think this question should be hard to answer. I have a high-score table for a game that contains the columns name, score, and rank. I want to know how I can order the table by descending order each time a new score is added so the table can always stay ordered by score.
I know this is the wrong way of doing this, but I hope this makes my point kind of clearer.
UPDATE `HSTable`.`Highscores` ORDER BY `Highscores`.`score` DESC;
What is the correct way of approaching this?
One more thing, is there a way I can set it so that the ranking value always stays where it's suppose to be from the SQL, for example, 1st place is always at the top regardless the score?
generally we use order by while fetching data from table
so we use
SELECT * FROM `HSTable` ORDER BY `score` DESC
Use a ranking function like RANK or DENSE_RANK to rank the results. For better performance you can add a clustered index that starts with score descending.
You can get ordered results using SELECT clause:
SELECT * FROM `HSTable` ORDER BY `score` DESC
I don't believe the order of the data in your database table should really matter because when you query the data you can sort it any which way you would like. What is the reason why you want to have the data stored in the database in the correct order?
That is not the correct way to select records in SQL. Use this instead:
SELECT * FROM `tablename` ORDER BY `id` DESC
Related
I ordered my results by their id's by:
CREATE TABLE my_table2 AS SELECT * FROM my_table ORDER BY record_group_id;
now when i execute:
SELECT DISTINCT record_group_id FROM my_table2 where rownum <=1000000;
I get gorup id's in random order, though my order by went fine:
Here is few of the records in result set
1599890050
1647717203
1647717120
1647717172
1647716972
1647717196
1647717197
1647717205
1599889999
1599889986
What could be the possible reason?
Shouldn't DISTINCT statement return records in same order as they are in table?
Neither SELECT or DISTINCT defines the order of data.
If you want ordered data explicitly define the Order you need.
SELECT DISTINCT record_group_id
FROM my_table2
WHERE rownum <=1000000
ORDER BY record_group_id;
The ordering only determines the order of the source data that is inserted in the table. If there is no clustered index in the table, that means that the records will be stored in that order physically.
However, how the records are stored doesn't guarantee that they will be selected in that order. The execution planner determines the most efficient way to run the query, which means that the data might not be fetched the way that you think it is, and it can differ from time to time as the data changes, or just the statistics about the data.
For a simple query like in the example, you usually get a predictable result, but there is no guarantee, so you always need to sort the query where you fetch the data to be sure to get a predictable result.
One reason that you don't get the data in the order that they are stored in the table in this case, may be that an index is used for filtering the result, and the records are returned in the order of the index rather than the order of the table.
Use ORDER BY on your SELECT statement:
SELECT DISTINCT record_group_id
FROM my_table2
WHERE rownum <=1000000
ORDER BY record_group_id;
Using DISTINCT has no effect on order, only on uniqueness of values.
If you want to control order too:
SELECT DISTINCT record_group_id
FROM my_table2
WHERE rownum <= 1000000
ORDER BY record_group_id -- Added this line
Your assumption that data in the table is ordered is wrong.
There is no implicit ordering in a database table - it's just a bag of unsorted data.
If you need ordered data, you'll have to use ORDER BY - there's no way around it (neither DISTINCT nor GROUP BY nor ...), see TomKyte Blog on Order By
I'm working with sql server 2005.
I have a view which sorts its columns according to order date. I call:
SELECT TOP 1 [OrderDate]
FROM [ordersview]
to get the latest time. How do I get the earliest time?
SELECT TOP 1 OrderDate FROM ordersview ORDER BY OrderDate DESC
Also:
SELECT MIN(OrderDate) FROM ordersview
Use a descending ordering:
select top 1 OrderDate from ordersview order by OrderDate desc
I think,
this is little bit tricky question.
Every body will say for white is opposite black.
And for first is it last.
but when u are not specifying initial order
what is really the first.
I think it is internal/vendor specific thing.
So both answers are right ,but actually not answering really your question.
I'm not really mssql-guy but think that your select will return random
row (maybe depending on inserting sequence , or same internal db thing like rowId).
And what is opposite for random ?
One more thing is that, ordering is pretty demanding(resource/performance) function ,
for such thing u should have index on column.
And basically when u are doing select like that u should thing about real paging
not only one item .
But then the result will have different order then original one ( so ... )
I have a bunch of records that I want to paginate by reverse modified date. From what I can tell, using a simple query pulls the same sub-set of records and then sorts only those by date.
Something like this:
SELECT * FROM items WHERE status='1' ORDER BY modified_date DESC LIMIT start,count
Would an index help me? Or am I going to have to figure out some way to code this perhaps adding a column that somehow keeps track of modified_date in reverse order?
An index on (status, modified_date) might help. See indexes dos and donts.
This query looks good for me. It does the following:
Find records with status = 1
Order them by modified_date DESC
Return count records starting from start
So if you need to show first page, you should set start=0. For second page it'll be start=count, for third start=2*count and so on.
Or do you have performance problems with this?
Its a hack and I haven't tried it because I can't reproduce your problem and may not perform well but this may work for you
SELECT *
FROM (SELECT *
FROM items
WHERE status = '1'
ORDER BY modified_date desc ) t
LIMIT START, COUNT
You can add a column that holds a TIMESTAMP then set the auto-update property on it, so that it is properly updated. Finally, create an index for this column. Your query will look something like this:
SELECT *
FROM items
WHERE status='1'
ORDER BY 'timestamp' DESC
LIMIT start,count
Is there a way to keep the order when using SELECT WHERE IN()? For example, using the following query:
SELECT id FROM data_table WHERE id IN(56,55,54,1,7);
The results will come back using the default order by id. 1,7,54,55,56
When I want to keep the order used in the IN: 56,55,54,1,7
Is there a quick way to do this in MySQL or will I be forced to order it after in code?
Use FIND_IN_SET:
ORDER BY FIND_IN_SET(id, '56,55,54,1,7')
You can also use FIELD:
ORDER BY FIELD(id, '56,55,54,1,7')
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_field
http://ivanjovanovic.com/2008/04/01/preserving-ordering-with-where-in-clause-in-mysql/
You could do a UNION, that might return the order the same way.
BUT:
Why not just have your application reorder the results when it receives them, rather than forcing the DB to do it?
If the following SQL statements are executed in the order shown:
CREATE TABLE orders
(order_num INTEGER NOT NULL,
Buyer_name VARCHAR(35),
Amount NUMERIC(5,2));
CREATE UNIQUE INDEX idx_orderno ON orders(order_num);
whenever the ORDERS table is queried rows should be displayed in order of increasing ORDER_NUM values?
Relational databases don't work that way. An index is a means to select values doing less work (this is, not having to scan all rows to find a value), it's not a means to order the values in a result set.
In fact, most (all?) relational databases guarantee only one thing related to order, and that is that there is no guaranteed order if no order by clause is present in the query.
So, if you want ordered results you have to use the order by clause, like
select * from orders order by order_num
By default, order by column will order in ascending order. If you want it the other way around you can use order by column desc. order by column asc also exists.
To order by multiple columns you specify them separated by comma
select * from orders order by order_num asc, name desc
You need to specify that in the query, e.g.
SELECT * FROM orders ORDER BY order_num ASC;
There's no portable way to order by default for a certain table.
Unless you specify an ORDER BY clause in an SQL SELECT statement, there is no guarantee in which order the rows are returned. A given database may return them in the order of the first UNIQUE INDEX but this is not certain, and may even change over time for the same database.
To be sure of the order in which your rows are returned, always specify an ORDER BY clause in your SELECT statement. Like so:
SELECT * FROM orders ORDER BY order_num;
No, the rows will be displayed in an undefined order depending on the actual database software--usually the order they are stored in the database.
The unique index does have a sort order, but that is just to control how the index is stored and how efficiently it is used.
The correct way to do this is to add the desired sort to all your queries:
SELECT *
FROM [orders]
ORDER BY [order_num]
In general no, there is no reason for it.