Repository navigation
How to define unique constraint in table columns #82
Description
Activity
- addedquestionFurther information is requestedFurther information is requested
on Sep 7, 2021 see #65 - it has the how to do it.
Basically you specify something like -
email: EmailStr = Field(sa_column=Column("email", VARCHAR, unique=True)) the = Field(sa_column=Column("username", VARCHAR, unique=True))Reacted by Andrea Guzzo, Stan Zubov, Arjun Umathanu, Kyei Samuel Osei, cworkschris, Manoj Kumar A and Matthieu LAURENTsee #65 - it has the how to do it.
Basically you specify something like -
email: EmailStr = Field(sa_column=Column("email", VARCHAR, unique=True)) the = Field(sa_column=Column("username", VARCHAR, unique=True))Thanks very much for your help, @obassett! Nevertheless, i have opened a Pull Request to use Unique constraint directly by the sqlmodel whithout using sa_column param.
PR: #83Reacted by Avi Perl, Stan Zubov, Arjun Umathanu, cworkschris, Cal Jacobson, Frank Zhang, Alex Kosh, kryptex and Matthieu LAURENTI had the same question, so just for documentation I put my complete example :)
Hope that can help someone.
So I had to define a list of product with an integer primary key id and a unique name for the products.
The class: BaseProduct is the default definition of the Product.
The class: Product is the DB model.The file
Product.pywith theBaseProductdefinition isfrom sqlmodel import SQLModel class ProductBase(SQLModel): name: str description: str price: float available: bool
The file:
product.pywith the definition ofProductisfrom typing import Optional from sqlalchemy import String from sqlalchemy.sql.schema import Column from sqlmodel import Field from app.src.schemas.entities import ProductBase class Product(ProductBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) # name is unique name: str = Field(sa_column=Column("name", String, unique=True))
Of course the relationship with ProductType and ProductTagLink are defined in another files and schemas :)
Hope this example helps :)
Reacted by cworkschris, Wouter Theune, guoyang521, Eloy Adonis Colell, Matthieu LAURENT and MichaelFound a solution that I think is more elegant using table_args
from typing import Optional from sqlmodel import Field, SQLModel, UniqueConstraint class users(SQLModel, table=True): __table_args__ = (UniqueConstraint("external_id"),) id: Optional[int] = Field(default=None, primary_key=True) email: strReacted by cworkschris, shifqu, Zaffer, Alex Kosh, Lyla Fischer, Alex Rogozhnikov, Alan Vazquez, Peter Dudfield, Matthieu LAURENT, m0wer and 1 moreWhy not simply add
sa_column_kwargs={"unique": True}toField()?Reacted by shifqu, Eduardo Côrtes, Wouter Theune, soonoo, 艾幻翔, Coding-Crashkurse, Thomas Dijkstra, Alex Kosh, Philipp Dowling, Ben Mares and 12 moreReacted by BrandonReacted by Ryan and Matthieu LAURENT@StefnirKristjansson not sure that the usage of
table_argsis more elegant, but it is certainly what I was looking for. This way you can define an actualUniqueConstraintthat spans multiple fields (or columns, whichever terminology you prefer).@sgraaf 's solution feels the most elegant one for single field constraints.
edit: However, both my statements are pure personal preference, no solid grounds on why they would be more or less elegant :)
Reacted by Stefnir, ChouUn and Matthieu LAURENT@sgraaf : Thank you, that works fine! Where is that "trick" documented?
@Data-Mastery Honestly?... Nowhere! I had to dive (deep) into the source code of SQLModel to find it.
While the docs are really good in some aspects (very heavy on examples / guides / tutorials), the lack of a comprehensive API reference is very unfortunate.
Reacted by aguydane, Arjun Umathanu, MichadeGroot, Saeejith Nair, David Dávila Vilanova, Matthieu LAURENT, Dmytro Kovalchuk and charlie-corusThis isn't documented as it is a feature from SQLAlchemy, but you can define unique constraints at the model level using "table_args".
from sqlmodel import SQLModel, Field from sqlalchemy import UniqueConstraint class Employee(SQLModel, table=True): """Employee Model""" __table_args__ = (UniqueConstraint("employee_id"),) employee_id: int = Field( title="Employee ID", ) firstname: str = Field( title="First Name", ) lastname: str = Field( title="Last Name", )So the above code would add a constraint to prevent duplicate entries in "employee_id".
I've only tested this on a PostgreSQL database, but it should work fine for others.
The benefit of doing it this way is you avoid having to override the column definition at the field level.
https://docs.sqlalchemy.org/en/14/orm/declarative_tables.html
Reacted by Hyeongseok Won and Matthieu LAURENTIt looks like the Field column now supports the unique=True/False keyword argument? Merged in #83
I was able to successfully use
code: str = Field(index=True, unique=True)and it generated aCREATE UNIQUE INDEX IF NOT EXISTS ix_venue_code ...in the output schemaReacted by Jonathan Vargas, Brandon, Matthieu LAURENT, mshenchao and NourEldin Osamaraphaelgibson commented
on Jan 28, 2023 on Jan 28, 2023 · Hidden as resolvedAuthorshow commentMore actionsraphaelgibson commented
on Oct 3, 2023 on Oct 3, 2023 · Hidden as resolvedAuthorshow commentMore actionsraffaelemancuso commented
on Jun 2, 2025 on Jun 2, 2025 · Hidden as resolvedshow commentMore actionsNow
Field(unique=True)works thanks to @raphaelgibson.But I think it would be nice to document the way how to create unique constraints including unique constraints on multiple columns
- added a commit that references this issue
on Mar 6, 2026 - locked and limited conversation to collaborators
on May 18, 2026
First Check
Commit to Help
Example Code
Description
Hi, guys!
I want to define something like:
email: str = Field(unique=True)But Field does not have unique param, like SQLAlchemy Column have:
Column(unique=True)I've searched in Docs, Google and GitHub, but I found nothing about unique constraint.
Thanks for your attention!
Operating System
Windows
Operating System Details
No response
SQLModel Version
0.0.4
Python Version
3.9.4
Additional Context
No response