How would you create a rule in postgres to force lowercase on X column on insert. EG When inserting:
INSERT INTO foobar (foo, bar) VALUES ('EXAMPLE', 2);
I would want EXAMPLE
to be lowercased to example
before persisting.
In PostgreSQL, the UPPER function is used to convert a string into upper case. Like the LOWER function, the UPPER function accepts a string expression or string-convertible expression and converts it to an upper case format.
Introduction to PostgreSQL CREATE TRIGGER statement First, specify the name of the trigger after the TRIGGER keywords. Second, specify the timing that cause the trigger to fire. It can be BEFORE or AFTER an event occurs. Third, specify the event that invokes the trigger.
A trigger function is created with the CREATE FUNCTION command, declaring it as a function with no arguments and a return type of trigger (for data change triggers) or event_trigger (for database event triggers).
An INSTEAD OF trigger is a trigger that allows you to skip an INSERT , DELETE , or UPDATE statement to a table or a view and execute other statements defined in the trigger instead. The actual insert, delete, or update operation does not occur at all.
This solution has been tested and is working in Postgres 9.1
I used triggers to solve problem.
Here's the full code so you can paste into postgres and try it out yourself & explanation of how it works below
DROP TABLE foobar;
CREATE TABLE foobar (
foo text,
bar int
);
CREATE OR REPLACE FUNCTION lowecase_foo_on_insert() RETURNS trigger AS $lowecase_foo_on_insert$
BEGIN
NEW.foo = LOWER(NEW.foo);
RETURN NEW;
END;
$lowecase_foo_on_insert$ LANGUAGE plpgsql;
CREATE TRIGGER lowecase_foo_on_insert_trigger BEFORE INSERT OR UPDATE ON foobar
FOR EACH ROW EXECUTE PROCEDURE lowecase_foo_on_insert();
INSERT INTO foobar (foo, bar) VALUES ('LOWERCASE ME', 1);
SELECT * FROM foobar; //result 'lowercase me'
Create our demo table:
CREATE TABLE foobar (
foo text,
bar int
);
Create function that converts (foo) to lowercase:
CREATE OR REPLACE FUNCTION lowecase_foo_on_insert() RETURNS trigger AS $lowecase_foo_on_insert$
BEGIN
NEW.foo = LOWER(NEW.foo);
RETURN NEW;
END;
$lowecase_foo_on_insert$ LANGUAGE plpgsql;
Create a trigger that executes code to lowercase foo before insert:
CREATE TRIGGER lowecase_foo_on_insert_trigger BEFORE INSERT OR UPDATE ON foobar
FOR EACH ROW EXECUTE PROCEDURE lowecase_foo_on_insert();
And now to test our work:
INSERT INTO foobar (foo, bar) VALUES ('LOWERCASE ME', 1);
SELECT * FROM foobar;
Result is that the only row in column foo is now set to 'lowercase me'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With