ichbinblau
ichbinblau

Reputation: 4809

What is the difference between Varchar and String in sqlalchemy's data type?

I used to use Varchar to text string of dynamical string length. Recently I saw people also use String with length to define it.

What is the difference between them? Which one is better to use?

Upvotes: 15

Views: 57407

Answers (2)

snakecharmerb
snakecharmerb

Reputation: 55629

String is more portable, because it is a generic SQLAlchemy type.

For most backends, a String column definition in the Python layer will be mapped to backend's VARCHAR type, but if the target backend uses some other type then that type will be used.

Thus

col = Column(String(1))

will work on any RDBMS

but

col = Column(VARCHAR(1))

will only work on RDBMS that provide an actual VARCHAR type.

See the documentation for The Type Hierarchy for more discussion.

Upvotes: 5

Mike JS Choi
Mike JS Choi

Reputation: 1151

From what I know,

  • Use varchar if you want to have a length constraint

  • Use string if you don't want to restrict the length of the text

The length field is usually required when the String type is used within a CREATE TABLE statement, as VARCHAR requires a length on most databases

Parameters

length - optional, a length for the column for use in DDL and CAST expressions. May be safely omitted if no CREATE TABLE will be issued. Certain databases may require a length for use in DDL, and will raise an exception when the CREATE TABLE DDL is issued if a VARCHAR with no length is included. Whether the value is interpreted as bytes or characters is database specific.

SQLAlchemy Docs

Upvotes: 12

Related Questions