Questions tagged [order-by]

A clause used in SQL SELECT statements to sort query results.

Filter by
Sorted by
Tagged with
0
votes
2answers
30 views

Is it possible to sort by the sequence of input IDs?

I want to find user's favorite music list. First step, I query all id from user's favorite table. In the next step I query the music list by id from songs table. But now I want to sort rows by the ...
52
votes
2answers
149k views

How does ORDER BY FIELD() in MySQL work internally

I understand how ORDER BY clause works and how the FIELD() function works. What i want to understand is how the both of them work together to sort. How are the rows retrieved and how is the sort ...
5
votes
1answer
158 views

Index Definition Order and ORDER BY Clause

So i was doing my morning blog reading and stumbled upon this fun exercise: https://www.erikdarlingdata.com/sql-server/lets-design-an-index-together-part-3/ Here is the query in question from the ...
2
votes
3answers
3k views

MySQL InnoDB Sorting Issue

I was surprised to see MySQL's InnoDB showing an interesting behavior, which I cannot fully explain. According to the official MySQL InnoDB Documentation: "All indexes other than the clustered ...
3
votes
1answer
82 views

case sensivity incongruity

I'm trying to learn and understand collations and how postgresql compare and order strings but I'm finding an incongruity and I don't know what I'm missing. The query: SELECT datname, datcollate FROM ...
1
vote
1answer
9k views

GROUP_CONCAT with ORDER BY , but results are not ordered

The following query works fine SELECT *, (SELECT GROUP_CONCAT(url SEPARATOR '$$' ) FROM project_photos WHERE project_id = projects.id ORDER BY priority) AS images FROM projects WHERE catID = 2 LIMIT ...
1
vote
1answer
1k views

MYSQL - How to optimize VIEW performance?

Total profiles - 100000 Each profile is connected to one or more platform Each profile have 50 Tags Each profile have 4 themes I have a user view (total users around 100000) where I am joining all ...
3
votes
2answers
121 views

Optmizing ORDER BY

I'm new to MySQL and have written the following query (see below). PROBLEM: The query returns accurate data but takes about 40 seconds to execute. However, When I remove the ORDER BY part, it takes ...
1
vote
1answer
167 views

How to sort query filename output like Windows explorer?

i would like to order my query output the way Windows Explorer does. First special characters like _, then the numbers, and the letters last. _ttt.bmp 0.gif bbb.png
0
votes
2answers
36 views

Sort index doesn't work for MySQL

I have a table with more than a million records. I get the data by using LIMIT, but also ORDER BY. The latter causes a huge performance problem. My query ends with this: ... ORDER BY `record`.`...
0
votes
1answer
25 views

Fill remaining LIMIT rows selection if conditions met are less than LIMIT number

I have a MySQL database with data in it. They all have locations (London, Liverpool, etc), I want a query to select 10 random rows with a location (for example London), and if there aren't enough to ...
20
votes
3answers
12k views

How to ORDER BY typical software release versions like X.Y.Z?

Given a "SoftwareReleases" table: | id | version | | 1 | 0.9 | | 2 | 1.0 | | 3 | 0.9.1 | | 4 | 1.1 | | 5 | 0.9.9 | | 6 | 0.9.10 | How do I produce this output? | id | version ...
4
votes
2answers
15k views

MySql: Delete all rows greater than n entries ordered by datetime

Can someone help me with a MySql query to delete all rows greater than n entries ordered by date? I.e. say I have 1200 rows of data with a timestamp column. I need to order it by date and preserve ...
2
votes
3answers
65 views

Ordering streets by their names and polysyllabic numbers in SQL query

In Oracle DB there is a table with some data: LAG HNR STREET 00020 44 Aachener Straße 00020 44/2 Aachener Straße 00020 44/1 Aachener Straße 00020 46 Aachener Straße 00020 46/6 Aachener Straße ...
4
votes
1answer
77 views

Ordering rows by repeating pattern

Given a table in Postgres like CREATE TABLE t1 ( type text NOT NULL, value int NOT NULL ) where type could be A, B or C and given an arbitrary, repeating pattern like A B B C B B how can I query ...
6
votes
1answer
6k views

Update one table from another table while sorting that table based on one column

This is the problem I'm trying to figure out in MySQL. We have an old table contains some forms submitted by our users. Somehow, the previous decision was each time a user comes to this survey, a new ...
95
votes
3answers
131k views

What is the default order of records for a SELECT statement in MySQL?

Suppose you have the following table and data: create table t ( k int, v int, index k(k) ) engine=memory; insert into t (k, v) values (10, 1), (10, 2), (10, 3); When ...
0
votes
1answer
47 views

How to use ORDER BY and LIMIT inside JSON_AGG

I have a query which returns a desired output. SELECT shop, JSON_AGG(item_history.* ORDER BY created_date DESC) as data FROM item_history GROUP BY shop; Results: [ { "shop&...
0
votes
1answer
31 views

Rank calculation using variables working only sometimes

I have the following code in MariaDB that was working perfectly well yesterday. It calculates a rank and orders by the data by another column: SET @c = (SELECT COUNT(*) FROM myTable); SET @rownum = 0; ...
1
vote
3answers
48 views

Change column values but keep order in MySQL

Lets consider I have a table: CREATE TABLE student ( id int, name varchar(128) ); INSERT INTO student (id,name) VALUES (1,'John'), (2,'Bob'), (3,'Alice'), (4,'Don'), (5,'Eve'); I need the 'names' ...
2
votes
1answer
10k views

Query with order by, group by and limit

I have two tables: chains and documents. CREATE TABLE `chains` ( `chain_id` int(10) unsigned NOT NULL AUTO_INCREMENT, ... PRIMARY KEY (`chain_id`), ... ) ENGINE=InnoDB CREATE TABLE `docs` ( `...
5
votes
3answers
3k views

