MySQL ORDER BY [custom SET field value] - mysql

I hope there's a simple solution for this:
I have a table where each row has it's own status (SET type field). Statuses can be:
offline
available
busy
distance
I'd like to order as follows
available
busy
distance
offline
I thought a simple
ORDER BY `status` ASC
will do the trick (alphabetical order) but it gives me the following:
offline
available
busy
distance
How can is sort out this in the most simple way?
Thanks in advance,
fabrik

SELECT * FROM table ORDER BY FIELD(status,'offline','available','busy','distance')
see Mysql order by specific ID values

Thought I'd add another way to order by custom field values,
ORDER BY FIND_IN_SET(status, 'available,busy,distance,offline')
(If the given strings contain a quote simply escape it)

You could also do something like this, if reordering the SET values in impractical:
... ORDER BY CASE `status`
WHEN 'available' THEN 1
WHEN 'busy' THEN 2
WHEN 'distance' THEN 3
WHEN 'offline' THEN 4
END

Simpler than the solutions above:
ORDER BY CONCAT(status)

Nevermind.
The trick is saving SET values at the right order.

Related

How to default a value in subquery result?

Hopefully this is a simple one but I am most likely over complicating this for myself. Purpose of this code is to find previous operation name within a specified list of operations that is still open and returning it. If it's closed to say 'CLOSED'.
So far I'm using subquery to get the correct operation name, as expected I'm getting some null results which indicates to me that operation is closed. I wanted to wrap my subquery into a case statement to say something along the lines of CASE WHEN it's null then 'CLOSED' else operation_name end.
(select work_center_no
from shop_order_operation
where order_no = so.order_no
and release_no = so.release_no
and sequence_no = so.sequence_no
and work_center_no in ('CNC','EXPF','LS3M','LS4M','LS6M','PLAS','SAW','TBPL','EXSAW')
and oper_status_code in ('Released','In Process') order by operation_no fetch first 1 row only )
Above is my subquery. Hope this makes sense.
Thanks!
K
You can nicely default a value using IFNULL, just change your select clause to this:
select IFNULL(work_center_no, 'CLOSED')

Mysql forcibly order by exact value

Need help with mysql request.
I make a request and I want to order result by the field ID.
ID for exemple: 1,2,3,4,5,6,7,8,9
But I need that it would be ordered like this: 6,3,1,2,4,5,7,8,9
Is there any solution in mysql to forcibly put ID=6 in 1st place, ID=3 in 2nd...?
or I want the impossible)
Use CASE expression in ORDER BY clause.
Query
select * from `your_table_name`
order by case `id` when 6 then 1 when 3 then 2 else 3 end, `id`;
Find a demo here
Use:
ORDER BY FIELD(id, 6,3,1,2,4,5,7,8,9)
The FIELD function returns the position of the first value in the remaining list.

ORDER BY "ENUM field" in MYSQL

There is a field 'noticeBy' enum('email','mobile','all','auto','nothing') NOT NULL DEFAULT 'auto'. As it known ordering by ENUM field performs relative to its index. However, how it possible make order by its values?
As documented under Sorting:
ENUM values are sorted based on their index numbers, which depend on the order in which the enumeration members were listed in the column specification. For example, 'b' sorts before 'a' for ENUM('b', 'a'). The empty string sorts before nonempty strings, and NULL values sort before all other enumeration values.
To prevent unexpected results when using the ORDER BY clause on an ENUM column, use one of these techniques:
Specify the ENUM list in alphabetic order.
Make sure that the column is sorted lexically rather than by index number by coding ORDER BY CAST(col AS CHAR) or ORDER BY CONCAT(col).
Per the second bullet, you can therefore sort on the column after it has been cast to a string:
ORDER BY CAST(noticeBy AS CHAR)
This also works:
ORDER BY FIELD(noticeBy, 'all','auto','email','mobile','nothing')
(I don't believe that there is a setting to achieve this, you have to provide the sort-values.)
You can define your order however you wish:
ORDER BY CASE noticeBy
WHEN 'email' THEN 1
WHEN 'mobile' THEN 2
WHEN 'all' THEN 3
WHEN 'auto' THEN 4
ELSE 5
END
This will return the rows in the following order: email, mobile, all, auto, nothing.
In my case, I had to sort enum results by the "ENUM" field and also make sure the values are in DESCENDING order. My enum had the following values: 'Open','Closed'
So when I used ORDER BY CAST(status AS CHAR), the results were in this order:
Closed
Open
Open
But I wanted the Open status tickets to be shown first and then the Closed tickets. So I used the following:
ORDER BY CAST(status AS CHAR) DESC
This gave me the order that I was looking for i.e.
Open
Open
Closed
Summary:
Just using ORDER BY CAST on an enum did not seem to help. To sort the results in a specific order, mentioning ASC or DESC as well, did the trick.
The best option to me:
ORDER BY FIELD(status, 'publish','not-publish','expirated','deleted'), creation DESC
Status is the field in my BBDD, and values in '' are the values that has in enum options.
I hope that help u too! :)

