Date data type in primary key is not working for oracle. Please help me to understand.
CREATE TABLE USER_TABLE1 (
SSN VARCHAR2(10 CHAR) NOT NULL,
DOB DATE NOT NULL,
USER_NAME VARCHAR2(50) NOT NULL,
constraint USER_TABLE1_PK primary key(SSN,DOB)
)
insert into USER_TABLE1 values('SSN1',sysdate,'User1');
select * from USER_TABLE1;
Results:
SSN DOB USER_NAME
SSN1 15-JUL-22 User1
SSN1 15-JUL-22 User1
In Oracle, a DATE
data type is a binary data type consisting of 7 bytes representing: century, year-of-century, month, day, hour, minute and second. It ALWAYS has those components and is not stored in any particular (human-readable) format.
What you are seeing is the client application choosing to display the DATE
in a format that is comprehensible to you, the user, and the implicit conversion it has used to convert the unformatted binary to a formatted string is only displaying the day-month-year components and the time components are not displayed.
If you do:
select ssn,
TO_DATE(dob, 'YYYY-MM-DD HH24:MI:SS') AS dob,
user_name
from USER_TABLE1;
Then you will see the time component and see that the values in the primary key columns are not identical.
What you probably want is to require the time component of the DATE
to always be midnight with a CHECK
constraint:
CREATE TABLE USER_TABLE1 (
SSN VARCHAR2(10 CHAR) NOT NULL,
DOB DATE NOT NULL,
USER_NAME VARCHAR2(50) NOT NULL,
constraint user_table1__dob__chk CHECK (dob = TRUNC(dob)),
constraint USER_TABLE1_PK primary key(SSN,DOB)
);
Then you cannot have DOB
with the same day and different time components.
db<>fiddle here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.