Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 581
ichbinblau Avatar asked Jan 28 '26 01:01

ichbinblau


2 Answers

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

like image 121
Mike JS Choi Avatar answered Jan 29 '26 14:01

Mike JS Choi


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.

like image 37
snakecharmerb Avatar answered Jan 29 '26 14:01

snakecharmerb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!