Questions tagged [order-by]

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

Filter by
Sorted by
Tagged with
1
vote
2answers
45 views

Select random database records between subset of records having the same count(*) in a query

I have this simple query: SELECT `value`, count(*) as `noHits` FROM `topic` WHERE identifier IN ('" . implode("','", array_keys($processedIdentifier)) ."') GROUP BY `value` ...
0
votes
1answer
31 views

Order By First Condtition and If multiple matches, order by second condition

I was practicing SQL problems at hackerrank.com when I came across the following question: Query the Name of any student in STUDENTS who scored higher than 75. The Marks field in the table stores ...
0
votes
2answers
30 views

Order by is ignored if inside a derived table of a update (only in MYSQL 5.7)

I have a update to fix positions values inside a table. The update worked fine in MYSQL 5.5, but after upgrade to MYSQL 5.7 it doesnt work anymore. Now, the "order by" inside the derived table is ...
2
votes
1answer
32 views

PostgreSQL ORDER BY clause effect different number of rows to return in pivot table

I've worked on "Seven Databases in Seven Weeks" recently, and when implementing the the task with building a pivot table using crosstab() - the task was already described here: https://stackoverflow....
0
votes
0answers
19 views

Postresql using subquery select in order by clause

Is it possible to order by a selected columnname? SELECT * FROM tablex ORDER BY quote_ident(( select column_name from information_schema.columns where table_name = tablex AND column_name LIKE '...
0
votes
1answer
40 views

Can queries that users ORDER BY using date to sort data be non deterministic?

I have a table in my database where I store dates using the following standard: YYYY-MM-DD. As you can see, I'm not saving the hour. The first time I exported the same table to a csv file I got the ...
0
votes
1answer
60 views

Efficient partition pruning with ORDER BY on same column as PARTITION BY RANGE + LIMIT?

I've set up a table in MariaDB (10.4.5, currently RC) with InnoDB using partitioning by a column of which its value is incrementing-only and new data is always inserted at the end. For this case, ...
0
votes
1answer
22 views

Force index using the unused index columns having effect as order by for the result set?

if I have a index for (col1, col2, col3, col4), my query put col1 and col2 in the query where clause and force MySQL to use the above index. Would my query result be sorted by col3 and col4 ...
1
vote
1answer
24 views

How to order by then start at first non null value and select a limit for number of values

I have an environmental logger and I am trying to select every 5th row starting at where outsidetemp is not null (I want to include the null values after the first not null value). Is there a way to ...
1
vote
1answer
113 views

Optimize MySQL query and index for multiple column range query

I have a table like this: CREATE TABLE IF NOT EXISTS `jobs` ( `job_id` varchar(36) NOT NULL, `job_status` varchar(30) NOT NULL, `created_at` datetime NOT NULL, `lease_date` datetime, ...
4
votes
6answers
2k views

Only first column in ORDER BY clause is sorted [closed]

It seems like I've misunderstood the concept of 'Order by'. I have a table with this structure and data: CREATE TABLE TestTest (Value1 Int, Value2 Int); INSERT INTO TestTest VALUES (1, 10), (2, 9), ...
1
vote
1answer
80 views

first and last record in one query

i want to select first and last score from such data WITH t AS ( SELECT 1 user_id, '2019-05-15'::date AS created_at, 4 as score UNION ALL SELECT 1 user_id, '2019-05-13'::date AS created_at, 12 as ...
2
votes
2answers
77 views

SQL Preserve the Order in group by

I have records like below in my table. I want distinct records and when I do group by it loses the Order. I want to maintain the order. I have written below query to get the desired however its not ...
1
vote
0answers
22 views

PostgreSQL - SELECT query with ORDER BY and LIMIT 4 very slow, same query much faster with LIMIT >= 40

I've got following sample query from our Postgres DB: SELECT * FROM advertised_car a0_ LEFT JOIN car_check c1_ ON a0_.car_check_id = c1_.id WHERE c1_.status = 'ACCEPTED' ORDER BY a0_.id LIMIT 4; ...
0
votes
0answers
56 views

postgres: join tables, order by GREATEST

Having the following table structure table1 id: BIGSERIAL updated_at: TIMESTAMP WITHOUT TIME ZONE DEFAULT now() ... CREATE INDEX table1_updated_at ON table2(updated_at); table2 table1_id: ...
1
vote
1answer
79 views

Redundant fields in ORDER BY for efficient sorting?

Suppose I have a table SortTest with fields Data1, Data2, Sort1, and Sort2, Key1 and Key2 need to perform the following query: SELECT TOP 1 Data1, Data2 FROM SortTest WHERE Key1 = @key1 AND ...
3
votes
5answers
440 views

Order table by two columns

I would like to order this table but I can not find a way to make it work. Can you help me? I have this table: I need this: I have a table where documents are listed, the first field is the id of ...
0
votes
1answer
39 views

Mysql Performance Issue with Group By/Order By

I am using Mysql 5.7 I have table which having 7006500 rows. My query performing group by and fetching row which has maximum count with each group on column which is already indexed but still takes ...
2
votes
2answers
202 views

First order by importance then group by section

In this table scheme http://sqlfiddle.com/#!9/101a9c/9/0 id section rev importance 2 1 b 6 1 1 a 5 3 2 c 9 5 3 e 6 4 ...
2
votes
3answers
72 views

Identify proper index for group and order by date and hour (2 columns)

PostgreSQL 10.4 I have a table that has already an index on date column. Current query plan is doing a Bitmap Heap Scan using the existing date index. I would like to add a new index for this query, ...
0
votes
2answers
50 views

Poor performance on a 'leaderboard' query

Consider the following 2 tables: players: | rooms: id | id name | type room_id | embed_code_id points | My query needs to fetch the 100 players with the most points from a given ...
0
votes
1answer
167 views

postgresql - trouble to order a list obtained by string_agg

I obtained a list of numbers (and text) by a string_agg. For instance, that : "09,12,20,200,217,400,500,90,91,92,Exp3" This is the string_agg: string_agg(DISTINCT t_ligne.ligne_code::text, ','::...
3
votes
1answer
162 views

Adding an additional “order by” column gives me a much worse plan

in other words, how can I get rid of the sort operator on the picture below? the picture above shows the execution plan of the following 2 selects together: SELECT TOP 1 so.OrgType,...
2
votes
1answer
88 views

Conditional ORDER BY based on NULL values in the column

I have a table like this. table(student_name nvarchar(20) not NULL, grades int). When I write select * from table order by grades asc It shows this student_name | grades --------------------- ...
0
votes
2answers
35 views

How to get the best time from submited values?

I have a MySQL table, and i'm trying to figure how can i get the first result for each user. For example: Email Time DateSubmission usera@email.com | 0:14 | 28/2/2019 00:10 usera@...
1
vote
2answers
135 views

How to cast (a) a date value recorded as a VARCHAR to (b) a specific DATE format for (c) use in an ORDER BY clause

How would I cast a column value (a "non-MySQL" DATE string retained as a VARCHAR) to a "MySQL date" so it can be used for sorting? I have dates in the format of 06-02-2019 (6 feb) but MySQL itself ...
0
votes
1answer
309 views

Is possible to use ORDER BY with IF ELSE condition?

Here I have some data. I want to show the records which have fav=1 at fast, then I want to show the data where the date is greater than the current date in ascending order(date) and at last the ...
1
vote
1answer
37 views

Sort output of plpgsql function

I'm creating a function in Postgres 9.6 that compares two schemas with the same tables. I want to find tables which are empty in one schema but populated in the other. I'm avoiding the reltuples ...
0
votes
2answers
30 views

How to SELECT most common (viral) from a table and LIMIT results for pagination?

Sorry if it's a dubplicate but I can't find an answer to the question. Hello there so I have three tables users and articles and likes, a user can write an article, in the table articles there is ...
0
votes
0answers
35 views

Pagination using seek-method with nullable columns, sharing a composite index with ORDER BY

I have the following table: CREATE TABLE users( id text PRIMARY KEY, -- actually a uuid organization_id text NOT NULL, lname text NOT NULL, fname text NOT NULL -- other irrelevant fields ); ...
0
votes
1answer
55 views

Using WITH in sql query

I am trying to replace # with numbers, but the order by is being ignored, and I was told to move the subquery usingWITH or adding a limit to the order by, I tried the latter but it didn't work, and I ...
0
votes
3answers
48 views

What order does Oracle's EXIST condition compare the sub-query results?

I know EXIST works better than IN for larger sub-queries because it checks each sub-query record individually and stops once a comparison is found. Let's say I can order the sub-query in a way to ...
2
votes
0answers
70 views

Postgres / slow query / order by

I'm joining two tables, filter out results by second table and order results by first table's ID. The query is super-slow on Postgres Database. I see issue is in ORDER BY statement. But increasing ...
2
votes
1answer
53 views

How can I get the last items by date desc then by id desc?

I have a employee course table which holds the current record for each of my employees who have some courses that they have taken. Then I have a history that keeps a static version of the save data ...
21
votes
6answers
2k views

How to prove the lack of implicit order in a database?

Recently I was explaining to colleagues the importance of having a column by which to sort data in a database table if it is necessary to do so, for example for chronologically-ordered data. This ...
0
votes
1answer
376 views

Using MATCH, AGAINST multiple times in MySQL fulltext search

I'm using MySQL database for my e-commerce project. And here is my query for search: SELECT DISTINCT p.id, p.name, p.price, p.created_at, MATCH(p.name) AGAINST('Sony* xperia* FHD* ' IN BOOLEAN ...
4
votes
1answer
61 views

Postgres not smart enough to combine fields in WHERE and ORDER BY for index scan?

I have the following table in Postgres 9.6: Table "public.TagNotifications" Column | Type | Modifiers ...
3
votes
1answer
322 views

SELECT Parent-Child with SORT

I have a simple, one level parent child relation table, with following columns: ID_Asset| Parent_ID_Asset | ProductTitle I need output grouped by Parent followed by children, and also sorted by ...
-4
votes
1answer
141 views

Selecting data from a sub query

I am doing the exercises this is the link (https://www.wiseowl.co.uk/sql/exercises/standard/subqueries/4228/). Can anyone help me. Thanks in advance! Question Write a SELECT statement to return ...
1
vote
1answer
52 views

mysql : ordering a table in the order of the primary key

I have a table with a primary key consisting of two integer columns. I store ~200 millions lines in this table. My program needs to get the full table ordered by the columns of the primary key in the ...
5
votes
2answers
162 views

Is there a “soft” ORDER BY / GROUP BY?

SQL-Fiddle http://sqlfiddle.com/#!9/c82c87b/1 Table Definition First of all, this is my table: CREATE TABLE `stackoverflow` ( `id` VARBINARY( 36 ) NOT NULL COMMENT 'GUID generated by PHP', `time` ...
0
votes
3answers
60 views

How can we optimise this OR and ORDER BY query?

We have a table with the following structure: +----+----------+-------------+---------------------+-----------+---------+----------+ | id | Batch_id | Merchant_id | ExpiryDate | Allocated | ...
0
votes
1answer
28 views

Sort pivot result

I just want to ask how to sort the result of a PIVOT in SQL Server. When I use ORDER BY there is an error: "The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, ...
7
votes
4answers
1k views

Adding a ROW_NUMBER() with no column to ORDER BY?

So I'm working on a code golf puzzle and need to add an INT "number" column n to a result while maintaining the current order. Let's say my source data is: SELECT value FROM STRING_SPLIT('one,two,...
1
vote
1answer
32 views

Getting the first 3 children(items) for each owner in a list of primary keys

I have two tables Item an Owner, an a Foreign Key from Item to Owner, owner_id. I'm using PostgreSQL 10. For each owner I want to get the first 3 items if exist. select "items_item"."name" FROM "...
1
vote
3answers
53 views

How correct Postgres plan in case of a double JOIN, ORDER BY and a LIMIT?

I got a SQL request that takes more than 4s: SELECT "Content"."contentId" FROM "UserFeed" JOIN "FeedRole" ON "FeedRole"."feedId" = "UserFeed"."feedId" JOIN "Permission" ON "Permission"."...
1
vote
2answers
361 views

Syntax error in SQL Server while making Dynamic SQL

Scenario: I have a table with 100M+ rows of data so I have created an index with something as: CREATE NONCLUSTERED INDEX FIBaseVoterWithDeletedAt ON dbo.base_voter (name_voter,...
1
vote
0answers
30 views

Exclusive and Inclusive ranking queries in Postgres 9.6

I'm trying to build a filtering/ranking search that would let me order and optionally filter out people based on a 1-to-many relationship with job "focuses". The tables are shown at the bottom. A "...
1
vote
0answers
103 views

ORDER BY doesn't use an index on SQL Server if CASE WHEN is present

Firstly, I apologize - I couldn't create an example SQL Fiddle, because the site doesn't seem to be working right now. Now, onto the problem... I'm getting an inconsistent sort order on SQL Server ...
2
votes
1answer
26 views

column_name ordered same as describe table

I was under impression that default order of columns is internal mysql order but for some reason describe table and selecting column_name gives me compleatly different order. How can I set ORDER BY ...