Select query to last row of table giving wrong result in mysql - mysql

I want to fetch last row of the table. For this i have used to below query but it returns me 99 where my table contains approx 123 and last pro_id = 123. Right result should be 123.
please suggest me for right way :
SELECT * FROM product ORDER BY pro_id DESC LIMIT 1

That's most likely because your pro_id column is defined as text.
You can tell sql to order by the numeric value in that column with
SELECT * FROM product ORDER BY CONVERT(pro_id, UNSIGNED INTEGER) DESC LIMIT 1

I think the problem is that your pro_id is character and it will be ordered by alphabetical order. You could try to convert it to number first.
SELECT * FROM product ORDER BY CAST(pro_id AS UNSIGNED) DESC LIMIT 1

This query will display a true desc result:
select pro_id from
(SELECT cast(replace(pro_id,' ','') as UNSIGNED) as pro_id from product) as a
ORDER BY pro_id desc limit 1

Related

Will DISTINCT always return a same order of values for a same SQL?

I have a sql statement is with pattern
SELECT id FROM table WHERE [conditions] ORDER BY [orders] LIMIT 10000 OFFSET 0
and the return value is like below:
id
-----
1
0
0
0
0
1
1
1
2
2
...
Then I want to get the distinct value as the order of their first appearance, since there's an ORDER BY in the sql, and DISTINCT or GROUP BY are both happened before ORDER BY in a sql, I tried below sql.
SELECT DISTINCT id FROM (SELECT id FROM table WHERE [conditions] ORDER BY [orders] LIMIT 10000 OFFSET 0) tmp;
And the result is like what I want:
id
----
1
0
2
...
My question is: can I ensure that in a same pattern SQL, DISTINCT will always return the distinct id as the order their first appearance?
Thanks.
---------------Notes------------------
Below can be ignored. I just noticed many peoples are recommended to try GROUP BY, so I tried below sql as well:
SELECT id FROM (SELECT id FROM table WHERE [conditions] ORDER BY [orders] LIMIT 10000 OFFSET 0) tmp GROUP BY id;
but the returning is reordered by the alpha-beta order (it's not integer order because the column is a CHAR column for the real id is a string), which is not what I want.
id
----
0
1
10
100
....
If you want results in a particular order, then you need to specify that in the ORDER BY for the outermost SELECT. That suggests something like this:
SELECT id
FROM tabl
WHERE [conditions]
ORDER BY [orders]
LIMIT 10000 OFFSET 0
Then, if you want to order by the first appearance, you need a column that specifies the first appearance. Let's call this CreatedAt (perhaps it is orders?). If so:
SELECT id
FROM table
WHERE conditions
GROUP BY id
ORDER BY min(CreatedAt)
LIMIT 10000;
Note: SQL tables represent unordered sets, so you need a column to specify the ordering of interest.

Attempting to order table multiple times

I am trying to group multiple rows and order it by the total values but im struggling to figure out whats going wrong.
Name Total
======= =======
ASOS 222
Tesco 11
ASOS 11111
Tesco 123
The table should look like this
Name Total
======= =======
ASOS 11111
ASOS 222
Tesco 123
Tesco 11
I thought this query would work
select * from tablename order by name asc, total asc
But that shows a result in the wrong order.
Any help would be appreciated.
Try this
select * from tablename order by total desc
Selecting two things to ORDER BY doesn't work too well if you're not familiar with ORDER BY syntax. from your description, it looks like you just want the highest total at the top. This query will order the results by total descending (highest first)
if you want the names to be ascending (lowest first) at the same time, try
select * from tablename order by name asc, total desc
First order by the max total for each name, descending, the order by total descending:
select *
from tablename t1
order by (select max(total) from tablename t2
where t1.name = t2.name) desc,
total desc
Try this:
SELECT *
FROM tablename
ORDER BY
Name,
char_length(CAST(Total As varchar(max))) DESC,
Total DESC

How to get the end of an Ascending list of records with a limit?

I'm fighting a bit with a query I'm building. Let's say I've got a DB table like this:
id | some_string
----------------
1 | 'lala'
2 | 'jeje'
3 | 'poopoo'
4 | 'wicked wicked'
I now want to get the last three records (2, 3, and 4) ordered ascending by key. I tried this:
SELECT * FROM tableName LIMIT 3 ORDER BY id ASC
This gets me the first three records, instead of the last three. I can of course also use the query below, which gets me the correct records, but then I don't get them in Ascending order:
SELECT * FROM tableName LIMIT 3 ORDER BY id DESC
Does anybody know how I can get the last three records in an ascending order? All tips are welcome!
select * from (
select * from table_name order by id desc limit 3
) last_3_rows
order by id
Sort on the resulting result set ie. do a select * from (<your query here>) order by id
This is a query inside another query. that reorders your query.(SQL - How to reorder a select query that uses the limit constraint)
select * FROM (SELECT * FROM tableName LIMIT 3 ORDER BY id DESC) AN_UNUSUAL_NAME ORDER BY id ASC

Find most frequent value in SQL column

How can I find the most frequent value in a given column in an SQL table?
For example, for this table it should return two since it is the most frequent value:
one
two
two
three
SELECT
<column_name>,
COUNT(<column_name>) AS `value_occurrence`
FROM
<my_table>
GROUP BY
<column_name>
ORDER BY
`value_occurrence` DESC
LIMIT 1;
Replace <column_name> and <my_table>. Increase 1 if you want to see the N most common values of the column.
Try something like:
SELECT `column`
FROM `your_table`
GROUP BY `column`
ORDER BY COUNT(*) DESC
LIMIT 1;
Let us consider table name as tblperson and column name as city. I want to retrieve the most repeated city from the city column:
select city,count(*) as nor from tblperson
group by city
having count(*) =(select max(nor) from
(select city,count(*) as nor from tblperson group by city) tblperson)
Here nor is an alias name.
Below query seems to work good for me in SQL Server database:
select column, COUNT(column) AS MOST_FREQUENT
from TABLE_NAME
GROUP BY column
ORDER BY COUNT(column) DESC
Result:
column MOST_FREQUENT
item1 highest count
item2 second highest
item3 third higest
..
..
For use with SQL Server.
As there is no limit command support in that.
Yo can use the top 1 command to find the maximum occurring value in the particular column in this case (value)
SELECT top1
`value`,
COUNT(`value`) AS `value_occurrence`
FROM
`my_table`
GROUP BY
`value`
ORDER BY
`value_occurrence` DESC;
Assuming Table is 'SalesLT.Customer' and the Column you are trying to figure out is 'CompanyName' and AggCompanyName is an Alias.
Select CompanyName, Count(CompanyName) as AggCompanyName from SalesLT.Customer
group by CompanyName
Order By Count(CompanyName) Desc;
If you can't use LIMIT or LIMIT is not an option for your query tool. You can use "ROWNUM" instead, but you will need a sub query:
SELECT FIELD_1, ALIAS1
FROM(SELECT FIELD_1, COUNT(FIELD_1) ALIAS1
FROM TABLENAME
GROUP BY FIELD_1
ORDER BY COUNT(FIELD_1) DESC)
WHERE ROWNUM = 1
If you have an ID column and you want to find most repetitive category from another column for each ID then you can use below query,
Table:
Query:
SELECT ID, CATEGORY, COUNT(*) AS FREQ
FROM TABLE
GROUP BY 1,2
QUALIFY ROW_NUMBER() OVER(PARTITION BY ID ORDER BY FREQ DESC) = 1;
Result:
Return all most frequent rows in case of tie
Find the most frequent value in mysql,display all in case of a tie gives two possible approaches:
Scalar subquery:
SELECT
"country",
COUNT(country) AS "cnt"
FROM "Sales"
GROUP BY "country"
HAVING
COUNT("country") = (
SELECT COUNT("country") AS "cnt"
FROM "Sales"
GROUP BY "country"
ORDER BY "cnt" DESC,
LIMIT 1
)
ORDER BY "country" ASC
With the RANK window function, available since MySQL 8+:
SELECT "country", "cnt"
FROM (
SELECT
"country",
COUNT("country") AS "cnt",
RANK() OVER (ORDER BY COUNT(*) DESC) "rnk"
FROM "Sales"
GROUP BY "country"
) AS "sub"
WHERE "rnk" = 1
ORDER BY "country" ASC
This method might save a second recount compared to the first one.
RANK works by ranking all rows, such that if two rows are at the top, both get rank 1. So it basically directly solves this type of use case.
RANK is also available on SQLite and PostgreSQL, I think it might be SQL standard, not sure.
In the above queries I also sorted by country to have more deterministic results.
Tested on SQLite 3.34.0, PostgreSQL 14.3, GitHub upstream.
Most frequent for each GROUP BY group
MySQL: MySQL SELECT most frequent by group
PostgreSQL:
Get most common value for each value of another column in SQL
https://dba.stackexchange.com/questions/193307/find-most-frequent-values-for-a-given-column
SQLite: SQL query for finding the most frequent value of a grouped by value
SELECT TOP 20 WITH TIES COUNT(Counted_Column) AS Count, OtherColumn1,
OtherColumn2, OtherColumn3, OtherColumn4
FROM Table_or_View_Name
WHERE
(Date_Column >= '01/01/2023') AND
(Date_Column <= '03/01/2023') AND
(Counted_Column = 'Desired_Text')
GROUP BY OtherColumn1, OtherColumn2, OtherColumn3, OtherColumn4
ORDER BY COUNT(Counted_Column) DESC
20 can be changed to any desired number
WITH TIES allows all ties in the count to be displayed
Date range used if date/time column exists and can be modified to search a date range as desired
Counted_Column 'Desired_Text' can be modified to only count certain entries in that column
Works in INSQL for my instance
One way I like to use is:
select *<given_column>*,COUNT(*<given_column>*)as VAR1 from Table_Name
group by *<given_column>*
order by VAR1 desc
limit 1

Most common number in MYSQL SELECT statement

I am trying to get a MYSql statement to spit out the most common number in a field. I believe I am supposed to use COUNT(QUANTITY) but I am confused by which to GROUP BY and ORDER BY, I can't seem to get the correct MODE (Most common number).
*EDIT*
Here is a sample table:
QUANTITY | ORDER_NUMBER
1 51541
4 12351
5 11361
5 12356
6 12565
8 51424
10 51445
25 51485
The MYSql statement should spit out the number 5 because it appears most often
SELECT QUANTITY,COUNT(*)
FROM ...
GROUP BY 1
ORDER BY 2 DESC
LIMIT 1;
SELECT ORDER_NUMBER AS ORDER, COUNT(QUANTITY) as numorders
FROM table
GROUP BY ORDER_NUMBER
ORDER BY numorders
to get the top 10 order_numbers do
select order_number, count(order_number) as quantity
from your_table
group by order_number
order by quantity desc
limit 10
SELECT QUANTITY, COUNT(QUANTITY) AS TOTAL_Q
FROM MYTABLE
GROUP BY QUANTITY
ORDER BY TOTAL_Q DESC
this will give you number of quanity from most to least number....