How to use CONSTRAINT CHECK in SQLDEVELOPER on a specific DATE? - oracle

I'm trying to set a CONSTRAINT on column Nr_AnoLetivo which is a DATE, which only can be NOT NULL AND greater than the year 2000.
I've been trying this:
CREATE TABLE Classe(
Cd_Classe NUMBER(8),
Nr_AnoLetivo NUMBER(4) CONSTRAINT CLASSE_NR_ANOLETIVO_NN NOT NULL,
Cd_Escola NUMBER(5),
Cd_Grau NUMBER(2),
Nr_Serie NUMBER(2) CONSTRAINT CLASSE_NR_SERIE_NN NOT NULL,
Sg_Turma VARCHAR2(2) CONSTRAINT CLASSE_SG_TURMA_NN NOT NULL,
Cd_Periodo NUMBER(2),
CONSTRAINT CLASSE_CD_CLASSE_PK PRIMARY KEY (CD_CLASSE),
CONSTRAINT CLASSE_NR_ANOLETIVO_CK CHECK (NR_ANOLETIVO IN DATE ('2000/01/01')),
CONSTRAINT ESCOLA_CD_ESCOLA_FK FOREIGN KEY (CD_ESCOLA) REFERENCES Escola (CD_ESCOLA),
CONSTRAINT GRAU_CD_GRAU_FK FOREIGN KEY (CD_GRAU) REFERENCES Grau (CD_GRAU),
CONSTRAINT PERIODO_CD_PERIODO_FK FOREIGN KEY (CD_PERIODO) REFERENCES Periodo (CD_PERIODO)
);
And the Error message is:
00000 - "missing expression"
Something tells me this error is generated by the DATE row and I don't get it why.
Can anyone tell why is this happening?

You got it wrong.
If you declared NR_ANOLETIVO column as NUMBER(4), it seems that you expect year only in that column (such as 1957, 1998, 2010, etc.), not the whole date (such as 16.09.2018 (dd.mm.yyyy)).
Therefore, setting a constraint to check some date value is wrong - you should check that value you put into that column is larger than 2000. Something like this (your code, simplified):
SQL> create table classe
2 (cd_classe number(8) constraint pk_cla primary key,
3 --
4 nr_anoletivo number(4) constraint ch_nra_2k check (nr_anoletivo > 2000)
5 not null,
6 --
7 cd_grau number(2));
Table created.
SQL> insert into classe (cd_classe, nr_anoletivo, cd_grau) values (1, 1990, 23);
insert into classe (cd_classe, nr_anoletivo, cd_grau) values (1, 1990, 23)
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CH_NRA_2K) violated
SQL> insert into classe (cd_classe, nr_anoletivo, cd_grau) values (2, 2018, 33);
1 row created.
SQL>
If you really meant to check the full date, then you should modify datatype column (to DATE), as well as the constraint:
SQL> create table classe
2 (cd_classe number(8) constraint pk_cla primary key,
3 --
4 nr_anoletivo date constraint ch_nra_2k check (nr_anoletivo > date '2000-01-01')
5 not null,
6 --
7 cd_grau number(2));
Table created.
SQL> insert into classe (cd_classe, nr_anoletivo, cd_grau) values (1, date '1990-12-25', 23);
insert into classe (cd_classe, nr_anoletivo, cd_grau) values (1, date '1990-12-25', 23)
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CH_NRA_2K) violated
SQL> insert into classe (cd_classe, nr_anoletivo, cd_grau) values (2, date '2018-09-16', 33);
1 row created.
SQL>

Related

How do I create a foreign key on two columns that are under the primary key constraint?

