2

I'm using Prisma as my ORM and PostgreSQL as my database, so this question applies both to Prisma and Postgres, and I have the following prisma schema:


model Employee {
  id                          String  @id                                     @default(uuid())
  registrationNumber          String  @db.VarChar @map("registration_number") @unique
  fullName                    String  @db.VarChar @map("full_name")
  username                    String? @db.VarChar @map("username")
  email                       String? @db.VarChar @map("email")
  isSapUser                   Boolean @db.Boolean @map("is_sap_user")         @default(false)

  @@map("employee")
}

My question is: Should I set a size to my varchar, like @db.VarChar(20)? If I do set a size, does the database allocate more space? If I don't, does the database uses only what each field occupies?

RinnieR
  • 209
  • 5
  • 15
  • For me there's no need to size varchar. See this post [https://stackoverflow.com/questions/4848964/difference-between-text-and-varchar-character-varying](https://stackoverflow.com/questions/4848964/difference-between-text-and-varchar-character-varying) – Philippe Mar 08 '22 at 14:10

1 Answers1

4

Don't specify a length maximum for database columns unless it is required by the application or you want to create a B-tree index on the column.

The performance will be the same, and PostgreSQL only allocates the space that is actually occupied by the data.

Here is what the documentation has to say about text, character varying and character:

There is no performance difference among these three types, apart from increased storage space when using the blank-padded type, and a few extra CPU cycles to check the length when storing into a length-constrained column. While character(n) has performance advantages in some other database systems, there is no such advantage in PostgreSQL; in fact character(n) is usually the slowest of the three because of its additional storage costs. In most situations text or character varying should be used instead.

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263