I have a column which holds status of applications - (New/Approved/Declined/Pending)
The column name is status. Now how do I order the select statement to order status so that 'New' applications come to the top of the display.
I tried this (SELECT * FROM applications ORDER BY status where status ='New')
This does not work, it is giving me error message.
Given status values "archived", "new" and "old" (for which neither ASC or DESC are working) and you want to retrieve all rows, "new" ones first, use this:
SELECT * FROM `applications`
ORDER BY IF(`status` = "new", 0, 1)
Try this:
SELECT * FROM applications ORDER BY status ASC;
If all you have is 'New' and 'Old', then this will result in 'New' first.
If you ONLY want New orders then you don't need an ORDER BY:
SELECT * FROM applications WHERE `status` = 'New';
If there are all kinds of values, like New/Approved/Declined/Pending and you just want to make sure 'New' is at the top you can do this
SELECT * FROM applications ORDER BY `status`, FIELD(`status`,'New');
What if you want 'New' first, then 'Approved', then you don't care what?
SELECT * FROM applications ORDER BY `status`, FIELD(`status`,'New','Approved');
(ASC and DESC have no effect after FIELD, but DESC after status will put your favorite values at the bottom rather than the top)
What about reversing their order but keeping them at the top? Either change their order in the FIELD() function or see below.
Finally, contrary to the previous suggestion, this does not really work:
SELECT * FROM applications ORDER BY FIELD(`status`,'New','Approved'),`status`;
To fix it, you need DESC after FIELD, but it gives you your values ordered in reverse (i.e. 'Approved' first, then 'New', then the rest):
SELECT * FROM applications ORDER BY FIELD(`status`,'New','Approved') DESC,`status`;
I think I spent too much time on this answer. Hmmm.
ugly but
(SELECT * FROM applications where status ='New')
union all
(SELECT * FROM applications where status !='New')
If you want to use this for something serious, replace the status column with a foreign key and add another table for the textual representations of your status_ids.
Then you can sort using
SELECT * FROM applications ORDER BY status_id
Try to avoid using reserved names for columns. It is possible to use them (with backticks), but can easily lead to problems if you don't take care.
Related
I'm new to this, sorry if the title is confusing. I am building a simple php/mysql gallery of sorts. It will show the newest 25 entries when a user first goes to it, and also allows off-site linking to individual items in the list. If the URL contains an ID, javascript will scroll to it. But if there are 25+ entries, it's possible that my query will fetch the newest results, but omit an older entry that happens to be in the URL as an ID.
That means I need to do something like this...
SELECT * FROM `submissions` WHERE uid='$sid'
But after that has successfully found the submission with the special ID, also do
SELECT * FROM `submissions` ORDER BY `id` DESC LIMIT 0, 25`
So that I can populate the rest of the gallery.
I could query that database twice, but I am assuming there's some nifty way to avoid that. MySQL is also ordering everything (based on newest, views, and other vars) and using two queries would break that.
You could limit across a UNION like this:
(SELECT * FROM submissions WHERE uid = '$uid')
UNION
(SELECT * FROM submissions WHERE uid <> '$uid' ORDER BY `id` LIMIT 25)
LIMIT 25
Note LIMIT is listed twice as in the case that the first query returns a result, we would have 26 results in the union set. This will also place the "searched for" item first in the returned sort result set (with the other 24 results displayed in sort order). If this is not desirable, you could place an ORDER BY across the union, but your searched for result would be truncated if it happened to be the 26th record.
If you need 25 rows with all of them being sorted, my guess is that you would need to do the two query approach (limiting second query to either 24 or 25 records depending on whether the first query matched), and then simply insert the uid-matched result into the sorted records in the appropriate place before display.
I think the better solution is:
SELECT *
FROM `submissions`
order by (case when usid = $sid then 0 else 1 end),
id desc
limit 25
I don't think the union is guaranteed to return results in the order of the union (there is no guarantee in the standard or in other databases).
I am looking to create an order based on multiple columns in my table - all date related. For example: my columns are: fee_due, fee_2_due, fee_3_due - they all contains results of various dates. However, I want to create an order combining all columns, so fee_due might be 2012-11-03, fee_2_due might be 2012-11-01 and fee_3_due might be 2012-11-02.
My query needs to be:
SELECT *
FROM table_name
ORDER BY [date] DESC
... whereby the dates from the 3 columns join to form one order, regardless of what column they are in.
Hope that makes sense and thanks in advance.
Additionally you can:
SELECT *
FROM table_name
ORDER BY fee_due ASC,fee_2_due DESC,fee_3_due DESC
You can sort each column independently according to your need.
I used the following to make it work:
SELECT * FROM table ORDER BY camp1 ASC, camp2 ASC, camp3 DESC
Have you try this:
SELECT *
FROM table_name
ORDER BY fee_due,fee_2_due,fee_3_due DESC
I got an odd problem. Whenever I add a new entry to the database it gives it a higher id number, but somehow sees it as a lower number and puts it below the older ones.
And when sorting DESC in PHP I also get this order, does anybody know whats going wrong here?
I use $res = mysql_query("SELECT * FROM data ORDER BY 'id' DESC");to sort them, and it gives the same order as in the pic. (Not sure why i'm being downvoted here but ok..)
Pic:
Your query is:
SELECT * FROM data ORDER BY 'id' DESC
You are sorting by the string 'id', note the syntax highlighting when not within quotes. This means you get them in a random order. Remove the '. If you meant to escape the column id you should use back-ticks:
SELECT * FROM data ORDER BY `id` DESC
When you insert data on the tables, it does not mean that the new number (or the highest) always on the lowest row. It randomly inserts the record. The only way you can sort it when you retrieve the rows in by using ORDER BY clause, example
SELECT *
FROM tableName
ORDER BY ID DESC
So assume that ID is numeric. If you're ID is stored as string then you should convert it to numeric,
SELECT *
FROM tableName
ORDER BY CAST(ID AS SIGNED) DESC
UPDATE 1
It should be
$res = mysql_query("SELECT * FROM data ORDER BY `id` DESC");
not
$res = mysql_query("SELECT * FROM data ORDER BY 'id' DESC");
what you have done was you have surrounded the ID with single quote forcing the server to read it as String and not Numeric
When you are not using any ORDER BY clause, the order in PHPMyAdmin is kind of random. Indeed, new rows could take place of old ones.
I am curious how you sort DESC in PHP though.
Don't absolutely trust in GUI web interface because sometimes (not always) it bugs with session management, however you can run SQL Queries using it.
1- To run a SQL query, click on "SQL" on the navigation bar.
2- Enter your SQL in the box provided.
SELECT *
FROM tableName
ORDER BY ID DESC
3- Click "Go".
I have two type of deal in my form 1)One way relocation deal and 2)Regular deal.There is a table in my db -Vehicles.
vehicles table
=====================================================
id, pickuplocation, returnlocation, included location
Now when user choose One way relocation deal then in db, only id,pickuplocation,returnlocation will be inserted and the coloumn included location will be null. And when user choose Regular deal,the column pickuplocation,returnlocation wil be null only the coloumn id and included location will set.Problem is i want to sort the whole data using their location.I tried this query -
SELECT *
FROM vehicles
where 1=1
ORDER BY pickuplocation ASC,returnlocation ASC
But it will not giving proper result because some data having null in included location.how can i sort for all pickuplocation,returnlocation,exculded location
You want the IFNULL function
Try sorting by
IFNULL(returnlocation, includedlocation)
Got the solution.I used this query
(SELECT id,pickuplocation,returnlocation,deal_type FROM `vehicles` where deal_type = 1)
UNION
(SELECT id,included_location,excluded_location,deal_type FROM `vehicles` where deal_type = 2)
order by pickuplocation,returnlocation
I hope this will help someone who may run into a similar problem in the future.
SELECT *
FROM vehicles
where 1=1 AND ($condition)
ORDER BY pickuplocation ASC,returnlocation ASC
Assuming $condition will be something like field01=1 OR field2 >=1
Alright, I'm trying to figure out why I can't understand how to do this well...
I have two tables:
invoices:
id
userID
amount
date
payments:
id
userID
amount
date
So, the goal here is to join both tables, where the userID matches whatever I want it to be - and then return everything ordered by date (most recent at the top). However, because there is a date field in each of the tables, I'm not sure how MySQL will handle things... will is sort by both dates automatically? Here's what I was thinking...
"SELECT DISTINCT *
FROM invoices,payments
WHERE {$userID} = invoice.userID
OR {$userID} = payments.userID
ORDER BY date DESC";
But, it's starting to become clear to me that maybe this isn't even the right use of a join command... maybe I need to just get all data on each table alone, then try to sort it somehow with PHP? If that's the better method, what's a good way to do this type of DATE sort while keeping all row data in tact?
I should add, the TIME inside the unix timestamp (that's how "date" is stored) is NOT negligible - it should sort by the date and time.
Thanks all...
If the columns of both tables are the same, you can use a UNION
SELECT X.*
FROM ( SELECT `id`,
`userID`,
'INVOICE' AS PTYPE
`amount`,
`date`
FROM `invoices`
WHERE {$userID} = userID
UNION
SELECT `id`,
`userID`,
'PAYMENT' AS PTYPE
`amount`,
`date`
FROM `payments`
WHERE {$userID} = userID
) X
ORDER BY X.`date`
EDIT
Read the relevant section of the MySQL manual on UNIONS. There are other ways of phrasing this, but this is my preferred style - it should be clear to anybody reading that the ORDER BY clause applies to the result of both sides of the UNION. A carelessly written UNION - even with an ORDER BY - may still leave the final resultset in indeterminate order.
The purpose of the PTYPE is that this query returns an extra column called PTYPE, that indicates whether each individual row is an INVOICE or a PAYMENT... ie. which of the two tables it comes from. It's not mandatory, but can often be useful within a union
Because you have two identical fields named date, MySQL will not know which one you're trying to order by.
"SELECT DISTINCT *
FROM invoices,payments
WHERE {$userID} = invoice.userID
OR {$userID} = payments.userID
ORDER BY invoices.date, payments.date DESC";
This would sort on the invoice date, then the payment date - if that's what you are trying to find out
If your data tipe is Date, Timestamp, or anything related, the SGBD will order it properly. If that was what you've asked.
But if the datatype is String, even when dates is store, it will not sort the way you want.