Constraints and data defaults
You're now going to practice creating a table with some constraints! Often, you'll need to make sure that a column is unique, nullable, a positive value, or related to a column in another table. This is where constraints come in.
As Jason showed you in the video, in addition to constraints, you can also set a default value for the column if no data is passed to it via the default
keyword on the column.
This exercise is part of the course
Introduction to Databases in Python
Exercise instructions
Table
,Column
,String
,Integer
,Float
,Boolean
are already imported fromsqlalchemy
.- Build a new table called data with a unique
name
(String),count
(Integer) defaulted to1
,amount
(Float), andvalid
(Boolean) defaulted toFalse
. - Submit the answer to create the table in the database and to print the table details for
data
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Import Table, Column, String, Integer, Float, Boolean from sqlalchemy
from sqlalchemy import Table, Column, String, Integer, Float, Boolean
# Define a new table with a name, count, amount, and valid column: data
data = Table('data', metadata,
Column('name', String(255), unique=____),
Column('count', Integer(), default=____),
Column('amount', Float()),
Column('valid', Boolean(), default=____)
)
# Use the metadata to create the table
metadata.create_all(engine)
# Print the table details
print(repr(metadata.tables['data']))