Make CONSTRAINT with string and integer in SQL - sql

I am a beginner. I created a query on PostgreSQL. I want to make CONSTRAINT with string and integer. It was successfully running but when I insert the data, it gave me an error
CREATE TABLE customer
(
id_customer char(5) PRIMARY KEY NOT NULL,
CONSTRAINT cek_id_customer CHECK ((left(id_customer,2) in ('CU'))
and substring(id_customer,3) LIKE '%[0-9]%'),
nama_customer varchar(30) NOT NULL,
gender_customer varchar(15) NOT NULL,
CONSTRAINT cek_gender_customer CHECK(gender_customer = 'Male' OR gender_customer = 'Female')
);
INSERT INTO customer
VALUES ('CU001', 'Sayaa', 'Male')
The message
ERROR: new row for relation "customer" violates check constraint "cek_id_customer"
DETAIL: Failing row contains (CU001, Sayaa, Male).
SQL state: 23514

To enforce the matching pattern you want you can use a regular expression matching rule in the constraint, like id_customer ~ '^CU[0-9]*$'.
For example:
CREATE TABLE customer (
id_customer char(5) PRIMARY KEY NOT NULL,
CONSTRAINT cek_id_customer CHECK (id_customer ~ '^CU[0-9]*$'),
nama_customer varchar(30) NOT NULL,
gender_customer varchar(15) NOT NULL,
CONSTRAINT cek_gender_customer CHECK(
gender_customer = 'Male' OR
gender_customer = 'Female'
)
);
INSERT INTO customer (id_customer, nama_customer, gender_customer)
VALUES ('CU001', 'Sayaa', 'Male'); -- succeeds
INSERT INTO customer (id_customer, nama_customer, gender_customer)
VALUES ('CU1X', 'Sayaa', 'Male'); -- fails!
See running example at DB Fiddle.

Related

Can we update a record that is defined as a foreign key of a unique record define in a different table?

I am new to PostgreSQL and how i can update the records while they are related with a foreign key definition.
I am getting an error and that would be great if you can guide me with any hints
Let's say we have two different tables like below :
CREATE TABLE IF NOT EXISTS student
(
id_num VARCHAR(40) NOT NULL REFERENCES registered(student_id),
first_name VARCHAR(32) NOT NULL,
last_name VARCHAR(32) NOT NULL,
birthdate DATE NOT NULL,
PRIMARY KEY(id_num)
);
CREATE TABLE IF NOT EXISTS registered
(
student_id VARCHAR(40) NOT NULL UNIQUE,
paid_tuition BOOL NOT NULL,
PRIMARY KEY(paid_tuition)
);
Based on my understating i need to fill the registered table and then try to insert values to the student table that their id match the student_id value in registered table.
But when I try it I get the following error?
Any idea or recommendation?
Message:"update or delete on table "registered" violates foreign key
constraint "student_id_num_id_fkey" on table "student"",
Detail:"Key (id_num)=(idNum-1) is still referenced from table
"student".", Hint:"", Position:0, InternalPosition:0,
InternalQuery:"", Where:"", SchemaName:"", TableName:"student",
ColumnName:"", DataTypeName:"",
ConstraintName:"student_id_num_id_fkey", File:"ri_triggers.c",
Line:2490, Routine:"ri_ReportViolation"}
seems like you are linking tables in opposite direction , to me it makes more sense that "registered" table has been linked to student table by fk studentid .
also in your "student" table definition you are saying that column "id" is primary key while no "id" column has been declared.
so here is what I mean:
CREATE TABLE IF NOT EXISTS student
(
id_num VARCHAR(40) NOT NULL REFERENCES registered(student_id),
first_name VARCHAR(32) NOT NULL,
last_name VARCHAR(32) NOT NULL,
birthdate DATE NOT NULL,
PRIMARY KEY(id_num)
);
CREATE TABLE IF NOT EXISTS registered
(
student_id VARCHAR(40) NOT NULL REFERENCES student(id_num)
paid_tuition BOOL NOT NULL,
PRIMARY KEY(id_num)
);

