Mysql select order by acts like a string, not a number - php

How do you order by number if your number can fall below and be bigger than 0?
Example Mysql table:
|Name|Karma|
__________
|Me | -8 |
|Bill| 5 |
|Tom | 2 |
|Saly| 0 |
|San.| -3 |
Example select query
$sql="SELECT karma FROM table ORDER BY karma DESC";
The result I get is this (separated by comma): 5,2,0,-8,-3.
Shouldn't it be 5,2,0,-3,-8?
I discovered somewhere in the internet that mysql orders by string. How to make it order by number?

Karma will be ordered as a string if you have made it a string, i.e. a varchar column.
Convert the column to a INT, and it will order numerically.
You also have the option of not changing the table, but casting the column into the right type while sorting:
SELECT karma FROM table ORDER BY CAST(karma AS int) DESC
but that is bad for performance.

There's another weirdest option:
SELECT karma FROM table ORDER BY karma+0 DESC

Related

Select a table values ordered by two field [duplicate]

How can I sort by multiple columns in SQL and in different directions. column1 would be sorted descending, and column2 ascending.
ORDER BY column1 DESC, column2
This sorts everything by column1 (descending) first, and then by column2 (ascending, which is the default) whenever the column1 fields for two or more rows are equal.
The other answers lack a concrete example, so here it goes:
Given the following People table:
FirstName | LastName | YearOfBirth
----------------------------------------
Thomas | Alva Edison | 1847
Benjamin | Franklin | 1706
Thomas | More | 1478
Thomas | Jefferson | 1826
If you execute the query below:
SELECT * FROM People ORDER BY FirstName DESC, YearOfBirth ASC
The result set will look like this:
FirstName | LastName | YearOfBirth
----------------------------------------
Thomas | More | 1478
Thomas | Jefferson | 1826
Thomas | Alva Edison | 1847
Benjamin | Franklin | 1706
SELECT *
FROM mytable
ORDER BY
column1 DESC, column2 ASC
Multiple column ordering depends on both column's corresponding values:
Here is my table example where are two columns named with Alphabets and Numbers and the values in these two columns are asc and desc orders.
Now I perform Order By in these two columns by executing below command:
Now again I insert new values in these two columns, where Alphabet value in ASC order:
and the columns in Example table look like this.
Now again perform the same operation:
You can see the values in the first column are in desc order but second column is not in ASC order.
You can use multiple ordering on multiple condition,
ORDER BY
(CASE
WHEN #AlphabetBy = 2 THEN [Drug Name]
END) ASC,
CASE
WHEN #TopBy = 1 THEN [Rx Count]
WHEN #TopBy = 2 THEN [Cost]
WHEN #TopBy = 3 THEN [Revenue]
END DESC
SELECT id,
first_name,
last_name,
salary
FROM employee
ORDER BY salary DESC, last_name;
If you want to select records from a table but would like to see them sorted according to two columns, you can do so with ORDER BY. This clause comes at the end of your SQL query.
After the ORDER BY keyword, add the name of the column by which you’d like to sort records first (in our example, salary). Then, after a comma, add the second column (in our example, last_name). You can modify the sorting order (ascending or descending) separately for each column. If you want to use ascending (low to high) order, you can use the ASC keyword; this keyword is optional, though, as that is the default order when none is specified. If you want to use descending order, put the DESC keyword after the appropriate column (in the example, we used descending order for the salary column).
SELECT * FROM EMP ORDER BY DEPTNO ASC, JOB DESC;
TRY
'select * FROM users ORDER BY id DESC, name ASC, age DESC
You can also sort or order by the Number of Characters in each Column you wish to sort by. Shown below is a sample which sorts by the first three characters of the First Name and by the last two characters in the name of the town.
SELECT *
FROM table_name
ORDER BY LEFT(FirstName, 3) ASC, LEFT(Town, 2);

Select distinct by highest or lowest value

I'm working on a track and field ranking database in MySQL/PHP5 whereby I'm struggling to find the best way to query results per unique athlete by highest value.
just
SELECT distinct name, event
FROM results
sample database
name | event | result
--------------------------
athlete 1 | 40 | 7.43
athlete 2 | 40 | 7.66
athlete 1 | 40 | 7.33
athlete 1 | 60 | 9.99
athlete 2 | 60 | 10.55
so let's say that in this case I'd like to rank the athletes on the 40m dash event by best performance I tried
SELECT distinct name, event
FROM results
WHERE event = 40
ORDER by result DESC
but the distinct only leaves the first performance (7.43) of the athlete which isn't the best (7.33). Is there an easy way other than creating a temp table first whereby the results are ordered first and performing a select on the temp table afterwards?
You might be interested in group by:
SELECT name, min(result) as result
FROM results
WHERE event = 40
GROUP BY name
This gives you the best result per athlete.
As suggested by spencer, you can also order the list by appending this:
ORDER BY min(result) ASC
The problem is that the columns used in the ORDER BY aren't specified in the DISTINCT. To do this, you need to use an aggregate function to sort on, and use a GROUP BY to make the DISTINCT work.
SELECT distinct name, event
FROM results
WHERE event = 40
GROUP BY name
ORDER by result DESC

