CodeBlanks Logo Icon CodeBlanks

Column and type

Learn column types with Column(Integer), Column(String).

Column and types

Column defines a table column. It takes a type as its first parameter: Integer, String, Float, Boolean, DateTime and so on.

class Product(Base):
    __tablename__ = "products"
    id = Column(Integer, primary_key=True)
    name = Column(String)
    price = Column(Float)
    in_stock = Column(Boolean)

primary_key=True marks a primary key, nullable=False marks a non-null column. A length can be given as in String(50).

Meaning of types

Each column type maps to a corresponding type in the database. Integer stores integers, String stores text, Float stores decimals, Boolean stores true/false.

amount = Column(Integer)      # integer
label = Column(String(50))   # text up to 50 chars
ratio = Column(Float)         # decimal
active = Column(Boolean)      # true/false

Choosing the right type matters for validation and efficiency. A wrong type can cause data loss.

Practice Define a Product model

Start with from sqlalchemy import create_engine, Column, Integer, String, Float and from sqlalchemy.orm import declarative_base. Define Base = declarative_base(). Inside class Product(Base): add __tablename__ = "products". Add columns id = Column(Integer, primary_key=True), name = Column(String) and price = Column(Float). Print the table name with print(Product.__tablename__).

Starter code

main.py
# bring in create_engine, Column, Integer, String, Float from sqlalchemy
# bring in declarative_base
# define Base
# define Product class (derive from Base, set table name to 'products')
# add id, name and price columns
# print Product.__tablename__

Sample solution

main.py
from sqlalchemy import create_engine, Column, Integer, String, Float
from sqlalchemy.orm import declarative_base

Base = declarative_base()

class Product(Base):
    __tablename__ = "products"
    id = Column(Integer, primary_key=True)
    name = Column(String)
    price = Column(Float)

print(Product.__tablename__)

Expected output

products

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does Column(Integer, primary_key=True) specify?

  • An auto-increment column
  • A foreign key column
  • A nullable column
  • A primary key column Correct answer

Explanation: primary_key=True marks the column as a primary key.

2 Complete the String column definition

Question
class Product(Base):
    __tablename__ = "products"
    name = Column(____)
Answer
class Product(Base):
    __tablename__ = "products"
    name = Column(String)

Explanation: Column(String) defines a text column.

3 Match the type concepts

Term Meaning
Integer Stores integers
String Stores text
Float Stores decimals
Boolean Stores true/false

All lessons in Advanced