try:
my_conn.execute("CREATE TABLE IF NOT EXISTS my_dt(dt1 text, \
dt2 text,\
CONSTRAINT my_Check CHECK(dt1 <= date('now')))")
my_conn.commit()
print("my_dt Table created successfully")
except sqlite3.Error as my_error:
print("error: ",my_error)
my_conn.commit()
Let us INSERT data to this table
try:
my_conn.execute("INSERT INTO my_dt(dt1,dt2) VALUES \
('2023-08-18','2020-12-13')")
my_conn.commit()
print("Row added successfully")
except sqlite3.Error as my_error:
print("error: ",my_error)
Based on date setting of your system, the output will change if any future date is used then we will get the error message.
error: CHECK constraint failed: my_Check
try:
my_conn.execute("BEGIN")
my_conn.execute("CREATE TABLE IF NOT EXISTS \
my_dt_new(dt1 text, \
dt2 text, \
CONSTRAINT my_Check CHECK(dt1 <= date('now')),\
CONSTRAINT my_check2 CHECK(date(dt2) >= date(dt1)))")
my_conn.execute("INSERT INTO my_dt_new SELECT * FROM my_dt")
my_conn.execute("DROP table my_dt")
my_conn.execute("ALTER TABLE my_dt_new RENAME TO my_dt")
my_conn.commit()
print("Date constraint updated successfully")
except sqlite3.Error as my_error:
print("error: ",my_error)
my_conn.commit()
Let us add some data to check the constraint. Before that we will understand date outputs using 'now'
q="SELECT date('now')"
r_set=my_conn.execute(q)
data_row=r_set.fetchone()
print(data_row[0])
Output is today's date ( based on your system date )
2020-08-19
By changing the query we can get different dates.
q="SELECT date('now','-1 day')" # yesterday date
q="SELECT date('now','1 day')" # Tomorrow date
Using above code we will add date values to our table to check the constraints.
try:
my_conn.execute("INSERT INTO my_dt(dt1,dt2) VALUES \
(date('now','-1 day'),date('now','-2 day'))")
my_conn.commit()
print("Row added successfully")
except sqlite3.Error as my_error:
print("error: ",my_error)
This will generate error ( value for column dt2 is less than dt1 )
error: CHECK constraint failed: my_check2
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.