CREATE TABLE "RESEARCH_DEP"."RESEARCH_TV_COMPANY"
( "CID" NUMBER(38,0) NOT NULL ENABLE,
"SOURCE_ID" NUMBER(2,0),
CONSTRAINT "PK_RESEARCH_TV_COMPANY_1" PRIMARY KEY ("CID", "SOURCE_ID")
USING INDEX (CREATE UNIQUE INDEX "RESEARCH_DEP"."IDX_TV_COMPANY_CID_SOURCE_ID" ON "RESEARCH_DEP"."RESEARCH_TV_COMPANY" ("CID", "SOURCE_ID")
CREATE TABLE "RESEARCH_DEP"."RESEARCH_METRICS_PHARMA_AUD"
( "ID" NUMBER GENERATED ALWAYS AS IDENTITY MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER NOCYCLE NOKEEP NOSCALE NOT NULL ENABLE,
"SOURCE_ID" NUMBER(2,0) NOT NULL ENABLE,
"MEDIA_COMPANY_ID" NUMBER(*,0) NOT NULL ENABLE
)
NEED
ALTER TABLE RESEARCH_DEP.RESEARCH_METRICS_PHARMA_AUD
ADD CONSTRAINT fk_METRICS_PHARMA_AUD_TV_COMPANY_ID
FOREIGN KEY (MEDIA_COMPANY_ID,SOURCE_ID) REFERENCES RESEARCH_DEP.RESEARCH_TV_COMPANY(CID,SOURCE_ID);
ORA-02298: parent keys not found
DO I NEED TO CREATE A COMPOSITION COLUMN: CID,SOURCE_ID?
OR
create sequence of values two column oracle CID,SOURCE_ID ?
Your code is more or less OK:
SQL> create table research_tv_company
2 (cid number,
3 source_id number,
4 --
5 constraint pk_rtc primary key (cid, source_id)
6 );
Table created.
SQL> create table research_metrics_pharma_aud
2 (id number,
3 source_id number,
4 media_company_id number
5 );
Table created.
SQL> alter table research_metrics_pharma_aud
2 add constraint fk_rmpa_rtc
3 foreign key (media_company_id, source_id)
4 references research_tv_company (cid, source_id);
Table altered.
SQL>
Note that I
removed double quotes
removed NOT NULL for primary key columns (they can't be NULL anyway)
don't have any indexes created so Oracle will - along with table creation - create a primary key constraint AND unique index to support it
as I'm on 11gXE and it doesn't support identity columns, I removed that
from the second table; I'd have to enforce it via a trigger. You don't have to do anything about it, just saying (so that you wouldn't wonder where did it go?)
Error you got:
ORA-02298: parent keys not found
means that there are combinations of (media_company_id, source_id) in the second table that do not exist as pairs of (cid, source_id) in the first table. To illustrate it:
Drop the foreign key constraint first (otherwise, I wouldn't be able to do that):
SQL> alter table research_metrics_pharma_aud drop constraint fk_rmpa_rtc;
Table altered.
Insert a row into the first (master) table:
SQL> insert into research_tv_company (cid, source_id) values (1, 1);
1 row created.
Insert two rows into the second (detail) table; the first combination is valid, the second is not as (2, 2) don't exist in research_tv_company:
SQL> insert into research_metrics_pharma_aud (id, source_id, media_company_id) values (1, 1, 1);
1 row created.
SQL> insert into research_metrics_pharma_aud (id, source_id, media_company_id) values (2, 2, 2);
1 row created.
SQL>
If we try to create a foreign key constraint:
SQL> alter table research_metrics_pharma_aud
2 add constraint fk_rmpa_rtc
3 foreign key (media_company_id, source_id)
4 references research_tv_company (cid, source_id);
add constraint fk_rmpa_rtc
*
ERROR at line 2:
ORA-02298: cannot validate (SCOTT.FK_RMPA_RTC) - parent keys not found
SQL>
See? The same error you got.
What can you do?
insert missing primary key values into the master table, or
delete detail rows that violate the constraint, or
create the constraint, but instruct Oracle not to check whether existing rows are valid or not:
SQL> alter table research_metrics_pharma_aud
2 add constraint fk_rmpa_rtc
3 foreign key (media_company_id, source_id)
4 references research_tv_company (cid, source_id)
5 enable novalidate;
Table altered.
SQL>
The enable novalidate means that foreign key constraint will be enabled for any new or modified rows, but existing rows won't be checked. If that option suits you, use it. However, I believe that one of the first two option is better, with the first one - adding missing primary keys - being the best.

Sample Oracle DB for Real Estate Agency

Im trying to build a sample database for a project about a real estate agency,on the table about the realties i have a column Realtie_id and i want it to start with 11%%% what type should it be (int or varchar ) and how do I make the constraint ?
create table Realties (
rid int not null,
address varchar(50),
m2 real not null,
r_type varchar(20),
primary key (rid),
constraint c_rid check(rid in (.....
);
It depends on what you'll be storing in there.
if it is a string, use VARCHAR2
if it is a number, use NUMBER (or INT)
Constraint in any case might be
SQL> create table realties
2 (rid int constraint ch_rid check (substr(to_char(rid), 1, 2) = '11'));
Table created.
SQL> insert into realties (rid) values ('abc');
insert into realties (rid) values ('abc')
*
ERROR at line 1:
ORA-01722: invalid number
SQL> insert into realties (rid) values ('245');
insert into realties (rid) values ('245')
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CH_RID) violated
SQL> insert into realties (rid) values ('1245');
insert into realties (rid) values ('1245')
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CH_RID) violated
SQL> insert into realties (rid) values ('11245');
1 row created.
SQL>
If your value is a number then make the column a numeric data type. The exception to this is when your value is a number string that can start with zeroes, like a phone number, when it should be a string data type; otherwise if you use a number data type then the, semantically important, leading zeroes will be stripped off. Since you want the number to start with 11 then this caveat does not apply.
As for the CHECK constraint, you can use LIKE '11%' and Oracle will implicitly convert it to a string to perform the check.
create table Realties (
rid int
not null
CONSTRAINT realties__rid__pk PRIMARY KEY
CONSTRAINT realties__rid__chk CHECK ( rid LIKE '11%' ),
address varchar(50),
m2 real
not null,
r_type varchar(20)
);

Alter Table , adding a Foreign key constraint at a column ORA-02253

Hello there i am studying for the Oracle Certification of SQL Associate .
And trying to do some Examples .
I have an issue where i cannot find easily a reference on this .
create table employees
(employee_id number NOT NULL,
first_name varchar(20),
last_name varchar(30),
constraint employee_pk primary key (employee_id));
create table employee_notes
(employee_notes_id number,
employee_notes varchar(500),
constraint pk_employee_notes primary key (employee_notes_id));
create sequence employee_notes_seq start with 1 increment by 1
Now i want to add a new column at employee_notes table with a foreign key constraint .
I can't find out in syntax where is the problem .
****alter table employee_notes
add employee_id number
constraint fk_employee_notes foreign key (employee_id) references employees (employee_id);****
i get this error
ORA-02253: constraint specification not allowed her
I also tried to alter the table and add column and then the constraint but cannot
alter table employee_notes
add employee_id number;
--
alter table employee notes
add constraint fk_employee_notes foreign key (employee_id) references employees (employee_id);
ORA-02253: constraint specification not allowed here
I would like to know how i can do this
and why this syntax is wrong :)
You did something wrong because - it works OK:
SQL> CREATE TABLE employees
2 (
3 employee_id NUMBER NOT NULL,
4 first_name VARCHAR (20),
5 last_name VARCHAR (30),
6 CONSTRAINT employee_pk PRIMARY KEY (employee_id)
7 );
Table created.
SQL>
SQL> CREATE TABLE employee_notes
2 (
3 employee_notes_id NUMBER,
4 employee_notes VARCHAR (500),
5 CONSTRAINT pk_employee_notes PRIMARY KEY (employee_notes_id)
6 );
Table created.
SQL> ALTER TABLE employee_notes ADD employee_id NUMBER;
Table altered.
SQL> ALTER TABLE employee_notes ADD CONSTRAINT fk_employee_notes
2 FOREIGN KEY (employee_id)
3 REFERENCES employees (employee_id);
Table altered.
SQL>
When you use ALTER TABLE ... ADD in order to add a column and a constraint in one statement, do the following:
-- notice the () and the comma!
alter table employee_notes
add (
employee_id number
, constraint fk_employee_notes
foreign key (employee_id) references employees (employee_id)
) ;
That should do the trick. See dbfiddle. The syntax is similar to CREATE TABLE, where you'd also write all column names, data types etc in (), separated by commas.

SQL*Plus ORA-00904 invalid identifier & ORA-00905 missing keyword (foreign key)

I've tried to debug this code to the best of my ability to eliminate the possibility of little mistakes being the reason these errors are occurring but I keep getting two different errors on three create table statements.
The CREATE TABLE SECTION statement gives an invalid identifier error on line 7 pointing to course#, here's my code:
CREATE TABLE SECTION
(SECTION# VARCHAR2(8) constraint pk_section# primary key,
TIME CHAR(5),
MAXST NUMBER(2),
ROOM VARCHAR2(14),
constraint chk_maxst check(maxst<=35),
constraint fk_crs foreign key(course#)
REFERENCES course(course#),
constraint fk_pro foreign key(empid)
REFERENCES professor(empid));
The CREATE TABLE TAKES statement gives an invalid identifier error on line 4 pointing to section#, here's my code:
CREATE TABLE TAKES
(GRADE CHAR(5) constraint nn_grade not null,
constraint chk_grade check(grade IN ('A','B','C')),
constraint fk_sec foreign key(section#)
REFERENCES section (section#),
constraint fk_stu foreign key(sid)
REFERENCES student(sid));
Full Context:
drop table professor cascade constraints;
drop table course cascade constraints;
drop table student cascade constraints;
drop table section cascade constraints;
drop table takes cascade constraints;
CREATE TABLE PROFESSOR
(NAME CHAR(15) constraint nn_name not null,
EMPID VARCHAR2(8) constraint pk_empid primary key,
PHONE NUMBER(10),
DATEHIRED DATE,
SALARY NUMBER);
CREATE TABLE COURSE
(NAME CHAR(24) constraint nn_names not null,
COURSE# CHAR(10) constraint pk_course# primary key,
CREDIT CHAR(6) constraint nn_credit not null,
COLLEGE CHAR(20),
HRS NUMBER(1),
constraint chk_credit check(credit IN('U','G')),
constraint chk_college check(college IN ('Arts and Sciences','Education','Engineering','Business')),
constraint chk_course check((credit='U' AND hrs<=4) OR (credit = 'G' AND hrs=3)),
constraint unq_course unique(name, college));
CREATE TABLE STUDENT
(SID VARCHAR2(7) constraint pk_sid primary key,
NAME CHAR(14),
ADDRESS CHAR(22),
BIRTHDATE DATE,
GRADELEVEL CHAR(2) constraint nn_glvl not null);
CREATE TABLE SECTION
(SECTION# VARCHAR2(8) constraint pk_section# primary key,
TIME CHAR(5),
MAXST NUMBER(2),
ROOM VARCHAR2(14),
constraint chk_maxst check(maxst<=35),
constraint fk_crs foreign key(course#)
REFERENCES course(course#),
constraint fk_pro foreign key(empid)
REFERENCES professor(empid));
CREATE TABLE TAKES
(GRADE CHAR(5) constraint nn_grade not null,
constraint chk_grade check(grade IN ('A','B','C')),
constraint fk_sec foreign key(section#)
REFERENCES section (section#),
constraint fk_stu foreign key(sid)
REFERENCES student(sid));
Textbook references:
[https://drive.google.com/open?id=1eDdBShzgnSjISqxByJ7FKgbkLCEwXzpd][1]
[https://drive.google.com/open?id=1WhDsgQy2xSwjxVMqDzaGOcBh7zSokneT][2]
[https://drive.google.com/open?id=12N51OCEucRn_unagqHYsqufEGK3tKJH_][3]
Did you follow documentation that describes how you are supposed to do what you are doing? Because, it seems that you didn't pay much attention at classes, nor read documentation and tend to make up things, doing something that is either wrong or doesn't ever exist.
Consider deleting all that mess and starting over.
Here are some guidelines; try to fix those mistakes, come back if it still doesn't work.
In the COURSE table:
don't use CHAR but VARCHAR2 data type
you can't create constraints on non-existent columns (for example, a check constraint on CRS_CREDIT column, while you named the column as CREDIT)
In the SECTION table:
don't use CHAR data type
you can't use columns (in FOREIGN KEY constraints) that don't exist in the SECTION table (such as SEC_CRS_COURSE#), nor in the table you reference (such as CRS_COURSE# in the COURSE table)
there are no ON UPDATE CASCADE nor ON DELETE RESTRICT in Oracle
The same goes for the TAKES table.
[EDIT, after you almost made it work]
Congratulations! You're now so close! SECTION and TAKES table need some adjustment (missing columns - have a look, I marked them with a comment) and then tables are successfully created.
Once again (as you won't listen): get rid of CHAR data type columns - use VARCHAR2 instead.
SQL> CREATE TABLE PROFESSOR
2 (
3 NAME CHAR (15) CONSTRAINT nn_name NOT NULL,
4 EMPID VARCHAR2 (8) CONSTRAINT pk_empid PRIMARY KEY,
5 PHONE NUMBER (10),
6 DATEHIRED DATE,
7 SALARY NUMBER
8 );
Table created.
SQL>
SQL> CREATE TABLE COURSE
2 (
3 NAME CHAR (24) CONSTRAINT nn_names NOT NULL,
4 COURSE# CHAR (10) CONSTRAINT pk_course# PRIMARY KEY,
5 CREDIT CHAR (6) CONSTRAINT nn_credit NOT NULL,
6 COLLEGE CHAR (20),
7 HRS NUMBER (1),
8 CONSTRAINT chk_credit CHECK (credit IN ('U', 'G')),
9 CONSTRAINT chk_college CHECK
10 (college IN ('Arts and Sciences',
11 'Education',
12 'Engineering',
13 'Business')),
14 CONSTRAINT chk_course CHECK
15 ( (credit = 'U' AND hrs <= 4) OR (credit = 'G' AND hrs = 3)),
16 CONSTRAINT unq_course UNIQUE (name, college)
17 );
Table created.
SQL>
SQL> CREATE TABLE STUDENT
2 (
3 SID VARCHAR2 (7) CONSTRAINT pk_sid PRIMARY KEY,
4 NAME CHAR (14),
5 ADDRESS CHAR (22),
6 BIRTHDATE DATE,
7 GRADELEVEL CHAR (2) CONSTRAINT nn_glvl NOT NULL
8 );
Table created.
SQL>
SQL> CREATE TABLE SECTION
2 (
3 SECTION# VARCHAR2 (8) CONSTRAINT pk_section# PRIMARY KEY,
4 TIME CHAR (5),
5 MAXST NUMBER (2),
6 ROOM VARCHAR2 (14),
7 course# CHAR (10), -- added by LF
8 empid VARCHAR2 (8), -- added by LF
9 CONSTRAINT chk_maxst CHECK (maxst <= 35),
10 CONSTRAINT fk_crs FOREIGN KEY (course#) REFERENCES course (course#),
11 CONSTRAINT fk_pro FOREIGN KEY (empid) REFERENCES professor (empid)
12 );
Table created.
SQL>
SQL> CREATE TABLE TAKES
2 (
3 GRADE CHAR (5) CONSTRAINT nn_grade NOT NULL,
4 section# VARCHAR2 (8), -- added by LF
5 sid VARCHAR2 (7), -- added by LF
6 CONSTRAINT chk_grade CHECK (grade IN ('A', 'B', 'C')),
7 CONSTRAINT fk_sec FOREIGN KEY (section#) REFERENCES section (section#),
8 CONSTRAINT fk_stu FOREIGN KEY (sid) REFERENCES student (sid)
9 );
Table created.
SQL>

Triggers in oracle PL/SQL

I am trying to do a trigger that updates a sum of all credits on update of the grade or a insert of a new one. That's my tables
create table Department (
Department_ID varchar(4) not null,
Name varchar(25) unique,
Department_Head_ID varchar(9),
College_ID varchar(4),
Credits_To_Degree NUMBER(3),
constraint pkDepartment primary key (Department_ID));
create table Enrollment (
Student_ID varchar(9) not null,
Course_ID varchar(5) not null,
Registered_Date date,Grade NUMBER,
Status varchar(4),constraint pkEnrollment primary key
(Student_ID, Course_ID));
create table Student (
Student_ID varchar(9) not null,
First_Name varchar(25),
Last_Name varchar(25),
Phone char(11),
Birth_Date date,
Street varchar(100),
Zip_Code char(5),
Department varchar(4),
Credits integer,
Eligible char(4), constraint pkStudent primary key
(Student_ID),constraint fkDeptId foreign key (Department)
references Department(Department_ID));
ALTER TABLE Department ADD FOREIGN KEY (Department_Head_ID)
REFERENCES Faculty(Faculty_Id) INITIALLY DEFERRED;
ALTER TABLE Department ADD FOREIGN KEY(College_ID) REFERENCES
College(College_ID) INITIALLY DEFERRED;
the trigger:
create or replace TRIGGER Credits
after INSERT OR UPDATE
ON enrollment
REFERENCING NEW AS New OLD AS Old
FOR EACH ROW
BEGIN
UPDATE STUDENT
SET CREDITS=(SELECT SUM(c.CREDITS) FROM COURSE c,ENROLLMENT e
WHERE c.COURSE_ID = e.COURSE_ID
and e.STUDENT_ID = :new.student_id
and e.GRADE>= 60 )
WHERE STUDENT.STUDENT_ID=:new.student_id;
END;
The trigger compiles but when i change value of the grade a get this error
UPDATE "FELIX"."ENROLLMENT" SET GRADE = '60' WHERE ROWID = 'AAAGUSAABAAALKJAAF' AND ORA_ROWSCN = '3540016'
ORA-20003: An error has occurred while performing credits trigger
ORA-06512: at "FELIX.CREDITS", line 5
ORA-04088: error during execution of trigger 'FELIX.CREDITS'
One error saving changes to table "FELIX"."ENROLLMENT":
Row 6: ORA-20003: An error has occurred while performing credits trigger
ORA-06512: at "FELIX.CREDITS", line 5
ORA-04088: error during execution of trigger 'FELIX.CREDITS'
line 5 is a FOR EACH ROW command
I figure out that the problem is in the :new.student_id. But how could i get the id of the row that the triggers fires upon.
Thanks in advance for the help.

Resources