Creating a audit trigger which update a audit table automatically

My tables are
Book
CREATE TABLE Book
(
Bk_id CHAR(06)NOT NULL,
BK_Name VARCHAR(60)NOT NULL,
Author VARCHAR(30)NOT NULL,
Price NUMERIC(03)NOT NULL,
No_of_copies NUMERIC(02)NOT NULL,
CONSTRAINT Book_PK PRIMARY KEY (Bk_id)
);
Location
CREATE TABLE Location
(
Loc_id CHAR(06)NOT NULL,
Loc_Name VARCHAR(15)NOT NULL,
Stock NUMERIC(02)NOT NULL,
CONSTRAINT Location_PK PRIMARY KEY (Loc_id)
);
Customer
CREATE TABLE Customer
(
Cus_id CHAR(06)NOT NULL,
Cus_Name VARCHAR(25)NOT NULL,
Gender VARCHAR(06)NOT NULL,
TP CHAR(12)NOT NULL,
Address VARCHAR(40)NOT NULL,
CONSTRAINT Customer_PK PRIMARY KEY (Cus_id)
);
Copy
CREATE TABLE Copy
(
Copy_id CHAR(06)NOT NULL,
Bk_id CHAR(06)NOT NULL,
Loc_id CHAR(06)NOT NULL,
Opinion CHAR(02)NOT NULL,
CONSTRAINT pk_Copy PRIMARY KEY (Copy_id),
CONSTRAINT fk_Copy_Bk_id_FK FOREIGN KEY (Bk_id) REFERENCES Book(Bk_id),
CONSTRAINT fk_Copy_Loc_id_FK FOREIGN KEY (Loc_id) REFERENCES Location(Loc_id)
);
Borrow
CREATE TABLE Borrow
(
Cus_evo NUMERIC(02)NOT NULL,
B_Date DATE NOT NULL,
R_Date DATE NOT NULL,
Fee NUMERIC(03)NOT NULL,
Copy_id CHAR(06)NOT NULL,
Cus_id CHAR(06)NOT NULL,
CONSTRAINT pk_Borrow PRIMARY KEY (Cus_id,Copy_id),
CONSTRAINT fk_Borrow_Copy_id_FK FOREIGN KEY (Copy_id) REFERENCES Copy(Copy_id),
CONSTRAINT fk_Borrow_Cus_id_FK FOREIGN KEY (Cus_id) REFERENCES Customer(Cus_id)
);
Audit_Table
Create table Audit_Table
(
Cus_Name VARCHAR(25)NOT NULL,
BK_Name VARCHAR(60)NOT NULL,
B_Date DATE NOT NULL,
Loc_Name VARCHAR(15)NOT NULL,
Cus_evo NUMERIC(02)NOT NULL
);
If a customer gives a zero evaluationCus_evo=0, the details of their Borrowing (Cus_Name from CUSTOMER, the BK_Name from Book, B_Date from Borrow, Loc_Name of the copy from Location and Cus_evo from Borrow) must be placed in an audit table.
The trigger that I created:
CREATE OR REPLACE TRIGGER "AUDIT_TRIGGER"
BEFORE
INSERT OR UPDATE ON Borrow
FOR EACH ROW
WHEN (new.Cus_evo=0)
BEGIN
INSERT INTO Audit_Table
VALUES (:OLD.Cus_Name, :OLD.BK_Name, :OLD.B_Date, :OLD.Loc_Name, :OLD.Cus_evo);
END;
/
I get this error:
Errors: TRIGGER AUDIT_TRIGGER
Line/Col: 3/9 PLS-00049: bad bind variable 'OLD.CUS_NAME'
Line/Col: 3/24 PLS-00049: bad bind variable 'OLD.BK_NAME'
Line/Col: 3/51 PLS-00049: bad bind variable 'OLD.LOC_NAME'
You can not use old and new values from other tables only from table Borrwo when you are creating trigger
You need to specify if you want to check new or old value in WHEN clause
CREATE OR REPLACE TRIGGER "AUDIT_TRIGGER"
BEFORE INSERT OR UPDATE ON Borrow --I have removed double quotes
FOR EACH ROW
WHEN (new.Cus_evo = 0) -- I have added new. before the name of the column
BEGIN
INSERT INTO Audit_Table
VALUES (:OLD.Fee, :OLD.Copy_id, :OLD.Cus_id, :OLD.B_Date, :OLD.Cus_evo);
-- I have replaced column names from other tables with column names
-- from table "Borrow"
END;
/
Here is a demo:
DEMO
In this demo I have removed
CONSTRAINT fk_Borrow_Copy_id_FK FOREIGN KEY (Copy_id) REFERENCES Copy(Copy_id),
from table Borrow spec because it references on the table Copy that we do not have here in your question.
After I have read the comment from #Belayer I have concluded you will need two triggers like this:
CREATE OR REPLACE TRIGGER "AUDIT_TRIGGER"
BEFORE INSERT ON Borrow
FOR EACH ROW
when (new.Cus_evo = 0)
BEGIN
INSERT INTO Audit_Table
VALUES (:new.Copy_id, :new.Copy_id, :new.B_Date, :new.Cus_id, :new.Cus_evo);
END;
/
CREATE OR REPLACE TRIGGER "AUDIT_TRIGGER2"
BEFORE UPDATE ON Borrow
FOR EACH ROW
when (OLD.Cus_evo = 0)
BEGIN
INSERT INTO Audit_Table
VALUES (:OLD.Copy_id, :OLD.Copy_id, :OLD.B_Date, :OLD.Cus_id, :OLD.Cus_evo);
END;
/
Here is a demo with demonstration:
DEMO

