简体   繁体   中英

How to compare the date in SQL

I'm new comer in Database, and I knew some of people had already ask this question before, but mine is a little tricky. Here it is, suppose we have table named Employee like this:

Create table People(
ID char(10) PK,
SSN char(15) Not Null,
First_Name char(15),
Last_Name char(15),
Birth_Day date NOT NULL
);

And we do some insertions like:

INSERT INTO People VALUES('0000000001','078-05-1120','George','Brooks', '24-may-85');
INSERT INTO People VALUES('0000000002','917-34-6302','David','Adams', '01-apr-63');
INSERT INTO People VALUES('0000000003','078-05-1123','Yiling','Zhang', '02-feb-66');
INSERT INTO People VALUES('0000000004','078-05-1130','David','Gajos', '10-feb-65');
INSERT INTO People VALUES('0000000005','079-04-1120','Steven','Cox', '11-feb-79');
INSERT INTO People VALUES('0000000006','378-35-1108','Eddie','Gortler', '30-may-76');
INSERT INTO People VALUES('0000000007','278-05-1120','Henry','Kung', '22-may-81');

So my question is how would I find the peoples who are born before ex: January 1st, 1980. I wanna simlply use < or > opeator, but it cannot work in this case

SELECT ID,SSN, First_Name, Last_Name, Birth_Day
FROM People
WHERE Birth_Day < '01-jan-80';

Anyone could help ?

You are using a date string and relying on implicit conversion for comparing it with date type.

Use DATE literals or TO_DATE function instead.

SELECT ID,SSN, First_Name, Last_Name, Birth_Day
FROM People
WHERE Birth_Day < DATE '1980-01-01'

SELECT ID,SSN, First_Name, Last_Name, Birth_Day
FROM People
WHERE Birth_Day < TO_DATE('01-jan-1980','dd-mon-yyyy');

Try this with to_date :

--this is only for testing
with brth as (
select to_date('24-may-85') as Birth from dual
union
select to_date('24-jan-79') as Birth from dual

) 
-- actual solution
select * from brth where BIRTH < to_date('01-JAN-80')

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM