ORDER BY FIELD , given field order comes at last - mysql

I am having table "business" as bellow
I want to fetch the record order by type in custom order. So I wrote the query like
SELECT * FROM business
ORDER BY FIELD (type, 'type3', 'type2', 'type10')
but what happen is other types comes up in order and the given order becomes at last. The given order should be at top and then other records. Above query returns the result as bellow.
How to bring the type3, type2 and type10 at top in order.

So that will be:
SELECT
*
FROM
business
ORDER BY
`type` IN ('type3', 'type2', 'type10'),
FIELD (`type`, 'type3', 'type2', 'type10')

Try below:
ORDER BY
CASE `type`
WHEN 'type3' THEN 1
WHEN 'type2' THEN 2
WHEN 'type10' THEN 3
ELSE 4
END

To see the selective data in top of the result set using field function you have to use either ASC or DESC on these set of values. Else the default result will be returned. Yours is an example of it.
You can try with
ORDER BY FIELD (type, 'type3', 'type2', 'type10') DESC
to see the results as
type10
type2
type3
How to bring the type3, type2 and type10 at top in order
Using ASC will result
type3
type2
type10
The input order of data to the function Field is the priority for display when used with ASC or DESC. Else the result would be default.
These fields I do not have given in query
They sure will be in resultset unless you specify a WHERE condition. FIELD function is not an alias to WHERE clause.
Refer to:
Ordering by specific field values with MySQL
MySQL: Sorting Rows

Related

MySQL UNION SELECT statement order by two different columns

I have a table with a column called "myorder". I want to only order the first 5 elements in ascending order by using the column "myorder" and then the rest of the elements ordererd by id in descending order. I've tried but I don't seem to get this 100%. I have created a sqlfiddle with this simple example. Can anybody help me?
The order in the sqlfiddle should be: Blue, Brown, Yellow, Red, Green, Orange, Gray, Black, White.
maybe try
SELECT * from tbl ORDER BY IF(myorder=0, 2147483647, myorder) ASC, id DESC
if by "first 5" you mean ones with nonzero myorder
Append this to the end of your sql statement:
ORDER BY FIELD(id, 3,4,5,1,2,9,8,7,6)
This will manually sort the results based on the id field in the specified order getting the colours in order.
Alternatively you could:
ORDER BY FIELD(NAME, BLUE,BROWN,YELLOW......)
Union does not preserves order, at least not in all databases.
To get this done you need to select a fake column and use order on the results (total)
Here is a solution:
(
SELECT Id, myorder, myorder as fake, name from tbl WHERE myorder!=0) UNION
(SELECT id, myorder, 2000 as fake,name from tbl WHERE myorder=0) ORDER BY fake asc, id desc
This Will work in any case, as long as you keep the fake number high enough.
Can we have NULL value instead of zero when myorder is not specified?
If so we can do this:
SELECT * from tbl ORDER BY -myorder DESC, id DESC
Fiddle:
http://sqlfiddle.com/#!2/ef9ee/4
Hint on forcing nulls to sort last: MySQL Orderby a number, Nulls last
Use a CASE statement and the following trick (for example):
SELECT *,
CASE myorder
WHEN 0 THEN id
ELSE 99999999 - myorder
END AS ord
FROM tbl
ORDER BY ord DESC
SQL Fiddle

SQL select first found value in 'in group'