How to order by multiple fields in MySQL?

I'm looking to order data in a specific way where I have explicitly laid out which fields I want to appear first. Basically, I'm looking to return a MySQL query by doing something that I would imagine might look like this:
ORDER BY
FIELD(brand,'toyota','honda','ford'),
FIELD(type, 'SUV', 'Sedan', 'Coupe'),
FIELD(transmission, 'manual', 'automatic', 'cvt')
Simply said I'm looking for a way to order things specifically based on multiple fields. I've tried it like this but it doesn't seem to be working. Can this even be done or after I specify the order of one field do I have to only order other things by either ASC or DESC?
Thanks for your help!
Perhaps something like this?
SELECT brand, type, transmission
FROM tablename
ORDER BY
case brand
when 'toyota' then 1
when 'honda' then 2
when 'ford' then 3
end ASC,
case type
when 'SUV' then 1
when 'Sedan' then 2
when 'Coupe' then 3
end ASC,
case transmission
when 'manual' then 1
when 'automatic' then 2
when 'cvt' then 3
end ASC
http://www.devx.com/tips/Tip/17288

Sorting varchar field numerically in MySQL

I have a field number of type varchar. Even though it is of type varchar, it stores integer values with optional leading zeros. A sort orders them lexicographically ("42" comes before "9"). How can I order by numeric values ("9" to come before "42")?
Currently I use the query:
SELECT * FROM table ORDER BY number ASC
Try this
SELECT * FROM table_name ORDER BY CAST(field_name as SIGNED INTEGER) ASC
There are a few ways to do this:
Store them as numeric values rather than strings. You've already discounted that as you want to keep strings like 00100 intact with the leading zeros.
Order by the strings cast as numeric. This will work but be aware that it's a performance killer for decent sized databases. Per-row functions don't really scale well.
Add a third column which is the numeric equivalent of the string and index on that. Then use an insert/update trigger to ensure it's set correctly whenever the string column changes.
Since the vast majority of databases are read far more often than written, this third option above amortises the cost of the calculation (done at insert/update) over all selects. Your selects will be blindingly fast since they use the numeric column to order (and no per-row functions).
Your inserts and updates will be slower but that's the price you pay and, to be honest, it's well worth paying.
The use of the trigger maintains the ACID properties of the table since the two columns are kept in step. And it's a well-known idiom that you can usually trade off space for time in most performance optimisations.
We've used this "trick" in many situations, such as storing lower-cased versions of surnames alongside the originals (instead of using something like tolower), lengths of identifying strings to find all users with 7-character ones (instead of using len) and so on.
Keep in mind that it's okay to revert from third normal form for performance provided you understand (and mitigate) the consequences.
Actually i've found something interesting:
SELECT * FROM mytable ORDER BY LPAD(LOWER(mycol), 10,0) DESC
This allows you to order the field like:
1
2
3
10
A
A1
B2
10A
111
SELECT * FROM table ORDER BY number + 0
Trick I just learned. Add '+0' to the varchar field order clause:
SELECT * FROM table ORDER BY number+0 ASC
I now see this answer above. I am wondering if this is typecasting the field and an integer. I have not compared performance. Working great.
For a table with values like Er353, ER 280, ER 30, ER36
default sort will give
ER280
ER30
ER353
ER36
SELECT fieldname, SUBSTRING(fieldname, 1, 2) AS bcd,
CONVERT(SUBSTRING(fieldname, 3, 9), UNSIGNED INTEGER) AS num
FROM table_name
ORDER BY bcd, num;
the results will be in this order
ER30
ER36
ER280
ER353
you can get order by according to your requirement my using following sql query
SELECT * FROM mytable ORDER BY ABS(mycol)
given a column username containing VARCHAR's like these:
username1
username10
username100
one could do:
SELECT username,
CONVERT(REPLACE(username, 'username', ''), UNSIGNED INTEGER) AS N
FROM users u
WHERE username LIKE 'username%'
ORDER BY N;
it is not cheap, but does the job.
SELECT * FROM table ORDER BY number ASC
Should display what you want it to display.. looks like you're sorting it by id or number is not defined as integer at the moment.
MySQL ORDER BY Sorting alphanumeric on correct order
example:
SELECT `alphanumericCol` FROM `tableName` ORDER BY
SUBSTR(`alphanumericCol` FROM 1 FOR 1),
LPAD(lower(`alphanumericCol`), 10,0) ASC
output:
0
1
2
11
21
100
101
102
104
S-104A
S-105
S-107
S-111
Another option to keep numerics at a top, then order by alpha.
IF(name + 0, name + 0, 9999999), name
Rough and ready: order by 1*field_name