Sqlalchemy Primary Key Auto Generate

Learn how to define an auto increment primary key in PostgreSQL. Get instructions on learning how to use the serial data type nd how to use a custom sequence.

  • SQLAlchemy Tutorial
  • SQLAlchemy Core
  • SQLAlchemy ORM
  • SQLAlchemy Useful Resources
  • Selected Reading

Let us now discuss how to use the create table function.

The SQL Expression Language constructs its expressions against table columns. SQLAlchemy Column object represents a column in a database table which is in turn represented by a Tableobject. Metadata contains definitions of tables and associated objects such as index, view, triggers, etc.

Hence an object of MetaData class from SQLAlchemy Metadata is a collection of Table objects and their associated schema constructs. It holds a collection of Table objects as well as an optional binding to an Engine or Connection.

Constructor of MetaData class can have bind and schema parameters which are by default None.

Next, we define our tables all within above metadata catalog, using the Table construct, which resembles regular SQL CREATE TABLE statement.

Key

An object of Table class represents corresponding table in a database. The constructor takes the following parameters −

NameName of the table
MetadataMetaData object that will hold this table
Column(s)One or more objects of column class

Column object represents a column in a database table. Constructor takes name, type and other parameters such as primary_key, autoincrement and other constraints.

SQLAlchemy matches Python data to the best possible generic column data types defined in it. Some of the generic data types are −

  • BigInteger
  • Boolean
  • Date
  • DateTime
  • Float
  • Integer
  • Numeric
  • SmallInteger
  • String
  • Text
  • Time

To create a students table in college database, use the following snippet −

The create_all() function uses the engine object to create all the defined table objects and stores the information in metadata.

Sqlalchemy Primary Key Auto Increment

Complete code is given below which will create a SQLite database college.db with a students table in it.

Sqlalchemy Primary Key Auto Generate Key

Because echo attribute of create_engine() function is set to True, the console will display the actual SQL query for table creation as follows −

Primary Key Definition

The college.db will be created in current working directory. To check if the students table is created, you can open the database using any SQLite GUI tool such as SQLiteStudio.

Super Key

The below image shows the students table that is created in the database −