Auto fill column when inserting data

I have a question and hope you can help me. How can I auto-fill a column and make sure it has the same value every time I insert the same value in another column? Here is the example:
CREATE TABLE courses(
course_id SERIAL PRIMARY KEY NOT NULL,
course_name varchar(50) NOT NULL
);
CREATE TABLE test(
id SERIAL PRIMARY KEY NOT NULL,
course_id INT NOT NULL,
course_name varchar(50) NOT NULL,
person_name varchar(50) NOT NULL,
FOREIGN KEY(course_id) REFERENCES courses(course_id) ON DELETE CASCADE ON UPDATE CASCADE
);
Imagine I have the 'courses' table with some values, like:
INSERT INTO courses(course_name) VALUES ('Science Computer'),('Engineering'),('English')
What can I do to guarantee that whenever I insert into 'test' a course_id value of '1' it will fill the course_name column with 'Science Computer' and if course_id = 2, course_name will be 'Engineering'? I'm using POSTGRESQL, thanks everyone.

beginner sql missing keyword and invalid identifier

CREATE table Book
(
book_title varchar (100) not null ,
book_genre char(60) not null,
Date_of_publish date not null,
user_code char(7) not null ,
book_id char (7) primary key not null ,
constraint writer__id_fk foreign key (writer_id),
constraint publisher__id_fk foreign key (publisher_id)
);
I'm getting
[ORA-00905: missing keyword]
in publisher table
CREATE table publisher
(
publisher_id char (7) primary key not null,
publisher_name char(20) not null,
publisher_number char(10) not null,
publisher_email varchar2(60) not null,
publisher_address varchar2(60) not null,
);
I'm getting
[ORA-00904: : invalid identifier]
The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders" table is created:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
Refer this link for more details
https://www.w3schools.com/sql/sql_foreignkey.asp
Hope this helps.
Welcome to the wonderful world of SQL! :-)
General remark:
Please tell us what kind of DBMS you're using. MySQL? SQL Server? Oracle? SQlite? Different systems use different kinds of syntaxes.
First statement:
The problem seems to be in the FOREIGN KEY-portion.
Usually, you'll state something like:
CONSTRAINT [constraint_name] FOREIGN KEY([column_in_this_table]) REFERENCES OTHER_TABLE([column_in_other_table])
edit (added):
The [column_in_this_table] has to exist in your DDL (CREATE TABLE-statement), like so:
CREATE TABLE Book ( book_title ... etc., publisher_id INT, CONSTRAINT FK_publ_id FOREIGN KEY(publisher_id) REFERENCES publisher(publisher_id));
Here, you'll have a 'original' column called 'publisher_id', in the 'publisher'-table. You refer to it from within the 'Book'-table, by first having a 'publisher_id' column in the 'Book'-table (which should have the same DDL as the original column by the way). Next, you'll add a FOREIGN KEY to the 'Book'-table, that is imposed on the Book(publisher_id) column. Note, that you could also name the column in your 'Book'-table differently -- like, say, 'Spongebob' or 'Patrick'. But for future use, you'd like naming conventions that tell what you might expect to find in a column. So you'd name columns for what they contain.
Second statement:
The problem is with the last portion of your statement, where there's a comma after the NOT NULL portion for column publisher_address.
(Part of) your statement:
publisher_address varchar2(60) not null, );
Try replacing that with:
publisher_address VARCHAR2(60) NOT NULL);
edit (note to self):
VARCHAR2 turns out to be a valid datatype in Oracle databases (see:
Oracle documentation)
For your first table, the Foreign Keys do not reference any table. For your second table, I would imagine that comma after your last column isn't helping anything.
So this is the answer.
CREATE table Book
(
book_title varchar (100) not null ,
book_genre char(60) not null,
Date_of_publish date not null,
user_code char(7) not null ,
publisher_id char (7) not null,
writer_id char(7) not null,
book_id char (7) primary key not null ,
CONSTRAINT book_writer_id_fk FOREIGN KEY(writer_id) REFERENCES writer(writer_id),
CONSTRAINT book_publisher_id_fk FOREIGN KEY(publisher_id) REFERENCES publisher(publisher_id)
);
CREATE table publisher
(
publisher_id char (7) primary key not null,
publisher_name char(20) not null,
publisher_number char(10) not null,
publisher_email varchar2(60) not null,
publisher_address varchar2(60) not null
);

