I have this table.
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name TEXT
);
I'm looking for a way to enforce lowercase for the name
values.
For example, when I save a record using this command:
INSERT INTO users (name) VALUES ('JOHN');
or:
INSERT INTO users (name) VALUES ('John');
I want it to be saved as john
without converting the case beforehand using my programming language i.e. JavaScript, Ruby and etc.
Is it possible to make use of LOWER()
function inside this CREATE TABLE
command?
asked Mar 29, 2019 at 10:57
1 Answer 1
You need a trigger for that:
create function make_lower_name()
returns trigger
as
$$
begin
new.name := lower(new.name);
return new;
end;
$$
language plpgsql;
create trigger ensure_lower_name_trg
before update or insert on users
for each row
execute procedure make_lower_name();
answered Mar 29, 2019 at 11:04
user1822user1822
-
Where should I run this? In
psql
console?Zulhilmi Zainudin– Zulhilmi Zainudin2019年03月29日 11:05:30 +00:00Commented Mar 29, 2019 at 11:05 -
Yes, it's two DDL statements. One to create the trigger function and one to create the trigger.user1822– user18222019年03月29日 11:06:04 +00:00Commented Mar 29, 2019 at 11:06
-
What if I want to apply this for many columns? Do I just need to add
new.xxx := lower(new.xxx);
between thebegin
and theend;
?Zulhilmi Zainudin– Zulhilmi Zainudin2019年03月29日 11:07:34 +00:00Commented Mar 29, 2019 at 11:07 -
@ZulhilmiZainudin: yesuser1822– user18222019年03月29日 11:07:48 +00:00Commented Mar 29, 2019 at 11:07
-
I got this error - pastebin.com/raw/Nc7cLXj9 - any idea?Zulhilmi Zainudin– Zulhilmi Zainudin2019年03月29日 11:14:00 +00:00Commented Mar 29, 2019 at 11:14
lang-sql