1

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

2

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
7
  • Where should I run this? In psql console? Commented Mar 29, 2019 at 11:05
  • Yes, it's two DDL statements. One to create the trigger function and one to create the trigger. Commented 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 the begin and the end;? Commented Mar 29, 2019 at 11:07
  • @ZulhilmiZainudin: yes Commented Mar 29, 2019 at 11:07
  • I got this error - pastebin.com/raw/Nc7cLXj9 - any idea? Commented Mar 29, 2019 at 11:14

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.