order by in a non-numerical order - sql

I'm trying to order the results of a query in a non alpha-numerical order. For example, if the possible values of a column are '1', '2' and '3'. ORDER BY asc will display rows with '1' first, then rows with '2' and finally rows with '3'. ORDER BY desc will do the oppsite.
What if I want a different order, like 3, 1, 2 or 1, 3, 2 ? Is that possible ?
Thank you

You want to use a case statement in your order by clause.
So for your 3, 1, 2 example, it would look something like this:
ORDER BY
CASE <yourField>
WHEN 3 THEN 1
WHEN 1 THEN 2
WHEN 2 THEN 3
ELSE 4 END ASC

It should be possible, however, you do not specify what order you are looking for. If you are just looking for a random order you can use ORDER BY NEWID().

you can add your own column named as example my_order
and then order by my_order

You don't really have an ordering as much as a certain sequence. How would you even specify this? If we think of the collection of rows as an indexed array, then you could make a auxiliary index table:
position refers_to
1 3
2 1
3 2
. .
. .
Then you can join the tables ON(index_table.refers_to = my_table.that_column) ORDER BY index_table.position.

Related

I want to find the longest varchar in a specific column of a SQL Server table

Here's an example:
ID = INT IDENTITY
DESC = VARCHAR(5000)
ID | Desc
---|-----
1 | a
2 | aaa
3 | aa
The SQL query here should return 3 and the word itself i.e., aaa? Since the longest value is aaa with 3 characters?
The output should be:
aaa 3
You can use order by and limit the results to one row:
select description, len(description)
from t
order by len(description) desc
offset 0 row fetch first 1 row only;
Or use:
select top (1) description, len(description)
from t
order by len(description) desc;
With OFFSET & FETCH:
OFFSET is specifying how many rows from the top of the result set you will ignore ...
And then the FETCH is used to limit the result to the number of rows you specify.
The combination of this two will return the desired result because the result set is ordered by len(descr).
select descr, len(descr)
from test
order by len(descr) desc
OFFSET 0 ROWS
fetch first 1 rows only;
With TOP:
TOP will limit the reultset to the number of rows you specify. In this example 1. Because it is ordered by the lenght of the column desc then the first row will be the one you are looking for.
select top 1 descr, len(descr)
from test
order by len(descr) desc
HERE IS A DEMO for both examples
Note for the end:
Use aliases (I will demonstrate on one of this two examples)
select descr as Description, len(descr) "Description length"
from test
order by len(descr) desc
OFFSET 0 ROWS
fetch first 1 rows only;
You can put them between double quotes or not, use keyword as or not, it is up to you but the result looks better with them.
Both ROW and ROWS keyword is ok for OFFSET and FETCH clause. So what ever you want to use you can...
You can try TOP as shown below. Here is the official documentation of TOP (Transact-SQL).
Select
top 1 Id, description, len(description) as MaxLength
from YourTable order by len(description) desc
Live Demo
This will do what you want on Oracle (one of the tags on the question):
SELECT descript,length(descript)
FROM t WHERE length(descript)=( SELECT max(length(descript)) FROM t);
Keep in mind that if there are two (or more) records with that length, you will get them all. You could add a AND rownum < 2 clause but that will give you which ever entry the database chooses to give.
If you want the first record of those with the longest field, a subquery will be required:
SELECT descript,length(descript) from (
select descript from t order by length(descript) desc, descript asc)
WHERE rownum < 2;
There is also the offset 0 row fetch... version listed earlier:
SQL> select descript, length(descript)
2 from t
3 order by length(descript) desc
4 offset 0 row fetch first 1 row only;
DESCRIPT LENGTH(DESCRIPT)
-------------------- ----------------
defg 4
Mind you, this only works on my "12.2.0.1.0" Oracle. If I try the same thing on my "11.2.0.4.0" Oracle, I get "ORA-00933: SQL command not properly ended" with that last line. Apparently this is newer, maybe that is why I have never seen it before.

ORDER BY followed by a number

I took this query from this question.
SELECT *
FROM A
WHERE x='abc'
OR y=0
order by case when x='abc' then 0 else 1 end;
This query supposedly will prioritize x='abc' cases. But I'm really confused why is this happening? Isn't ORDER BY followed by a column name or column number? Also, I researched on the syntax of ORDER BY and they don't tell anything about this. I also tried something like this but it says: "1st ORDER BY term out of range - should be between 1 and 1":
SELECT A
FROM B
ORDER BY 2
So, can anyone explain this query or at least point to a good documentation? Thank you very much.
Well, when an ORDER BY clause is followed by a number, this number will be referenced to the column in the (number) position.
The ORDER BY followed by a CASE EXPRESSION is called conditional ordering, each column will get the value 0 when x is equal to abc and when its not it will get the value 1. After that, the ordering is in ASC , so 0 will always be prioitized before 1.
It will be something like this:
x | y | .... | Here is the new value that will order the query
abc 1 0
ayr 0 1
acz 1 1
.........
So, basically it's like generating a new value.

