I have a table in Postgres with the following schema:
create table if not exists cars
(
id bigserial not null,
tyre_code varchar(8)
);
The tyre_code
in the table should ideally not be more than 8 characters in length. But, in the case that someone does provide a string that is greater than 8 characters, is there a way at the table-level schema in Postgres to truncate the value of this string and insert it? The other option I have is to truncate the value in the Java code and then insert it. However, that is not ideal, and would prefer is I can do this at the table level itself.
For example:
tyre_code provided - ABCDEFGHIJK
tyre_code after truncation - ABCDEFGH
I am using Postgres, with Spring and Hibernate. Any help will be greatly appreciated! Thank you!
2
Answers
With your existing table definition OR after adding check constraints for length; If you try to insert column value more than 8 characters;
It shall throw you error as :
But;
You can achieve it using :
BEFORE INSERT trigger
as follows :===============================================================
Also if you are looking for adding constraints to check column length in postgresql; Then you may try : CHECK constraint
Here is a working demo using DBFIDDLE
In more simplified way as :
Here is a working demo
Assuming you already have a table structure as follows :
To add an extra constraint in
alter table
statement.ALTER (EXISTING) TABLE DEMO
Define the column as type
text
(no length limit) with a check constraint that enforces the length. Then use aBEFORE
trigger to truncate the value: