Order by LOCATE MySql - mysql

I'm trying to retrieve the data set by locating a string based on its occurrence, check the below query -
select name, LOCATE('test', name)
from afkapi_dev.articles
where name like '%test%'
order by LOCATE('test', name) ASC
The result set is -
Result set is perfectly fine, but the issue here is the ordering.
Can anyone explain why "testing" is listed above "test low" and also suggest a way to make this happen.
Thank you

You seem to be asking to do further sorting on name. For multiple level sorting, you can specify different columns/expressions in ORDER BY clause, separated by comma, with respective sorting order [ASC or DESC]
Also, you can alias the LOCATE(..) expression in the SELECT clause, and reuse that in the ORDER BY. This should prevent re-computation of LOCATE(..) values.
select name, LOCATE('test', name) AS location
from afkapi_dev.articles
where name like '%test%'
order by location ASC, name ASC

Related

How to order selection from database alphabetically?

From this code:
SELECT *
FROM members
ORDER BY #ALPHABETICALLY
How to order it in this type?
Thanks.
If you have name column in that table the query would be:
SELECT *
FROM members
ORDER BY name ASC
SELECT ..., last_name, first_name, ...
FROM tbl
ORDER BY last_name, first_name;
VARCHAR columns in ORDER BY are sorted alphabetically; INT columns are sorted numerically.
ASC and DESC are optional suffixes for "ascending" and "descending":
`ORDER BY date DESC`
to see the latest first.
SQL queries require you to provide a column to sort on -- otherwise, your database engine would have no idea which data to use. This is an error because the behavior that would result is almost certainly not what you would be expecting!
Per your comment, you want to sort alphabetically on "name". Presuming that name is a character column, sorting on it will result in an alphabetical sort. So the query you're looking for is:
SELECT *
FROM members
ORDER BY username ASC
ASC is optional and the default; it means to sort in ascending order. To sort Z -> A, you can specify DESC instead. You can specify a different column (say, email) to sort by it instead.
SELECT *
FROM `Table_Name`
ORDER BY `Your_Column_name_1` ASC, `Your_Column_name_2` DESC

How to surface a value for more than one row in MySQL

I know that I can surface a row in a query by using it in the ORDER BY like this :
SELECT IF(`category` IS NOT NULL,`category`,"Uncategorized") AS `category` FROM `table` ORDER BY `category`="Uncategorized" DESC
Which will make the first row always contain "Uncategorized", however I have multiple rows that contain it that I also want surfaced. Here are two sample sets of returned data:
What I'm getting:
Uncategorized
Science
Health
Uncategorized
Wellness
What I want:
Uncategorized
Uncategorized
Health
Science
Wellness
I have tried a number of other things including a CASE and also using a conditional IF. What am I doing wrong?
The reason why it is not working is because the ORDER BY clause is comparing with the column name category and not on the alias given on the column.
SELECT IF(category IS NOT NULL,category,'Uncategorized') category
FROM `table`
ORDER BY IF(category IS NOT NULL,category,'Uncategorized')='Uncategorized' DESC
you can alternatively use COALESCE or IFNULL to make it shorter
SELECT COALESCE(category, 'Uncategorized') category
FROM `table`
ORDER BY COALESCE(category, 'Uncategorized') = 'Uncategorized' DESC, category
You need to use the function in the ORDER BY clause.
SELECT IF(`category` IS NOT NULL,`category`,"Uncategorized") AS `category`
FROM `table`
ORDER BY IF(`category` IS NOT NULL,`category`,"Uncategorized")="Uncategorized" DESC
You can create a custom ordering via FIELD()
...
ORDER BY FIEID(category,
'Uncategorized',
'Health',
'Science'
'Wellness')
The FIELD() function returns the index of the 1st parameter in the others.

Order Results of search query mySQL

I have the following mysql query for a search function. I have in my data 3 different account types that I need to show in a specific order. For that I used ORDER BY FIELD(profiltype,2,1,3). That works great and with no problems, however within these results I also need to order the different columns in a priority like:
1. name2
2. a_z_feld1
etc.
However this is not working with the query I have below. It should keep the order of Profile types but within this order also have a priority of the columns.
SELECT * FROM main_users
WHERE ((name2 LIKE %s)
OR (a_z_feld1 LIKE %s)
OR (a_z_feld2 LIKE %s)
OR (a_z_feld3 LIKE %s)
OR (city LIKE %s)
OR (content_stellenvor LIKE %s)
OR (main_content LIKE %s))
AND levelmember <> 1
ORDER BY FIELD(profiltype,2,1,3) ASC,
a_z_feld1 ASC, a_z_feld2 ASC, a_z_feld3 ASC
Based on your comment, you need to include name in the order by:
ORDER BY FIELD(profiltype,2,1,3) ASC, name2, a_z_feld1 ASC, a_z_feld2 ASC, a_z_feld3 ASC

order by problem in date type

Same like date_format(ExpenditureDate,'%d-%m-%Y') between '01-01-2011' AND '31-01-2011' ,
Also i cant able to check cond with between, ????
ExpenditureDate -- DATE type
Below query Displaying correctly , latest dates are coming top and one by one
SELECT ExpenditureName,ExpenditureAmount,ExpenditurePlaceTypeWhome,ExpenditureDate FROM tblexpenditure WHERE Status=1 AND EntryUser=2 ORDER BY ExpenditureDate DESC
but if i add date_format(ExpenditureDate,'%d-%m-%Y') as ExpenditureDate
Then loose my proper order, it displaying inordered
SELECT ExpenditureName,ExpenditureAmount,ExpenditurePlaceTypeWhome,date_format(ExpenditureDate,'%d-%m-%Y') as ExpenditureDate FROM tblexpenditure WHERE Status=1 AND EntryUser=2 ORDER BY ExpenditureDate DESC
I don't have a box running mysql to test, but I try to avoid naming the string formated displayable 'expenditure date' the same as the one you sort by.
They probably come sorted, but by lexicographical order of the dates rather than chronological order. It's normal since you sort on the ExpenditureDate alias, which is a string containing the formatted date.
Use another alias :
SELECT ExpenditureName,ExpenditureAmount,ExpenditurePlaceTypeWhome,date_format(ExpenditureDate,'%d-%m-%Y') as FormattedExpenditureDate FROM tblexpenditure WHERE Status=1 AND EntryUser=2 ORDER BY ExpenditureDate DESC
If you really want to keep the same alias, you might also try this :
SELECT ExpenditureName,ExpenditureAmount,ExpenditurePlaceTypeWhome,date_format(ExpenditureDate,'%d-%m-%Y') as ExpenditureDate FROM tblexpenditure WHERE Status=1 AND EntryUser=2 ORDER BY tblexpenditure.ExpenditureDate DESC
MySQL seems to sort on the formatted value. Try writing
...,date_format(ExpenditureDate,'%d-%m-%Y') as FormattedExpenditureDate ...
but leave the ORDER BY clause with the column name.

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.