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?

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();
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.
    – user1822
    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
    – user1822
    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

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.