How to order selection from database alphabetically? - mysql

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

Related

Order by LOCATE 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

Multiple Order by (date and time ) not working in MYSQL

I am combining multiple tables, filtering and then ordering by certain format. Every time I try to order by both date and time, it messes up the output.
SELECT
t1.empid,t2.lastName,t2.firstName
,t1.date as "OVERBOOKED DATE",t1.sfrom,t1.dept as "dname"
,t3.manager as "MANAGER"
from schedule_2 as t1
INNER JOIN employees_2 as t2 ON t1.empid = t2.empid
INNER JOIN dept_heads as t3 ON t1.dept = t3.Dept_name
JOIN ( SELECT empid,date from schedule_2
GROUP BY empid,date
having count(empid)>1
) inr on inr.empid=t1.empid and inr.date=t1.date
ORDER BY empid ASC, "OVERBOOKED DATE" ASC, sfrom ASC;
Im attaching the snippet of the output and the snippet of expected output. Im new to this, so would appreciate any help!
[
[
Your problem is that the values in your sfrom column are not valid inputs to the DATE function (as you are using it in your "Current Output" query). You need to use STR_TO_DATE to convert them to a valid value for ordering i.e. replace sfrom (or DATE(sfrom)) in your ORDER BY clause with
ORDER BY empid ASC, "OVERBOOKED DATE" ASC, STR_TO_DATE(sfrom, '%h%p') ASC
Edit
As has been pointed out by #TimBiegeleisen, "OVERBOOKED DATE" is just a string literal and is not valid to sort by, either the raw column name (t1.date), a regular name alias (OVERBOOKED_DATE) or the alias name in backticks should be used e.g.
ORDER BY empid ASC, `OVERBOOKED DATE` ASC, STR_TO_DATE(sfrom, '%h%p') ASC
You are storing date and time separately, which isn't usually a good idea, because it often leads to problems exactly like the one you are facing now. Given that the hour portion of your time string is fixed width, and that AM/PM sort correctly in ascending order, we can try the following:
ORDER BY
empid,
OVERBOOKED_DATE, -- DON'T use aliases with spaces, if you plan to order by them
RIGHT(sfrom, 2),
LEFT(sfrom, 2);
Note: Doing ORDER BY "OVERBOOKED DATE" appears to be ordering by a string literal, which is really no ordering at all. Instead, use the following alias:
OVERBOOKED_DATE
And then order by this single term alias.

Obtaining the maximum value with Order By and Limit 1

First of all, I am using MySQL. When I make the following query:
SELECT CodE,sum(tiempo) AS 'tiempo total'
FROM Participa
GROUP BY CodE
ORDER BY 'tiempo total' DESC LIMIT 1;
it shows me the first line of my table instead of the MAX value. However, If I make the following query:
SELECT CodE,sum(tiempo)
FROM Participa
GROUP BY CodE
ORDER BY 2 DESC LIMIT 1
I get the correct result.
I have just changed the alias 'tiempo total' for somthing that should be equivalent.
How it´s possible?
Only use single quotes for string and date constants -- never for column aliases. So:
SELECT CodE, sum(tiempo) AS `tiempo total`
FROM Participa
GROUP BY CodE
ORDER BY `tiempo total` DESC
LIMIT 1;
You are ordering by a constant string, not the name of a column. Hence, if you get the maximum in your query, it would be a total accident.
Note: You can get around these issues by giving columns names that never need to be escaped:
SELECT CodE, sum(tiempo) AS tiempo_total
FROM Participa
GROUP BY CodE
ORDER BY tiempo_total DESC
LIMIT 1;
Easier to type, too.

MySQL INSERT... SELECT column count and virtual/aliased columns

I'm trying to insert using a select statement. However, I need to order the sub-select results using a ranking equation. If I create an alias, it throws off the column count. Can I somehow order my results using an equation?
INSERT INTO draft
( fk_contrib_id , end_time )
SELECT pk_contrib_id, UNIX_TIMESTAMP(), (X+Y+Z) AS ranking
FROM contrib
ORDER BY ranking DESC
LIMIT 1
I need the 'ranking' column for sorting, but if I do, the column count is off for the insert. Do I have to use two queries for this?
You could simply change your query to directly use the expression in the ORDER BY clause, like so:
INSERT INTO draft
( fk_contrib_id , end_time )
SELECT pk_contrib_id, UNIX_TIMESTAMP()
FROM contrib
ORDER BY (X+Y+Z) DESC
LIMIT 1
Remove the expression from the SELECT list. And use the expression in the ORDER BY clause.
ORDER BY X+Y+Z
It's perfectly valid to ORDER BY expressions that are not in the SELECT list.

MySQL sort by not sorting?

I am fetching rows from my DB using this request:
SELECT * FROM {$db_sales} WHERE date = '{$date}' ORDER BY 'amount' DESC
So, obviously, i expected the returned values to be sorted in descending order by the amount column in my DB, but it doesn't? it still fetches them, but just doesn't sort them?
Any ideas here? is my SQL statement wrong?
remove single quote around amount like this and try:
SELECT * FROM {$db_sales} WHERE date = '{$date}' ORDER BY amount DESC
Use below query
SELECT * FROM {$db_sales} WHERE date = '{$date}' ORDER BY amount DESC
ORDER BY clause uses column name.
Column name should not give in quotes.
there fore the query becomes as follows
SELECT * FROM {$db_sales} WHERE date = '{$date}' ORDER BY amount DESC