Does ORDER BY on a clustered key affect performance?

Say I have a table clustered on PrimaryKey, and in all cases I want my results to be ordered by PrimaryKey, so I additionally always ORDER BY PrimaryKey in all queries. Does this ORDER BY affect ...
1
vote
1answer
47 views

Best index for case insensitive match on one field and ordering by another field

I want to run a query like this: SELECT * FROM "core_user" WHERE UPPER("core_user"."email"::text) = UPPER('emailsearch@example.com') ORDER BY "core_user"."...
1
vote
1answer
36 views

Order a nested table with path index according to list_order in SQLite

I have a SQL table with this nested structure: CREATE TABLE items (`id` INTEGER, `item_name` VARCHAR(6), `parent_id` INTEGER, `list_order` INTEGER); My SQLite version does not support window function,...
6
votes
2answers
38k views

CASE ORDER BY with multiple columns, and different sort options

I am attempting to use a T-SQL CASE ORDER BY in a stored procedure where I am passed @OrderBy parameter as a TINYINT. @Orderby = 1 Then Date column should be ASC @Orderby = 2 Then Date column ...
0
votes
1answer
17 views

Why is below 2 query generating different execution plan in MYSQL?

Only difference in the below query is the order by column. The resultset of both query is same. However, the 2nd query execution plan shows 'Using temporary; Using filesort' for ordering where as for ...
0
votes
2answers
68 views

Strange behavior of TOP 1 clause sql server

I have a SQL Server database and restored it on another server on a different machine. Now I run following same query on both DBs which produces same below result set. select person_id, visit_id, ...
0
votes
1answer
23 views

Order by starting from "the middle" in a windowing function

What I have is a table like this, where I need to do a running total of the values column for the upcoming months. The issue is that I would like to start from month 4 (shown in column 3) and go all ...
0
votes
1answer
24 views

MySql ORDER BY slow with join, fast as 2 queries

Why is the following query slow but fast when I provide the values inline? select u.* from user u join user_group g on u.group_id = g.id where g.account_id = 1 order by u.id limit 10; -- takes ~30ms ...
0
votes
1answer
45 views

Postgresql: sort by value position in array column, then by secondary order

I'm not quite sure what the best way to phrase this is... So in my DB there is pillars text array which is basically an enum where providers ordered what values meant the most to their business, from ...
-1
votes
2answers
43 views

A quick way to ORDER all IDs randomly in MySQL [closed]