sqlite query unsorted result

I have list of Ids 31165,31160,31321,31322,31199,31136 which is dynamic.
When I run query
select id,name from master_movievod where id in(31165,31160,31321,31322,31199,31136);
I get following result
31136|Independence Day
31160|Planet of the Apes
31165|Mrs. Doubtfire
31199|Moulin Rouge
31321|Adult Movie 2
31322|Adult Movie 3
This is sorted list in ascending order.
I want the list in the same order which I give as input like
31165|Mrs. Doubtfire
31160|Planet of the Apes
31321|Adult Movie 2
31322|Adult Movie 3
31199|Moulin Rouge
31136|Independece Day
Without an order by clause, there's no guarantee on the order a database returns the results to you. SQLite, unfortunately, doesn't have something like MySQL's field for custom sorting, but you can jimmy-rig something with a case expression:
SELECT id, name
FROM master_movievod
WHERE id IN (31165, 31160, 31321, 31322, 31199, 31136)
ORDER BY CASE ID WHEN 31165 THEN 0
WHEN 31160 THEN 1
WHEN 31321 THEN 2
WHEN 31322 THEN 3
WHEN 31199 THEN 4
WHEN 31136 THEN 5
END ASC
Unfortunately, SQLite does not have an option like MySQL's FIELD for doing a custom ordering. You are left with two options. The first is that you could create a custom table containing the ordering you want and use that to sort. This option isn't very attractive. The second (and easier) option is to use ORDER BY CASE to achieve the order you want:
SELECT id, name FROM master_movievod
WHERE id IN (31165,31160,31321,31322,31199,31136)
ORDER BY
CASE id
WHEN 31165 THEN 0
WHEN 31160 THEN 1
WHEN 31321 THEN 2
WHEN 31322 THEN 3
WHEN 31199 THEN 4
WHEN 31136 THEN 5
END ASC

How to sort the string 'MH/122020/[xx]x' in an Access query?

I am trying to sort the numbers,
MH/122020/101
MH/122020/2
MH/122020/145
MH/122020/12
How can I sort these in an Access query?
I tried format(mid(first(P.PFAccNo),11),"0") but it didn't work.
You need to use expressions in your ORDER BY clause. For test data
ID PFAccNo
-- -------------
1 MH/122020/101
2 MH/122020/2
3 MH/122020/145
4 MH/122020/12
5 MH/122021/1
the query
SELECT PFAccNo, ID
FROM P
ORDER BY
Left(PFAccNo,9),
Val(Mid(PFAccNo,11))
returns
PFAccNo ID
------------- --
MH/122020/2 2
MH/122020/12 4
MH/122020/101 1
MH/122020/145 3
MH/122021/1 5
you have to convert your substring beginning with pos 11 to a number, and the number can be sorted.
How about this ?
SELECT
tmpTbl.yourFieldName
FROM
tmpTbl
ORDER BY
CLng(Mid([tmpTbl].[yourFieldname],InStrRev([tmpTbl].[yourFieldname],"/")+1));
Given the following data in my test_table, column DATETIMESTAMP:
XXX123
YYY000
XXX-1234
my Statement:
SELECT CInt(Mid(datetimestamp,4)) AS Ausdr1
FROM test_data
ORDER BY 1;
sorts my data. please hange 4 to 11 and it will work for you

How do I preserve the order of a SQL query using the IN command

SELECT * FROM tblItems
WHERE itemId IN (9,1,4)
Returns in the order that SQL finds them in (which happens to be 1, 4, 9) however, I want them returned in the order that I specified in the array.
I know I could reorder them after in my native language (obj c), but is there a neat way to do this in SQL?
Somthing like this would be great:
ORDER BY itemId (9,1,4) -- <-- this dosn't work :)
Probably the best way to do this is create a table of item IDs, which also includes a rank order. Then you can join and sort by the rank order.
Create a table like this:
itemID rank
9 1
1 2
4 3
Then your query would look like this:
select tblItems.* from tblItems
inner join items_to_get on
items_to_get.itemID = tblItems.itemID
order by rank
Use a CASE expression to map the ID values to an increasing sequence:
... ORDER BY CASE itemId
WHEN 9 THEN 1
WHEN 1 THEN 2
ELSE 3
END
I had the same task once in a mysql environment.
I ended up using
ORDER BY FIND_IN_SET(itemID, '9,1,4')
this is working for me since then. I hope it also works for sqlite
You can add a case construct to your select clause.
select case when itemid = 9 then 1
when itemid = 1 then 2 else 3 end sortfield
etc
order by sortfield
You could create a procedure to order the data in SQL, but that would be much more complicated than its native language counterpart.
There's no "neat way" to resort the data like that in SQL -- the WHERE clause of a SELECT simply says "if these criteria are matched, include the row"; it's not (and it cannot be) an ordering criterion.