not null default date in postgresql - sql

I want to create a new table that following code below;
create table dwh.dim_produk (
sk_produk serial primary key,
kode_produk varchar(25),
nama_produk varchar(50),
kode_kategori varchar(50),
nama_kategori varchar(50),
date_from date not null default current_timestamp,
date_to date not null default '12/31/9999');
but i get result such as;
SQL Error [22008]: ERROR: date/time field value out of range: "12/31/9999"
Hint: Perhaps you need a different "datestyle" setting.
Position: 253
thank in advance

If you want a date that is "in the future", use infinity
date_from date not null default current_date,
date_to date not null default 'infinity'
Or if you really want a date in the year 9999, use a proper DATE literal formatted using ANSI style:
date_from date not null default current_date,
date_to date not null default DATE '9999-12-31'
Alternatively you can represent a range using the daterange data type:
valid_during daterange not null default daterange(current_date,null)
A null for the upper range means "infinity" as well.

Related

how to create date

how to create date format yyyy-mm with postgresql11
CREATE TABLE public."ASSOL"
(
id integer NOT NULL,
"ind" character(50) ,
"s_R" character(50) ,
"R" character(50) ,
"th" character(50),
"C_O" character(50) ,
"ASSOL" numeric(11,3),
date date,
CONSTRAINT "ASSOL_pkey" PRIMARY KEY (id)
This is a variation of Kaushik's answer.
You should just use the date data type. There is no need to create another type for this. However, I would implement this use a check constraint:
CREATE TABLE public.ASSOL (
id serial primary key,
ind varchar(50) ,
s_R varchar(50) ,
R varchar(50) ,
th varchar(50),
C_O varchar(50) ,
ASSOL numeric(11,3),
yyyymm date,
constraint chk_assol_date check (date = date_trunc('month', date))
);
This only allows you to insert values that are the first day of the month. Other inserts will fail.
Additional notes:
Don't use double quotes when creating tables. You then have to refer to the columns/tables using double quotes, which just clutters queries. Your identifiers should be case-insensitive.
An integer primary key would normally be a serial column.
NOT NULL is redundant for a PRIMARY KEY column.
Use reasonable names for columns. If you want a column to represent a month, then yyyymm is more informative than date.
Postgres stores varchar() and char() in the same way, but for most databases, varchar() is preferred because trailing spaces actually occupy bytes on the data pages.
for year and month you can try like below
SELECT to_char(now(),'YYYY-MM') as year_month
year_month
2019-05
You cannot create a date datatype that stores only the year and month component. There's no such option available at the data type level.
If you want to to truncate the day component to default it to start of month, you may do it. This is as good as having only the month and year component as all the dates will have day = 1 and only the month and year would change as per the time of running insert.
For Eg:
create table t ( id int, col1 text,
"date" date default date_trunc('month',current_date) );
insert into t(id,col1) values ( 1, 'TEXT1');
select * from t
d col1 date
1 TEXT1 2019-05-01
If you do not want to store a default date, simply use the date_trunc('month,date) expression wherever needed, it could either be in group by or in a select query.

SQL: how to specify a date format on creating a table and fill it

I want to save the date in format 'dd.mm.yyyy'. So I read there are different formats for a date in SQL (by the way I use Visual Studio and SQL Server).
I tried this code:
CREATE TABLE APP(
ID INT NOT NULL,
DT DATE FORMAT 'dd.mm.yyyy',
ADDRESS NVARCHAR (100) ,
PRIMARY KEY (ID)
);
But it returns the error:
Incorrect syntax near 'FORMAT'.
After that I want to use this code:
INSERT INTO APP (ID, DT)
VALUES ('1','22.12.2016')
You don't need to specify the format in the table definition as dates are stored in a binary format.
CREATE TABLE APP(
ID INT NOT NULL,
DT DATE,
ADDRESS NVARCHAR (100) ,
PRIMARY KEY (ID)
);
When you try to insert into that table however, the server will try to convert the string to a date before inserting it. This can be problematic as it is unable to tell if 12.11.2017 is the 12th of November or 11th of December. To figure this out it uses the localization settings of the user account that is performing the operation.
Often you will find that the account that is running the operation is set to USA format, month day then year (MDY), when what you want is day month year (DMY) format. One way to tell it what the sequence of the date's parts is to use the DATEFORMAT setting like this:
SET DATEFORMAT dmy;
INSERT INTO APP (ID, DT)
VALUES (1,'22.12.2016')
Another alternative is to cast the string to a date using the CONVERT function and tell it what the date format is. The formats have numeric codes like 104 for German format Like this:
INSERT INTO APP (ID, DT)
VALUES (2,CONVERT(date,'22.12.2016',104))
Dates are stored in an internal format. Formats only make sense for input and output.
In your case you want the date in a German format (104), so you can use:
select convert(varchar(255), dt, 104)
If you like, you can include the formatted date as a separate column:
CREATE TABLE APP (
ID INT NOT NULL,
DT DATE,
ADDRESS NVARCHAR(100),
DT_FORMATTED AS (convert(varchar(255), dt, 104)),
PRIMARY KEY (ID)
);
You can then refer to dt_formatted to get the string in the format you want.
Use this:
CREATE TABLE APP(
ID INT NOT NULL,
DT DATE ,
ADDRESS NVARCHAR (100) ,
PRIMARY KEY (ID)
);
Its default setting is yyyy-MM-dd.
No, it's not. There is no formatting information at all associated with the field.
The value is not formatted by the database. It's returned only as a point in time. Formatting that value into its textual representation is done by the application that is getting the data from the database.
So, there is nothing that you can do in the database to change how the date value is formatted. You have to change that where the data is displayed.
Dates are stored in an internal format.
Formats only make sense for input and output.
You can include the formatted date as a separate column:
SQL Server supports the date format. You have to use the below date format.
With century (yyyy) | Standard | Input/Output
103 | British/French | 103 = dd/mm/yyyy
CREATE TABLE [dbo].[Post]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[Name] VARCHAR(MAX) NULL,
[RowNo] INT NULL,
[ColNo] INT NULL,
[Deadline] (CONVERT(VARCHAR(255), dt, 103)), -- Include the formatted date as a separate column
CONSTRAINT [PK_KtoCo]
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Use this.
CREATE TABLE:
CREATE TABLE EMP
(EID NUMBER(20),
ENAME VARCHAR2(20),
DT DATE,
SAL NUMBER(20));
INSERT INTO THE TABLE:
INSERT INTO EMP (EID,ENAME,DT,SAL) VALUES(01,'ABCDE','11.NOV.2011',10000);
O/P OF ABOVE TABLE:
SELECT * FROM EMP;
EID ENAME DT SAL
01 ABCDE 11-DEC-11 10000

Oracle: Insert default value 0 into timestamp column

Is it possible to insert a default value of 0 into an oracle timestamp(6) column?
I have a column CS_Date_Time defined as Timestamp(6) NOT NULL. In certain cases it is not valid to insert any value to this column. So instead of changing the definition to allow NULL values and leaving this column as NULL in these cases, I was looking for any alternatives.
0 is a number, not a timestamp. You can use a date which is clearly outside your business rule, e.g 0000-01-01 00:00:00 or 1900-01-01 00:00:00 or 2999-12-31 23:59:59
Of course, it should be only one special value over entire application, these values are just examples.
Example:
CREATE TABLE T
(
END_TIME TIMESTAMP(6) DEFAULT TIMESTAMP '9999-12-31 23:59:59' NOT NULL,
...
);

MySQL Syntax for setting Default Date

How can we set element to some default date in mysql ?
In oracle we would do something like
start_date DATE DEFAULT to__date('01011900','DDMMYYYY')
mutation_date_time DATE DEFAULT SYSDATE
CONSTRAINT entity_specification UNIQUE(external_name, start_date_time, end_date_time))
Also do we have any site or resource where we can get MySQL equivalent syntax to Oracle Syntax.
Update
I tried to do as mentioned in answer but again am getting error message:
create table product_offer_type(object_id INT(19), snapshot_id INT(19), PRIMARY KEY(object_id,snapshot_id), enum_value VARCHAR(64) NOT NULL, external_name VARCHAR(64) NOT NULL, description VARCHAR(255), business_validation INT(1), valid_for_start_date_time DATE DEFAULT '1900-01-10', valid_for_end_date_timeDATE DEFAULT '4712-01-01', mutation_date_time DATE DEFAULT 'SYSDATE()', mutation_user VARCHAR(32) DEFAULT 'USER');
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DEFAULT '4712-01-01', mutation_date_time DATE DEFAULT 'SYSDATE()', mutation_user' at line 1
mysql>
Simply pass it a formatted string.
start_date DATE DEFAULT '1900-01-01'
For a fixed default date on a DATE field, the format is 'YYYY-MM-DD', like start_date DATE DEFAULT '2009-10-30'. DATETIME would be 'YYYY-MM-DD HH:MM:SS'.
For a dynamic date based on the current date, you can use DEFAULT CURRENT_TIMESTAMP if you are using a TIMESTAMP field; otherwise, it is not possible to use a function as a DEFAULT in MySQL. TIMESTAMP fields are formatted as 'YYYY-MM-DD HH:MM:SS'. Otherwise, you'd have to get the current date in your code before inserting the data.

updating DATE fields

I inherited MYSQL database that has lots of tables with data like
CREATE TABLE IF NOT EXISTS `ejl_registration` (
`id` int(11) NOT NULL auto_increment,
`team_id` int(11) default NULL,
`start_date` date default NULL,
`end_date` date default NULL,
PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=88668 ;
start_date and end_date should have values like:
2007-1-5, 2007-12-31
2008-1-1, 2008-12-31
2009-1-15,2009-12-31
But some of those en_date fields are either NULL or 0000-00-00.
Is there a ways to have single query to update all those invalid en_date fields and set their value to the end of the year equal to the year of start_date
Try this (please double check, I have not tested the command):
UPDATE `ejl_registration` SET `end_date`= CONCAT(YEAR(`start_date`),'-12-31')
WHERE `end_date` IS NULL OR `end_date` = '0000-00-00';
I don't know if DATEADD and DATEDIFF exist in MySQL, but I would strongly advise using some kind of date function rather than converting to strings and manipulating them that way.
In MS SQL SERVER this would work...
UPDATE
ejl_registration
SET
end_date = DATEADD(YEAR, 1 + DATEDIFF(YEAR, 0, start_date), 0)
WHERE
(end_date) IS NULL OR (end_date = '0000-00-00')