I'm making a sqlite3 database for my bank management program. To create tables I used the following script.
1 CREATE TABLE account_profile(
2 account_id INTEGER PRIMARY KEY,
3 first_name TEXT NOT NULL,
4 last_name TEXT NOT NULL,
5 date_of_birth TEXT NOT NULL,
6 phone TEXT UNIQUE NOT NULL,
7 email TEXT UNIQUE NOT NULL
8 );
9
10 CREATE TABLE balance(
11 account_id INTEGER PRIMARY KEY,
12 balance REAL DEFAULT 0,
13 FOREIGN KEY (account_id)
14 REFERENCES account_profile (account_id)
15 ON UPDATE CASCADE
16 ON DELETE CASCADE
17 );
Now by using an insert command like below
INSERT INTO account_profile(first_name, last_name, something...) values (something...);
I want that a row is created in the balance table with the account_id 1.
Is it possible? If so, how should I modify the first codes block?
You need an AFTER INSERT trigger
:
CREATE TRIGGER ins_balance AFTER INSERT ON account_profile
BEGIN
INSERT INTO balance(account_id) VALUES (NEW.account_id);
END;
But, since there is a 1:1
relationship between the 2 tables and the only column in the table balance
, except the foreign key, is balance
, why do you need another table?
You can have the column balance
inside account_profile
:
CREATE TABLE account_profile(
account_id INTEGER PRIMARY KEY,
first_name TEXT NOT NULL,
last_name TEXT NOT NULL,
date_of_birth TEXT NOT NULL,
phone TEXT UNIQUE NOT NULL,
email TEXT UNIQUE NOT NULL,
balance REAL DEFAULT 0
);
and there is no need to create a trigger and you avoid the overhead of cascaded updates, cascaded deletes and calls to a trigger.
Thank you for your reply! This solution worked well. Your suggestion is valid, but I wanted to know if such a triggering is possible and how to do that.