SQL ORDER BY date DESC - mysql

I have a table with several rows of timestamp (unix epoch)
eg: 1620518277 , 1556748676 , 1547547076, 1602756807, 944971077 (field name -> date_stamp)
And by using
SELECT *
FROM table
ORDER BY date_stamp DESC
The result of this query is :
1. 944971077
2. 1620518277
3. 1602756807
4. 1556748676
5. 1547547076
Everything is sorted fine but how can 944971077 > 1620518277 ???
Anybody had this kind of strange SQL issues ?

Presumably, you are storing these timestamps as strings, not as numbers. A simple option forces a numeric conversion:
SELECT * FROM table ORDER BY date_stamp + 0 DESC

This would occur if timestamp were a string. A simple method is to convert to a number using implicit conversion:
SELECT *
FROM table
ORDER BY date_stamp + 0 DESC

Related

Select only date form datetime field in where condition

I have stored this kind of format 2022-02-06 18:40:00 in my trans_reminder_date. I want to use only date in where condition but with this condition i am not able to fetch data
$today = date('Y-m-d');
SELECT * FROM sales_detail
WHERE trans_reminder_date = '".$today."'
AND trans_reminder_date != ''
ORDER BY sales_detail_id DESC";
If when your filter parameter is a string:
select * from sales_detail
where cast(trans_reminder_date as date) = cast('2020-03-22' as date)
if you want to use the current date for filtering then MySQL has a function that getting only the current date without time.
select * from sales_detail
where cast(trans_reminder_date as date) = curdate()
On MySQL for converting other types to another, you can use a cast
P.S.
Starting with MySQL 8.0.13 we have now an easiest way to create functional indexes. When you are using cast(updated_at as date) then DB will not use index for column updated_at. You must create a functional index for best performance.
The following query will give you all the result for the current date. By doing this there won't be any need to cast values.
SELECT
*
FROM
sales_detail
WHERE
trans_reminder_date >= curdate()
AND trans_reminder_date < curdate() + INTERVAL '1' DAY
ORDER BY
sales_detail_id DESC;
Using Cast function to change datetime type to date example
Cast(column_name as date)
Or
You using convert function change datetime type to date
CONVERT(column_name, date);
CONVERT(expression, datatype);
OR,
CONVERT(expression USING character_set);
character_set: It specifies the desired character set in which we want to be converted.
Data type : It specifies the desired data type in which we want to be converted.
Expression : It is a specified value going to be converted into another specific datatype.

MySQL - sort by date column which is stored as text in format MMYYYY

I'm trying to sort by a column called date which stores various dates in format MMYYYY (for example, 122020, 102019, etc.).
The SQL query that I have looks like this:
SELECT `date`, `invested` FROM `savings` WHERE `id` = 123 ORDER BY STR_TO_DATE(`date`, "%m%Y") ASC but this query does not sort the output correctly.
Any ideas on how to sort it properly?
Important note: Reclassifying/modifying the column's type is not an option at this point.
EDIT: My current SQL query, which is described above, sorts the dates like this: 102019, 102020, 112019, 112020. But my goal is to have it like this: 102019, 112019, 102020, 112020.
Thank you
Try separating the date string into two parts (year and month), cast each part as integer, and then ordering by that number:
SELECT
date_,
invested
FROM
savings
WHERE
id = 123
ORDER BY
CAST(SUBSTRING(date_, 3, 6) AS UNSIGNED),
CAST(SUBSTRING(date_, 1, 2) AS UNSIGNED)
;
This will do the job :) refer to this DB Fiddle for clarification.

Ordering a mysql table by date when the column is declared varchar