Is is possible to select the first row matched in a list?
Table bar:
Column 'bar'
Values: value2, value3
SELECT * FROM `foo` WHERE `bar` IN ('value','value2','value3');
It select value2 and returns.
Thanks in advance
EDIT:
The values I am expecting are:
Foo
Foobar
Foobarsome
Foobarsomething
I determine this based on the length of the strings but I also need a default value if nothing is found. Lets say 'nothing' but nothing is bigger then foobar and could be a valid value.
You can query:
SELECT * FROM `foo` WHERE `bar` IN ('value','value2','value3') LIMIT 1;
But without additional ordering it's not deterministic, which first row will be your result.
You can use a CASE statement in the ORDER BY clause to specify the order based on column values. Then use can use LIMIT to select just one row in the result.
SELECT * FROM foo
WHERE bar IN ('value','value1','value2')
ORDER BY CASE bar WHEN 'value' THEN 1 WHEN 'value1' THEN 2 WHEN 'value2' THEN 3 ELSE 100 END
LIMIT 1;
I tested this example on SQL Fiddle.
UPDATE: The original poster edited the question and added that he wants to sort on string length and have a default value of 'nothing' returned if there are no results.
SELECT * FROM foo
WHERE bar IN ('value','value1','value2')
ORDER by CASE bar WHEN 'value' THEN 1 WHEN 'value1' THEN 2 WHEN 'value2' THEN 3 ELSE 100 END
LIMIT 1;
SELECT bar FROM
(
SELECT bar, 0 as SortOrder FROM foo
WHERE bar IN ('value','value1','value2')
UNION
SELECT 'nothing' as bar, 999 as SortOrder
) as x
ORDER BY SortOrder, LENGTH(bar)
LIMIT 1;
You can see the update query run in SQL Fiddler.
This solution works by using a UNION to combine the default value of 'nothing' to the result and also includes a "SortOrder" column. The UNION'ed queries are Order By the SortOrder column so that the default value is sorted to the bottom of the results, then the results are sorted by the length of bar. Finally there is LIMIT 1 clause so the default value 'nothing' appear in the final result if it is the only record otherwise the shortest string that matches in the 'in group' set is returned.
Mysql should work with..
SELECT *
FROM foo WHERE bar IN ('value','value2','value3')
LIMIT 0,1;
Could you please write your expected output? It will make it easier...

How to order your result in a specific way in SQL Server

I have a simple query, but I would like to see the results in a specific way. I would like to see 'N/A' at the top of the result, without having to result to "Case When Then"
Select *
From Ordertype
Results:
Car21
Car34
Bus42
N/A
Thanks,
There are no 'overrides' for ORDER BY, if you want the specific order you're asking for, you'll have to use the CASE:
SELECT type
FROM OrderType
ORDER BY
CASE
WHEN type = 'N/A' THEN 1
ELSE 2
END
,type
If you want an arbitrary order that is not tied directly to the structured of a column (alphabetical/numerical) but rather to it's importance which only you know in your head it can be useful to add a Rank column to your table.
Column1 Rank
Car21
Car34 2
Bus42 1
N/A 99
then you can do
select Column1
from Table
order by rank desc, column1
This will put highly ranked items first then low ranked items, then when rows don't have a rank it will sort them alphabetically by column1
You can try this:
SELECT * FROM ordertype ORDER BY ID DESC
to see the newest ones 1st

mysql ordering exception

I have a MySQL database and a have a funny question.
I need to order the results of a query by a field which has entries of 1,2,3 or 4, ordered descending but with 4 at the end.
So I wish to have the results in the following order
3's
2's
1's
4's
Is this possible at all?
I know I can do order the result array in php but unfortunately I need to do this in an sql statement.
If the field is an int,
ORDER BY (fieldname = 4) DESC, fieldname DESC
should do the trick.
Here is another cool way
ORDER BY MOD(fieldname,4) DESC,fieldname
If the result is a CHAR(1) then
ORDER BY LOCATE(fieldname,'3214'),fieldname
add this to the order
ORDER BY
CASE field_name WHEN 4 THEN 1
ELSE 2
END
this will return the result of the query order using the value of the field

Method to sort MYSQL results by an arbitriary letter (ie, show all rows starting with F first)

I have a column of states, and, depending on the query, I want to order by results by a particular state, then by id (Asc or Desc, depending). For instance, I might want to show all rows with state "HI", sorted by ID desc, and then all the other rows, sorted by id desc.
I was hoping I could do this in one query, rather than getting all my favored state results, and then getting the rest. Can I?
How about:
SELECT id, state
FROM sometable
ORDER BY IF(state = 'HI', 0, 1) ASC, id DESC;
This will sort 'HI' rows first. If you want them last, change the ASC to DESC.
You have two options:
do a union
write a function and use it to order rows by
In the first case, you could do something like
select 1 as res_order, ...
...
where state like 'hi%'
union
select 2 as res_order, ...
...
where state not like 'hi%'
order by res_order asc, id desc
In the second case, you could do something like
select my_function(state, "hi") as row_order, ...
...
order by row_order
where the function returns lower values for matching states.
The code is off the top of my head: it might need some tweaking to make it runnable.