Sql order by date doesn't work in sqlite - sql

I have this syntax SQL below:
SELECT * FROM products_validity WHERE type = 'milk' order by date sac
My row called 'date' is 'DATETIME' and records that are saved within this line follow this format:
day / month / year
And I'm having a problem, in my case he is adjusting according to the 'day', instead of doing a complete analysis of data, eg:
09/09/1234
10/10/2016
20/09/2014
23/08/2014
How to fix this error, causing the sql can order the correct way?
EDIT
My Table is in this format:
CREATE TABLE IF NOT EXISTS products_validity
(ID INTEGER PRIMARY KEY AUTOINCREMENT,
product VARCHAR,
type VARCHAR,
date DATETIME,
desc VARCHAR,
show VARCHER

Related

SQL Server - Looking for a way to shorten code

I'm basically very new to SQL Server, so please bare with me. Here is my problem:
I have a table with (let's say) 10 columns and 80k rows. I have 1 column called Date in the format of YYYY-MM-DD type varchar(50) (can't convert it to date or datetime type I tried, the initial source of data is not good).
**Example :
Table [dbo].[TestDates]
Code
SellDate
XS4158
2019-11-26
DE7845
2020-02-06
What I need to do is to turn the YYYY-MM-DD format to DD/MM/YYYY format. After a lot of tries (I tried the functions (DATE_FORMAT, CONVERT, TO_DATE etc) and this is solution :
1- I added a primary key for join purpose later (ID)
2- I split my date column in 3 columns in a whole new table
3- I merged the 3 columns in the order I need with the delimiter of my choice (/) in the same new table
4- I copied the good column to my initial table using the primary key ID I created before
alter table [dbo].[TestDates]
add ID int not null IDENTITY primary key;
SELECT ID,
FORMAT(DATEPART(month, [SellDate]),'00') AS Month,
FORMAT(DATEPART(day, [SellDate]),'00') AS Day,
FORMAT(DATEPART(year, [SellDate]),'0000') AS Year
INTO [dbo].[TestDates_SPLIT]
FROM [dbo].[TestDates]
GO
ALTER TABLE [dbo].[TestDates_SPLIT]
ADD SellDate_OK varchar(50)
UPDATE [dbo].[TestDates_SPLIT]
SET SellDate_OK = [Day] + '/' + [Month] + '/' + [Year]
ALTER TABLE [dbo].[TestDates_SPLIT]
DROP COLUMN Month, Day, Year
ALTER TABLE [dbo].[TestDates]
ADD SellDate_GOOD varchar(50)
UPDATE [dbo].[TestDates]
SET [TestDates].SellDate_GOOD = [TestDates_SPLIT].SellDate_OK
FROM [dbo].[TestDates]
INNER JOIN [dbo].[TestDates_SPLIT]
ON [TestDates].ID = [TestDates_SPLIT].ID
This code works but i find too heavy and long, considering I have 6 more dates columns to work on. Is there a way to make it shorter or more efficient? Maybe with SET SellDate = SELECT (some query of sorts that doesn't require to create and delete table)
Thank you for your help
I tried the usual SQL functions but since my column is a varchar type, the converting was impossible
You should not be storing dates as text. But, that being said, we can try doing a rountrip conversion from text YYYY-MM-DD to date to text DD/MM/YYYY:
WITH cte AS (
SELECT '2022-11-08' AS dt
)
SELECT dt, -- 2022-11-08
CONVERT(varchar(10), CONVERT(datetime, dt, 121), 103) -- 08/11/2022
FROM cte;
Demo

SQL Computed Column , Coallesce , Two DateTime Fields , Index

I have in my database following two Columns :
Delivery_Date (DateTime)
Delivery_Override (DateTime)
( I must preserve the Original Delivery Date for other things I do )
I created following Computed Column
Delivery_Packdate
formula : (coalesce(nullif([Delivery_Override],''),[Delivery_Date]))
and now I can do a select like this :
select * from Deliveries where Delivery_PackDate = '2019-09-24'
and this automatically selects the Overriden Date if filled or else the original date.
the Problem is I would like to index this , but SQL will not allow this because it is non-deterministic .
I suppose I am doing something wrong here , how can I solve this correctly ? Any tips?
Thank you.
The problem is that you are converting to a string. The following works fine:
create table t (
Delivery_Override datetime,
Delivery_Date datetime
);
alter table t add dt as (coalesce(Delivery_Override, Delivery_Date)) persisted;
create index idx_t_dt on t(dt);
Here is a db<>fiddle.
There is no such thing as a date/time with the value ''.

Insert current date time in a column of and keep it constant

i am using sql server in making my project with javafx. Their i have a table of purchase and sale. One of the column of both of them is date having current date and time to store them as a record that this transaction has been saved in this time.
Now i am using the that date column with varchar datatype and have using computed column specification with following function:
(CONVERT([varchar](25),getdate(),(120)))
but when i select records from that table using query
SELECT pr.Date, p.Name, pr.Quantity, s.Name, p.Pur_Price
FROM (([Product] AS p
INNER JOIN [Purchase] AS pr ON pr.Product_id=p.Product_id)
INNER JOIN [Supplier] AS s ON s.Supplier_Id=p.Supplier_Id)
WHERE pr.Date>= dateadd(dd, 0, datediff(dd, 0, getdate()-30))
but it selects all the records keeping all date records to current date and time. Thanks in advance.
Looking forward for your good replies.
The problem is that your Date column is computed on the fly and not actually stored in the table. So each time you SELECT from that table, the expression of the computed column is calculated (CONVERT([varchar](25),getdate(),(120))) thus resulting in the same value for all rows.
A fix would be using a PERSISTED computed column so that values are actually stored with the table when inserting or updating:
CREATE TABLE Product (
OtherColumns INT,
[Date] AS (CONVERT([varchar](25), getdate(), 120)) PERSISTED)
The problem with this is that non-deterministic expressions can't be persisted, as this error message pops up:
Msg 4936, Level 16, State 1, Line 1 Computed column 'Date' in table
'Product' cannot be persisted because the column is non-deterministic.
You have several other options for this. Please use DATE or DATETIME columns to store and handle dates and avoid using VARCHAR for this as it brings many problems. The following examples use DATETIME:
Use a DEFAULT constraint linked to the column with the expression you want:
CREATE TABLE Product (
OtherColumns INT,
[Date] DATETIME DEFAULT GETDATE())
INSERT INTO Product (
OtherColumns) -- Skip the Date column on the INSERT
VALUES
(1)
SELECT * FROM Product
OtherColumns Date
1 2018-12-14 08:49:08.347
INSERT INTO Product (
OtherColumns,
Date)
VALUES
(2,
DEFAULT) -- Or use the keyword DEFAULT to use the default value
SELECT * FROM Product
OtherColumns Date
1 2018-12-14 08:49:08.347
2 2018-12-14 08:50:10.070
Use a trigger to set the value. This will override any inserted or updated value that the original operation set (as it will execute after the operation, as stated in it's definition).
CREATE TRIGGER utrProductSetDate ON Product
AFTER INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON
UPDATE P SET
Date = GETDATE()
FROM
inserted AS I
INNER JOIN Product AS P ON I.OtherColumns = P.OtherColumns -- Assuming PK or Unique columns join
END
Thanks all of you. But i solved my problem by putting my date Column of that table into datetime data type and i my query i have entered the date using getdate() method. It worked for me to save current date and time in my purchase and sale table.

Oracle 12c - how to set 'date' column with year quarter?

I have a need to create a column in Oracle 12c that will be date column with values:
20163
20164
20171
20172
20173
20174
...
How to specify that for a column in a create table statement?
thanks.
You can model the column as containing dates, constrained to fall only on the first moment of each quarter.
CREATE TABLE TEMP
( QUARTER DATE
CONSTRAINT IS_QUARTER CHECK ( (QUARTER = TRUNC(QUARTER, 'Q') ) )
)
To put values into the table, you need to set the date to the start of the quarter:
INSERT INTO temp VALUES ( TO_DATE('2017-04', 'yyyy-mm') );
To read values from the table, you can format as you like:
SELECT TO_CHAR( quarter, 'YYYYQ') FROM temp;
Because the underlying column is a date, you can do things like compare it with other dates, etc.
SELECT TO_CHAR( ADD_MONTHS( quarter, 3 ), 'YYYYQ') FROM temp;
Joe!
Such fields as you described are frequently using for monthly periods.
Typicaly they are encoded in integer datatypes.
If you were not on Oracle, Int32 would be perfect.
In Oracle the decision is not so clear.
I would prefer NUMBER(6,0) and simple constraint that field most be less than any possible date in future.
CHAR(6) - is fine too but constraints will be more complex.

Alter column data type in Hive

we need to alter the table column data type from string to date. While am trying to do am getting the below error. Could you please help.
hive> describe sales_staging;
OK
cust_id string prod_num string
qty int sale_date string
sale_id string
Time taken: 0.151 seconds,
Fetched: 5 row(s)
hive> alter table sales_staging CHANGE sale_date sale_date DATE ;
FAILED: Execution Error, return code 1 from
org.apache.hadoop.hive.ql.exec.DDLTask. Unable to alter table. The
following columns have types incompatible with the existing columns in
their respective positions :sale_date
hive>
You can't give same name to column you wish to change datatype of. use like this
ALTER TABLE sales_staging CHANGE sale_date sale_date_new DATE;
refer this Apache Hive Wiki
you can't change the existing string type data to date type. but we can able to solve this issues in 2 ways.
create another table with the same columns count but the data type is date where the column you need string to date, then use insert command to export old table data to new table by casting the string to date.
add a new column to existing table with datatype as date. overwrite the table itself by casting the string to date into the new column.
ex:
I have orders table
describe orders;
order_id int
order_date string
order_customer_id int
order_status string
created another table ordersnew
describe ordersnew;
id int
odate date
cid int
ostatus string
now exported the orders data to ordersnew table
insert into ordersnew select order_id,cast(from_unixtime(unix_timestamp(substring(order_date,1,19), 'yyyy-MM-dd HH:mm:ss')) as timestamp) as strdate, order_customer_id,order_status from orders;
substring(order_date,1,19), 'yyyy-MM-dd HH:mm:ss' this is the place you have to check and alter your query as per your data.
please check here for date conversions
Do the following steps:
step-1) check all the dates in field "sale_date" are valid dates or not. If yes then go to step-2
step-2) Check the date format, for DATE datatype format should be 'yyyy-MM-dd'. If the date format is 'yyyy-MM-dd HH:mm:ss' then you should try the following syntax:
alter table sales_staging CHANGE sale_date sale_date TIMESTAMP;