I need to assign random IDs to a table. Thus, I create a mapping table as CREATE TABLE t2 ( ID int(11) unsigned NOT NULL AUTO_INCREMENT, SourceID int(11) unsigned NOT NULL, UNIQUE INDEX(SourceID), ...
12
votes
2answers
19k views

MySQL not using indexes when joining against another table

I have two tables, the first table contains all articles / blog posts within a CMS. Some of these articles may also appear in a magazine, in which case they have a foreign key relationship with ...
4
votes
3answers
2k views

Case Insensitive ORDER BY clause using COLLATE

I have spent a long time looking for this, and I am getting mixed messages. In other DBMSs (tested in SQLite, Oracle, MariaDB, MSSQL) I can override the default sort order using the COLLATE clause: ...
4
votes
3answers
3k views

Extremely slow query on indexed column in Postgres

I'm getting a extremely slow query on an indexed column. Given the query SELECT * FROM orders WHERE shop_id = 3828 ORDER BY updated_at desc LIMIT 1 explain analyze returned: QUERY PLAN ----...
1
vote
0answers
44 views

Postgres Ignores Index When Ordering By Column From Joined Table

I am trying to figure out why Postgres is not using index when querying with ORDER BY clause with a SELECT query and 2 simple LEFT JOIN statements. I will explain my relevant database structure first: ...
3
votes
2answers
144 views

Order by column which casted to varchar

situation is that, i want to prepare datasets for front end chart. the raw data from table contains LAC | FLUID_MERIT|FA_BDATE |GRP |FARM_FK ------------------------------------------ 0 |234.56 ...
1
vote
1answer
794 views

MariaDB / mYSQL Order BY PrimaryKey DESC vs DESC set by Default

What do you guys think about: After each query, I put "Order BY PrimaryKey DESC" VS I set "PrimaryKey Sort by DESC Default" and each query I don't need to put Order By there. Which one will be ...
4
votes
2answers
12k views

Preordering the table by a specified column

I have a table and I am always getting the data by ordering a column. In my case, I order by datenum. However, the selection is so slow because of the ordering. Is it possible to order the table ...
4
votes
2answers
2k views

Why is this query with WHERE, ORDER BY and LIMIT so slow?

Given this table posts_lists: Table "public.posts_lists" Column | Type | Collation | Nullable | Default ------------+------------------------+-----------+-...
0
votes
1answer
69 views

MSSQL - Insert Into adding data into the middle of the table? [duplicate]

A bit of a random one here... I've got a basic table that I'm using for temporary data inserts - and for that reason, I don't need or want a unique ID - however, I'm seeing odd behaviour! (or it feels ...
5
votes
1answer
328 views

Are the results of the STRING_SPLIT() function returned in a deterministic order?

I need to split a comma delimited string, manipulate it, and then concatenate it back into a single string retaining the original order of the data (if possible). For example, take a column definition ...
0
votes
2answers
153 views

The opposite of ordering by a column in SQL

If you have a table and you'd like to sort by a column you can use order by foo to order the results by foo. Is it possible to do the opposite, such that rows which have the same value for foo would ...
0
votes
2answers
2k views

Clever way to order a json item by key in postgresql (two examples)

I need to sort a json item in a record, so here are two examples: First case create table jsontable ( jsonitem json ); Next I insert a json item: insert into jsontable(jsonitem) values ('{ "...
0
votes
1answer
35 views

Creating a table with Rank ordering in Oracle [closed]

I am trying to create a table in Oracle as follow: create table hops.t_distribution AS (select UID, CONTACT_EMAIL, PRODUCT_ID, rank() over(Partition by UID order by to_number(PRODUCT_ID)) as ...
8
votes
3answers
5k views

How do I order by NULLS LAST if my database doesn't support it?

Select FullName, Login FROM [User] ORDER BY FullName desc, login asc Results FullName Login ----------------------------- ------------------------------ M...... ...
8
votes
2answers
228 views

Sqlite: Finding the next or previous element in a table consisting of integer tuples

I have a sqlite table called tuples defined like create table tuples ( a INTEGER not null, b INTEGER not null, c INTEGER not null, d INTEGER not null, primary key (a, b, c, d) ) ...
1
vote
1answer
27 views

Optimizing multi-criteria sort query

I want to efficiently sort a table in PostgreSQL based off of two criteria. Here is my table structure: CREATE TABLE shapes ( shape_id character varying, shape_pt_lat double precision, ...
0
votes
2answers
84 views

Get unique ids based on order by another column using group by with row_number

Here is a link to the SQLfiddle. For pagination purpose, I am first executing a query to execute if's and order by's and return a list of ids, using which I query for all the data with contained lists ...
0
votes
3answers
140 views

Sort varchar by its numeric fields

I'm sure this has been asked before, but since the question can be formulated in many different ways it's difficult to find the proper answer. I have an orders table with a varchar field for the order ...
1
vote
1answer
180 views

Select Query slow for Non-clustered index

I am using SQL Server 2008 R2. Select query is slow when non cluster index is used in the table compared to table without index. Query Used: select * from table order by customer_name It is too ...

1
2 3 4 5
8