How to check the greatest number in table in SQL using PHP

I was just wondering that, how to get the greatest number in the table.
I mean i have a table called: hits; in that their are 2 columns:
1. id
2. hit
and their are many ids in the table and all have more than 10 hits, now what i want to do is to get the greatest id of the greatest hit
PS: See below:
id | hit
---|----
1 | 10
2 | 15
3 | 45
4 | 9
yes you can use MAX function to use like below
Select Id,Max(hit) from yourtableName group by id having hit=Max(hit)
Select Id,
Max(Hit)
from tableName
group by id
having Max(hit)=(Select Max(Hit) from TableName)
SQL FIDDLE Demo
Wouldn't it be faster to do this:
SELECT * FROM table WHERE 1 ORDER BY hit DESC, id DESC LIMIT 1
Rather than using MAX, Especially if you have a larger table
http://www.witti.ws/blog/2011/04/06/mysqls-max-slow-5-years-later

Lowest varchar amount

I am having issues comparing two values in the Mysql database and display the lowest one.
For instance I have this:
value1 = 23.4
value2 = 4.479
I tried this:
ORDER BY CAST(column AS SIGNED) ASC
but its not working
Again, field type is VARCHAR.
The result I am looking for should be 23.4 and not 4.479
any suggestions?
Simply put, you need to change your column to DECIMAL if you're storing prices. VARCHAR will be in alphabetical order. Read up on Numeric Types in MySQL.
ALTER TABLE your_table MODIFY COLUMN price DECIMAL(10,3);
A pretty costly work-around for you is to cast all values to decimal before sorting:
SELECT name, price FROM test ORDER BY CAST(price AS DECIMAL(20, 10)) ASC LIMIT 1
Just make sure your DECIMAL limits are enough to correctly cast all values in the column.
It will work if you CAST it to DECIMAL.
select * from tablename order by cast(price as decimal);
+--------+-------+
| name | price |
+--------+-------+
| nail | 0.95 |
| glue | 9.23 |
| hammer | 45.12 |
+--------+-------+

Count/Group By/Order By is only showing the count of the most common value and not the string itself

I'm querying a table to find the most common string in a column. However, it doens't seem to be working correctly. It should be returning the value of the most common string, but is instead returning the number of times the most common string exists. The query is:
SELECT COUNT(field_review_bar_tab_2_value) AS `Rows`
FROM (field_data_field_review_bar_tab_2)
GROUP BY (field_review_bar_tab_2_value)
ORDER BY `Rows` DESC
LIMIT 1
Table structure, simplified, would be something to the effect of:
-----------------------------------
| ID | field_review_bar_tab_2_value |
|----+----------------------------- |
| 1 | Food Drinks |
| 2 | Drinks |
| 3 | Food Drinks |
| 4 | Food |
-----------------------------------
The query is recognizing that, in the example above, "Food Drinks" is the most common string in the column. But, the query is returning "2" instead of "Food Drinks". Any ideas as to why it would be making the correct query but returning the count of the result instead of the value of the string?
You need to include field_review_bar_tab_2_value in the SELECT list as well. I've switched the aggregate to COUNT(*) here, and included the grouped column in the SELECT.
SELECT
field_review_bar_tab_2_value AS the_most_common_string,
COUNT(*) AS `Rows`
FROM (field_data_field_review_bar_tab_2)
GROUP BY (field_review_bar_tab_2_value)
ORDER BY `Rows` DESC
LIMIT 1
You're selecting the count, not the value. I think you mean:
SELECT field_review_bar_tab_2_value
FROM field_data_field_review_bar_tab_2
GROUP BY field_review_bar_tab_2_value
ORDER BY COUNT(*) DESC
LIMIT 1
Since you're already grouping by the value in question, you can just do COUNT(*)...
You will need to modify your query to return the field itself. Currently the query is only returning the COUNT because that's what is indicated in your select statement. Modify it as follows:
SELECT field_review_bar_tab_2_value AS `MostCommonString`, COUNT(field_review_bar_tab_2_value) AS `Rows`
FROM (field_data_field_review_bar_tab_2)
GROUP BY (field_review_bar_tab_2_value)
ORDER BY `Rows` DESC
LIMIT 1

Categories