Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Constraint: date A is before date B -- How?

I'm creating an SQL table that needs the fields from=date and to=date but I'd like to make a constraint so that to cannot be before from. My program will check for it but I'd like to learn how to enforce it with SQL. I've written SQL before but never really used constraints and don't know how they work.

So the question is: Using standard SQL, how do I make sure that From is before To?

like image 375
hannson Avatar asked Dec 05 '12 20:12

hannson


1 Answers

create table foo
(
   from_date date,
   to_date date,
   constraint check_dates check (from_date < to_date)
);

Or if you need to apply this to an existing table, use:

alter table foo
   add constraint check_dates check (from_date < to_date);

The PostgreSQL manual contains a good chapter about check constraints: http://www.postgresql.org/docs/current/static/ddl-constraints.html#AEN2410

like image 165
a_horse_with_no_name Avatar answered Oct 06 '22 01:10

a_horse_with_no_name