How to sort rows by ON, OFF, SOLD - php

I have followings 3 values that could be in a row in database - ON, OFF, SOLD (column sort_it). When I set the sort clausule on ORDER BY sort_it ASC, so I will get the items with a value in the sort_in column OF, then ON and SOLD.
But I need the sequence ON, OFF, SOLD.
Exist any way to do it somehow? I mean... edit a way saving data into database will be demanding, so I would do this in the last moment.

Yes you can use custom data sortings like this:
SELECT * FROM table ORDER BY FIELD(`sort_it`,'ON','OFF','SOLD'),`sort_it`

You can use a CASE statement to generate your custom ordering sequence from the underlying values, something like this:
ORDER BY
CASE sort_it
WHEN 'ON' then 1
WHEN 'OFF' then 2
WHEN 'SOLD' then 3
END
Sample Demo: http://sqlize.com/MGz6lLb0Qk

Using Strings is generally a bad idea. it would be better to use a numeric type. Then you can say ON=1, OFF=2 and SOLD=3 and then sort.

SELECT t.*, IF(sort_it='ON',1,IF(sort_it='OFF',2,3)) as new_sort FROM Table AS t ORDER by new_sort ASC
Another solution from comments on MySql manual:
http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html
select * from tablename order by priority='High' DESC, priority='Medium' DESC, priority='Low" DESC;

Related

How to order the ORDER BY using the IN() mysql? [duplicate]

I am wondering if there is away (possibly a better way) to order by the order of the values in an IN() clause.
The problem is that I have 2 queries, one that gets all of the IDs and the second that retrieves all the information. The first creates the order of the IDs which I want the second to order by. The IDs are put in an IN() clause in the correct order.
So it'd be something like (extremely simplified):
SELECT id FROM table1 WHERE ... ORDER BY display_order, name
SELECT name, description, ... WHERE id IN ([id's from first])
The issue is that the second query does not return the results in the same order that the IDs are put into the IN() clause.
One solution I have found is to put all of the IDs into a temp table with an auto incrementing field which is then joined into the second query.
Is there a better option?
Note: As the first query is run "by the user" and the second is run in a background process, there is no way to combine the 2 into 1 query using sub queries.
I am using MySQL, but I'm thinking it might be useful to have it noted what options there are for other DBs as well.
Use MySQL's FIELD() function:
SELECT name, description, ...
FROM ...
WHERE id IN([ids, any order])
ORDER BY FIELD(id, [ids in order])
FIELD() will return the index of the first parameter that is equal to the first parameter (other than the first parameter itself).
FIELD('a', 'a', 'b', 'c')
will return 1
FIELD('a', 'c', 'b', 'a')
will return 3
This will do exactly what you want if you paste the ids into the IN() clause and the FIELD() function in the same order.
See following how to get sorted data.
SELECT ...
FROM ...
WHERE zip IN (91709,92886,92807,...,91356)
AND user.status=1
ORDER
BY provider.package_id DESC
, FIELD(zip,91709,92886,92807,...,91356)
LIMIT 10
Two solutions that spring to mind:
order by case id when 123 then 1 when 456 then 2 else null end asc
order by instr(','||id||',',',123,456,') asc
(instr() is from Oracle; maybe you have locate() or charindex() or something like that)
If you want to do arbitrary sorting on a query using values inputted by the query in MS SQL Server 2008+, it can be done by creating a table on the fly and doing a join like so (using nomenclature from OP).
SELECT table1.name, table1.description ...
FROM (VALUES (id1,1), (id2,2), (id3,3) ...) AS orderTbl(orderKey, orderIdx)
LEFT JOIN table1 ON orderTbl.orderKey=table1.id
ORDER BY orderTbl.orderIdx
If you replace the VALUES statement with something else that does the same thing, but in ANSI SQL, then this should work on any SQL database.
Note:
The second column in the created table (orderTbl.orderIdx) is necessary when querying record sets larger than 100 or so. I originally didn't have an orderIdx column, but found that with result sets larger than 100 I had to explicitly sort by that column; in SQL Server Express 2014 anyways.
SELECT ORDER_NO, DELIVERY_ADDRESS
from IFSAPP.PURCHASE_ORDER_TAB
where ORDER_NO in ('52000077','52000079','52000167','52000297','52000204','52000409','52000126')
ORDER BY instr('52000077,52000079,52000167,52000297,52000204,52000409,52000126',ORDER_NO)
worked really great
Ans to get sorted data.
SELECT ...
FROM ...
ORDER BY FIELD(user_id,5,3,2,...,50) LIMIT 10
The IN clause describes a set of values, and sets do not have order.
Your solution with a join and then ordering on the display_order column is the most nearly correct solution; anything else is probably a DBMS-specific hack (or is doing some stuff with the OLAP functions in standard SQL). Certainly, the join is the most nearly portable solution (though generating the data with the display_order values may be problematic). Note that you may need to select the ordering columns; that used to be a requirement in standard SQL, though I believe it was relaxed as a rule a while ago (maybe as long ago as SQL-92).
Use MySQL FIND_IN_SET function:
SELECT *
FROM table_name
WHERE id IN (..,..,..,..)
ORDER BY FIND_IN_SET (coloumn_name, .., .., ..);
For Oracle, John's solution using instr() function works. Here's slightly different solution that worked -
SELECT id
FROM table1
WHERE id IN (1, 20, 45, 60)
ORDER BY instr('1, 20, 45, 60', id)
I just tried to do this is MS SQL Server where we do not have FIELD():
SELECT table1.id
...
INNER JOIN
(VALUES (10,1),(3,2),(4,3),(5,4),(7,5),(8,6),(9,7),(2,8),(6,9),(5,10)
) AS X(id,sortorder)
ON X.id = table1.id
ORDER BY X.sortorder
Note that I am allowing duplication too.
Give this a shot:
SELECT name, description, ...
WHERE id IN
(SELECT id FROM table1 WHERE...)
ORDER BY
(SELECT display_order FROM table1 WHERE...),
(SELECT name FROM table1 WHERE...)
The WHEREs will probably take a little tweaking to get the correlated subqueries working properly, but the basic principle should be sound.
My first thought was to write a single query, but you said that was not possible because one is run by the user and the other is run in the background. How are you storing the list of ids to pass from the user to the background process? Why not put them in a temporary table with a column to signify the order.
So how about this:
The user interface bit runs and inserts values into a new table you create. It would insert the id, position and some sort of job number identifier)
The job number is passed to the background process (instead of all the ids)
The background process does a select from the table in step 1 and you join in to get the other information that you require. It uses the job number in the WHERE clause and orders by the position column.
The background process, when finished, deletes from the table based on the job identifier.
I think you should manage to store your data in a way that you will simply do a join and it will be perfect, so no hacks and complicated things going on.
I have for instance a "Recently played" list of track ids, on SQLite i simply do:
SELECT * FROM recently NATURAL JOIN tracks;

MYSQL Query: 3 Table UNION, Last 100 Results in ASC Order

So far, I have taken 3 tables and joined them together. What I want to do is display the Last 100 entries (DESC) in ASC ORDER according to the timestamp in the column Posted.
This is as far as I could get: http://sqlfiddle.com/#!9/e2771/1
In addition, if there is a more efficient way to do this in PhP and not MYSQL, I'm all for that. I've tried looking, but haven't been able to find anything that works.
You just need one more level of sort:
select t.*
from (<your query here>) t
order by posted;

SQL: How to sort query by date (DESC) while having rows with column specified value at top?

My brain is failing me in this. I'm sure this is easily found by searching, but I'm having a hell of a time wording it to find any relevant results.
I'm using Laravel, so if there's an Eloquent solution, that would be preferred, but a RAW query would be fine as well.
I have a table, called threads, which has the two columns status and of course updated_at. I would like to sort by updated_at DESC, but have any rows with a status of a specified value returned on top, but also that group sorted by updated_at.
I hope that makes sense.
Here's what I believe you need.
ORDER BY status=17 DESC, updated_at DESC
Edit. This ORDER BY expression doesn't have any effect on the rows selected, only on their ordering. It works because the expression status=17, as a Boolean value, has either the value 1 or 0. Ordering it DESC puts the true ones first and the false ones second. Then the updated_at DESC puts the rows in descending order by date.
I'm guessing about 17. Put your desired status there instead.
This
it sounds like you want
select status, updated_at from threads order by status, updated_at desc

MySQL Query - How to order the results in a certain way

Below is a preview of what I have so far:
MySQL Table:
What I want to do is be able to sort this in a certain way. I would like for all rows that are "FREE" to be at the very top, so where special_price is equal to 0.00.
I also would like all rows with a special to be after that, and then all rows with just a normal price would be after that. Is there any way to do that without specifying a sort_id so the user wouldn't have to change the order themselves?
So in the above example, the last field "Testing" would be moved up one, and "Replace Air Filter" would be last.
Right now in my query there is no ORDER BY, so it is ordering by the id.
Any help is appreciated. Thanks!
ORDER BY COALESCE(special_price,99999) ASC, price ASC
should do the trick.
Explaination
COALESCE is a function that takes the first non-null value, so anywhere you have a null special price, it will default to 99999 (just some arbitrary high number to get it at the end of the ordering). From there we order on price, so any ties, as well as the end of the list, will be in ascending order by price.
You can combine two selects with UNION
SELECT * FROM `table` WHERE `special_price` IS NOT NULL ORDER BY `special_price` ASC,`price` ASC;
UNION ALL
SELECT * FROM `table` WHERE `special_price` IS NULL ORDER BY `price` ASC;
I don't know, how this behaves from the performance point of view, but as far as I know this is just like two simple queries, with the small overhead from UNION.
Minor update: Because both queries cannot return the same records the default behaviour UNION DISTINCT is not required and I hope, that UNION ALL is just a little bit more performant.
Using a function return value to sort the results can be very slow if you are sorting a large number of rows because MySQL can't use an index to sort these values. So how to get around this?
If an item MUST be on special to be free (which seems to be the case from the table layout image you provided) you could try:
SELECT *, special_price IS NULL AS not_special
FROM tablename
ORDER BY not_special ASC, special_price ASC, price ASC;
This adds an extra column to the results that equals 0 if the item is on special, 1 if not. We then put all the "special" items at the top of the sort and sort by ascending special price and price.
This will allow you to avoid the overhead of UNION, still use an index for the sort operation and avoid very slow queries when sorting a large number of rows with a function return value ... but only if an item must be on special to be free.
try
SELECT * FROM table_name ORDER BY CASE special_price
WHEN '0.00' THEN 1
WHEN null THEN 3
ELSE 2
END

PHP, MYSQL: Order by date but empty dates last not first

I fetch an array with todo titles and due dates from MySQL. I want to order it by date and have the oldest on top. But there are some todos without a date. These todos I don't want to show at first positions but rather at the bottom of my list. Unfortunately MySQL put the empty ones first.
Is there any way I can do it in one query (can't use MySQLi, using CI's ActiveRecord). I could run a second query for all todos without dates and put them at the bottom. But I'd like to make it in one query – if possible?
You can do it in MySQL with the ORDER BY clause. Sort by NULL first, then the date.
SELECT * FROM your_table ORDER BY (date_column IS NULL), date_column ASC
Note: This assumes rows without a date are NULL.
Yes
SELECT *
FROM table
ORDER BY CASE your_date
WHEN '' THEN 'b'
ELSE 'a'
END,
date ASC
possibly add a NVL( thedate, to_date('2099-12-31','yyyy-mm-dd')) in the order by clause
You can use this:
select * from my_table
order by if(isnull(my_field),1,0),my_field;
Well, as a pure MySQL answer, I would probably do it like this.
select todo.title, todo.due_date
from todo
order by ifnull(todo.due_date, '9999-12-31')

Categories