Creating Table (Oracle)

I am creating two tables. The first table creates with no errors, but when I try to create the SUBHEAD table, I get an error: Line 2, Missing right parenthesis. I am not sure what is wrong with this line. Below is my SQL statements:
CREATE TABLE HEAD
(Code NUMERIC(4,0) NOT NULL PRIMARY KEY,
HeadName VARCHAR(50) NOT NULL UNIQUE,
HType VARCHAR(1) NOT NULL,
HDate DATE NOT NULL,
OpBal DECIMAL(11,2) NOT NULL
);
CREATE TABLE SUBHEAD
(HCode NUMERIC(4,0) NOT NULL FOREIGN KEY REFERENCES HEAD(Code),
SubCode NUMERIC(4,0) NOT NULL,
SubName VARCHAR(50) NOT NULL,
SDate DATE NOT NULL,
OpBal DECIMAL (11,2) NOT NULL,
CONSTRAINT pk_subheadID PRIMARY KEY (HCode, SubCode)
);
syntax: http://docs.oracle.com/cd/B28359_01/server.111/b28286/clauses002.htm#SQLRF52167
note that "in-line" constraint syntax is : "col col_type REFERENCES TAB(COL)" and not "FOREIGN KEY"
The data type for number is NUMBER not NUMERIC
So my memory did not fool me - you can have multiple in-line constraints (although the syntax graph doesn't show it):
SQL> create table tt1(a number primary key);
Table created.
SQL> create table tt2(a number references tt1(a) not null);
Table created.
CREATE TABLE SUBHEAD
(HCode NUMERIC(4,0) NOT NULL, FOREIGN KEY (Hcode) REFERENCES HEAD(Code),
SubCode NUMERIC(4,0) NOT NULL,
SubName VARCHAR(50) NOT NULL,
SDate DATE NOT NULL,
OpBal DECIMAL (11,2) NOT NULL,
CONSTRAINT pk_subheadID PRIMARY KEY (HCode, SubCode)
);
(note comma, and reference to the new table column)