I need to sort a table by date (descending), but all columns in the table are varchar, so I need to manipulate the data on the fly for sorting it correctly.
date sales
10/09/2014 100
13/09/2014 250
30/08/2014 200
Is that possible without altering the table? So the result will be like below, newest dates first?
date sales
13/09/2014 250
10/09/2014 100
30/08/2014 200
Like pseudocode
SELECT * FROM table ORDER BY (CONCAT(REGEXP(date, '[0-9]{4}'),
REGEXP(date, '/[0-9]{2}/'), REGEXP(date, '^[0-9]{4}/')) DESC
I think I need to use substring_index somehow, because regexp just returns 1 or 0, not the actual value found.
You need to convert your varchar-stored date objects into DATE objects, then use them to order.
This you can do on the fly like so
ORDER BY STR_TO_DATE(date,'%d/%m/%Y') DESC
But performance is going to be horrible. For best results store your dates in a DATE column in your table.
you can use STR_TO_DATE
SELECT *
FROM Table1
ORDER BY STR_TO_DATE(date, '%d/%m/%Y') desc,
sales desc

ORDER BY DESC is not working right

I have this sql query
SELECT `price` FROM `used_cars` ORDER BY `price` DESC
So I obviously want to order by price from high to low. However, it seems to be taking the first digit and sorting by that. My theory is that it is treating it like a string, and as the column is a varchar it makes sense. However, this is third party data, so I am stuck with it. How can I order so that the larger numbers come first?
So this is an example of how they are ordered
9698
8999
8988
8900
5983
4988
4984
42441
40949
3995
3995
38995
37685
36999
35983
34990
34785
32999
30594
29999
29999
2862
28000
27995
You should convert the column to a numeric data type. You can do that in the table definition, or in the query itself, for example with:
... ORDER BY `price`+0 DESC
CAST should work:
SELECT CAST(price AS UNSIGNED) AS NumPrice
FROM used_cars
ORDER BY NumPrice DESC
This should work:
(...)
ORDER BY CAST (price AS INT)
This will work but is bad performance
SELECT price FROM used_cars ORDER BY CAST(price AS int) DESC

Order By is a case with ascending and decending orders

I am using MySQL database. I have to make a stored procedure which accepts an integer type parameter. Depending upon the integer's value i have to 'order by' a different value like this..
**if(type == 1) than
order by Date Desc,
Quantity asc,
Amount asc
else if(type == 2)than
order by Date ASc,
Quantity asc,
Amount asc
else if(type == 3)than
order by
Quantity asc
Date desc,
Amount asc
However when i try this i am unable to do this its gives error also.
If you look at the syntax for SELECT, you'll see that the ORDER BY clause can't appear within a CASE statement.
If a column is a numeric type, you can write an expression that is 1 for ascending, -1 for descending and multiply the expression by the column to sort by, though this will impact performance as MySQL won't be able to use any indices for the sort.
SELECT ...
ORDER BY IF(?='d', -1, 1) * value
In general however, you'll have to use different statements to get different orderings.
If Date is a proper date or datetime you can do something like this:
ORDER BY
CASE type WHEN 3 THEN -1 * Date ELSE Date END asc,
Quantity asc, Amount asc
http://dev.mysql.com/doc/refman/5.0/en/case-statement.html
This works because date, time and the other MySQL date and time types are stored internally as integers:
http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html
Well i got the solution finally....
SELECT distinct
order_detail.*, -(1)*CAST(order_detail.Date as unsigned) as lOrderDate,
from order_detail
order by
CASE
WHEN type = 1 THEN lOrderDate
WHEN type = 2 THEN order_detail.Date
WHEN type = 3 THEN order_detail.Quantity
END,
CASE
WHEN type = 1 THEN order_detail.Quantity
WHEN type = 2 THEN order_detail.Quantity
WHEN type = 3 THEN lOrderDate
END,
CASE
WHEN type = 1 THEN order_detail.Amount
WHEN type = 2 THEN order_detail.Amount
WHEN type = 3 THEN order_detail.Amount
END;
Two ways:
Build your query - like a string, then use a prepared statements to execute it.
Use IF-ELSEIF-END IF statement to execute three different SELECT queries.