Oracle SQL assign specific values - sql

So I am working on my coursework and I am sort of stuck as to what to do for this one part. The question is this :
Flatpack(FlatpackID, Name, Colour, Type, UnitPrice)
FlatpackID should be generated by the DBMS
Name has at most 20 characters and should be not null
Colour is optional
Type is one of (Office, Kitchen, Bedroom, General)
UnitPrice should be between 5.00 and 500.00
Okay so the one I need help with is the one that is in bold/italic i.e. "Type is one of (Office, Kitchen, Bedroom, General")
How exactly am I declaring this within my
CREATE TABLE FLATPACK (
);
I asked and I was told it is only allowed those values and nothing else.
Any help would be greatly appreciated! Thanks

One method is a check constraint:
constraint chk_flatpack_type check ( Type in ('Office', 'Kitchen', 'Bedroom', 'General') );
Another option is to set up foreign key constraint to a reference table, and have the reference table only contain these values.

This is one option (having types restricted by a check constraint):
SQL> CREATE TABLE flatpack
2 (
3 flatpackid NUMBER CONSTRAINT pk_fp PRIMARY KEY,
4 name VARCHAR2 (20) NOT NULL,
5 colour VARCHAR2 (20),
6 TYPE VARCHAR2 (20)
7 CONSTRAINT ch_ty CHECK
8 (TYPE IN ('Office',
9 'Kitchen',
10 'Bedroom',
11 'General')),
12 unitprice NUMBER CONSTRAINT ch_pr CHECK (unitprice BETWEEN 5 AND 500)
13 );
Table created.
SQL>
Another, better (why? More flexible, as you can add any type you want, without altering the table) option is to create a table which will be referenced by the TYPE column:
SQL> CREATE TABLE flatpack_type (TYPE VARCHAR2 (20) CONSTRAINT pk_ty PRIMARY KEY);
Table created.
SQL> CREATE TABLE flatpack
2 (
3 flatpackid NUMBER CONSTRAINT pk_fp PRIMARY KEY,
4 name VARCHAR2 (20) NOT NULL,
5 colour VARCHAR2 (20),
6 TYPE VARCHAR2 (20)
7 CONSTRAINT fk_fp_ty REFERENCES flatpack_type (TYPE),
8 unitprice NUMBER CONSTRAINT ch_pr CHECK (unitprice BETWEEN 5 AND 500)
9 );
Table created.
SQL> insert into flatpack_type --> valid values
2 select 'Office' from dual union all
3 select 'Kitchen' from dual union all
4 select 'Bedroom' from dual union all
5 select 'Genral' from dual;
4 rows created.
As of the ID, you could use an identity column (if on 12c or higher), or a standard option for lower versions - a trigger which uses a sequence:
SQL> create sequence seq_fp;
Sequence created.
SQL> create or replace trigger trg_bi_fp
2 before insert on flatpack
3 for each row
4 begin
5 :new.flatpackid := seq_fp.nextval;
6 end;
7 /
Trigger created.
SQL>

Related

In SQL, can I combine two or more fields into one field during the same insert statement?

For this scenario, I have a table like this: ID (Autoincrement, PK), PartType (VarChar), and DesignItemID (VarChar). I would like to combine the columns ID and PartType into column DesignItemID using a single INSERT statement.
Is this possible?
The purpose for this scenario spawns from trying to use an external SQL database for a part library in Altium Designer. Altium Designer needs a unique ID to maintain a proper link to the part that is placed and the DB. Ordinarily, an autoincrement PK could work, however, I need to keep the different types of parts in separate tables (such at resistors in a resistor table and capacitors in a capacitor table, etc.). So, if I have two or more different tables with an autoincrement PK ID column, I will have multiple IDs all starting at 1.
My proposed solution is to make a table with column ID using autoincrement for the PK, column PartType using a char or varchar, and column DesignItemID also using a char or varchar. Upon an INSERT command, I will enter the value RES for resistor or CAP for capacitor for column PartType and somehow LPAD ID to about 6 places and CONCAT with PartType to create DesignItemID RES000001 or CAP000001 for example. Both tables have 1 as PK ID, but, with the part type and padding, a unique column can be made for Altium Designer.
I understand that in a SQL admin interface, I could structure a query to create this unique piece of data, but Altium Designer requires this unique ID to be in a column.
I can accomplish this task in Access by using a calculate field, but Access is limited to number of concurrent users and cannot scale like an external SQL DB can.
Please note that I will have far more columns in the Database that corresponds to the part. I am only focusing on the columns that I do not know if what I am asking can be done.
depending on your database,
it seems you are asking for a unique number that spans across multiple tables. This could be called ultimately a GUID - if it should also be unique across databases.
this could be done with a single SEQUENCE. or you can look up GUID generators.
exporting multiple tables with such a GUID would be no problem - you just query from wherever they live and send them to your output stream.
Importing on the other hand is more difficult - since you will need to know where each GUID lives (in which table). You can do this with another table that maps each GUID to the table it belongs in.
A little bit of walking instead of just talking. Code you'll see is Oracle, but I guess other databases offer the same or similar options. Note that I don't know Altium Designer.
Question you asked was:
can I combine two or more fields into one field during the same insert statement?
Yes, you can; you already know the operator - it is concatenation. In Oracle, it is either the concat function or double pipe || operator. Here's how.
First, two sample tables (resistors and capacitors):
SQL> create table resistor
2 (id_res varchar2(10) constraint pk_res primary key,
3 name varchar2(10) not null
4 );
Table created.
SQL> create table capacitor
2 (id_cap varchar2(10) constraint pk_cap primary key,
3 name varchar2(10) not null
4 );
Table created.
Sequence will be used to create unique numbers:
SQL> create sequence seqalt;
Sequence created.
Database trigger which creates the primary key value by concatenating a constant (RES for resistors) and the sequence number, left-padded with zeros up to 7 characters in length (so that the full value length is 10 characters):
SQL> create or replace trigger trg_bi_res
2 before insert on resistor
3 for each row
4 begin
5 :new.id_res := 'RES' || lpad(seqalt.nextval, 7, '0');
6 end trg_bi_res;
7 /
Trigger created.
SQL> create or replace trigger trg_bi_cap
2 before insert on capacitor
3 for each row
4 begin
5 :new.id_cap := 'CAP' || lpad(seqalt.nextval, 7, '0');
6 end trg_bi_cap;
7 /
Trigger created.
Let's insert some rows:
SQL> insert into resistor (name) values ('resistor 1');
1 row created.
SQL> select * from resistor;
ID_RES NAME
---------- ----------
RES0000001 resistor 1
Capacitors:
SQL> insert into capacitor (name) values ('capac 1');
1 row created.
SQL> insert into capacitor (name) values ('capac 2');
1 row created.
SQL> select * From capacitor;
ID_CAP NAME
---------- ----------
CAP0000002 capac 1
CAP0000003 capac 2
My suggestion is a view instead of a new table to be used by the Altium Designer - of course, if it is possible (maybe Designer requires a table, and nothing but a table ...):
SQL> create or replace view v_altium (designitemid, name) as
2 select id_res, name from resistor
3 union all
4 select id_cap, name from capacitor;
View created.
SQL> /
View created.
SQL> select * from v_altium;
DESIGNITEM NAME
---------- ----------
RES0000001 resistor 1
CAP0000002 capac 1
CAP0000003 capac 2
You'd now make the Altium Designer read the view and - from my point of view - it should work just fine.
If it has to be a table (let's call it altium), then it would look like this:
SQL> create table altium
2 (designitemid varchar2(10) constraint pk_alt primary key,
3 name varchar2(10)
4 );
Table created.
Triggers will now be changed so that they also insert a row into the altium table (see line #7):
SQL> create or replace trigger trg_bi_res
2 before insert on resistor
3 for each row
4 begin
5 :new.id_res := 'RES' || lpad(seqalt.nextval, 7, '0');
6 insert into altium (designitemid, name) values (:new.id_res, :new.name);
7 end trg_bi_res;
8 /
Trigger created.
SQL> create or replace trigger trg_bi_cap
2 before insert on capacitor
3 for each row
4 begin
5 :new.id_cap := 'CAP' || lpad(seqalt.nextval, 7, '0');
6 insert into altium (designitemid, name) values (:new.id_cap, :new.name);
7 end trg_bi_cap;
8 /
Trigger created.
Let's try it:
SQL> insert into resistor (name) values ('resistor 4');
1 row created.
SQL> insert into resistor (name) values ('resistor 5');
1 row created.
SQL> insert into capacitor (name) values ('capac 5');
1 row created.
Altium table contents reflects contents of resistor and capacitor:
SQL> select * from altium;
DESIGNITEM NAME
---------- ----------
RES0000011 resistor 4
RES0000012 resistor 5
CAP0000013 capac 5
SQL>
However: why do I prefer a view over a table? Because consistency might suffer. What if you delete a row from the capacitor table? You'd have to delete appropriate row from the new altium table as well, and vice versa.
You can't create a foreign key constraint from the altium table to reference primary keys in other tables because as soon as you try to insert a row into the altium table that references resistor, it would fail as there's no such a primary key in capacitor. You can create constraints, but - that's pretty much useless:
SQL> drop table altium;
Table dropped.
SQL> create table altium
2 (designitemid varchar2(10) constraint pk_alt primary key,
3 name varchar2(10),
4 --
5 constraint fk_alt_res foreign key (designitemid) references resistor (id_res),
6 constraint fk_alt_cap foreign key (designitemid) references capacitor (id_cap)
7 );
Table created.
OK, table was successfully created, but - will it work?
SQL> insert into resistor (name) values ('resistor 7');
insert into resistor (name) values ('resistor 7')
*
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.FK_ALT_CAP) violated - parent key not
found
ORA-06512: at "SCOTT.TRG_BI_RES", line 3
ORA-04088: error during execution of trigger 'SCOTT.TRG_BI_RES'
SQL>
Nope, it won't as such a primary key doesn't exist in the capacitor table.
It means that you'd have to maintain consistency manually, and that's always tricky.
Therefore, if possible, use a view.

oracle : Missing right parenthesis

I have a problem, I don't understand why do I have this error
Here's the code
CREATE TABLE Deposit
( ac_no Int(15),
customer_name Varchar(35),
branch_name Varchar(30),
Amount Int(10,2),
credit_date Date
);
Because integers don't have size nor precision.
Also, use VARCHAR2 instead of VARCHAR (that's not an error, but Oracle recommends so).
SQL> CREATE TABLE deposit
2 (
3 ac_no INT,
4 customer_name VARCHAR2 (35),
5 branch_name VARCHAR2 (30),
6 amount INT,
7 credit_date DATE
8 );
Table created.
SQL>
As #Littlefoot already said, INT data type has no precision or scale. If you want precision and scale in your numbers, then use number data type instead.
SQL> CREATE TABLE deposit
2 (
3 ac_no number(15),
4 customer_name VARCHAR2 (35),
5 branch_name VARCHAR2 (30),
6 amount number(10,2),
7 credit_date DATE
8 );
Table created.
SQL>

Getting an error of invalid identifier when try to create relationship between two tables in Oracle SQL developer? [duplicate]

This question already has an answer here:
A CREATE statement with quoted fields in Oracle
(1 answer)
Closed 1 year ago.
This is my device table
CREATE TABLE "DEVICE" (
"IMEI_Number" varchar(15),
"Device_Model" varchar(30),
"Device_Description" varchar(500),
"Assigned_Sim_Number" varchar(11),
"Activation_Date" timestamp,
"Deactivation_Date" timestamp,
"Manufacturer_ID" int,
"Customer_ID" int,
PRIMARY KEY ("IMEI_Number")
);
Then I have the manufacturer table which is
CREATE TABLE "MANUFACTURER" (
"Manufacturer_ID" int,
"Manufacturer_Name" varchar(30),
PRIMARY KEY ("Manufacturer_ID")
);
and I trying to create a relationship between these and getting the ORA-00904: "MANUFACTURER_ID": invalid identifier
My relationship code is
ALTER TABLE DEVICE
ADD FOREIGN KEY (Manufacturer_ID) REFERENCES MANUFACTURER(Manufacturer_ID);
That's just awful. Don't use double quotes when creating objects in Oracle as you'll have to use them every time you reference those objects, and match letter case every time.
SQL> alter table device add constraint fk_mf foreign key ("Manufacturer_ID")
2 references manufacturer ("Manufacturer_ID");
Table altered.
SQL>
A better option would be
SQL> create table device (
2 imei_number varchar2(15),
3 device_model varchar2(30),
4 device_description varchar2(500),
5 assigned_sim_number varchar2(11),
6 activation_date timestamp,
7 deactivation_date timestamp,
8 manufacturer_id int,
9 customer_id int,
10 primary key (imei_number)
11 );
Table created.
SQL> create table manufacturer (
2 manufacturer_id int,
3 manufacturer_name varchar2(30),
4 primary key (manufacturer_id)
5 );
Table created.
SQL> alter table device add constraint fk_mf foreign key (manufacturer_id)
2 references manufacturer (manufacturer_id);
Table altered.
SQL>
(Note also VARCHAR2 datatype; use that instead of VARCHAR).
By default, Oracle stores names in uppercase into data dictionary, but you can reference them using any case you want (upper, lower, mixed). If you do use double quotes, then you have to use their names exactly as during creation phase.
The columns in the tables you've created are surrounded by double-quotes, making their names case-sensitive, while the alter statement does not use quotes, and thus can't match the case-sensitive column name.
The best practice would be to drop these quotes and make the column names case-insensitive. If this is not an option, you could use the same quotes in the alter statement too:
ALTER TABLE DEVICE
ADD FOREIGN KEY ("Manufacturer_ID") REFERENCES MANUFACTURER("Manufacturer_ID");
-- Here ---------^---------------^--------------------------^---------------^

Create Table / Sequence / Trigger in Apex Oracle SQL - ORA-00922 / ORA-00907 / ORA-00922

Using: Application Express 18.1.0.00.45
Please note: I am very new to Oracle Apex and SQL.
For a project I have to create an Application straight in Apex.
I was trying to create a table that works with a Primary Key that auto-increments itself.
Yesterday I created my first Application with a page for user input in a table, a page with table display and filter option and was playing around with forms, dashboard and authentication methods.
I removed the app after playing to start the "Real Work", but I my enthusiasm went quickly away when I realized that I am doing something very wrong but am not sure what.. :)
After lots of googling / reading etc, I am still not sure what is wrong..
See below the code:
-- Create Sequence
CREATE SEQUENCE seq_odm_for_pk
START WITH 1
INCREMENT BY 1
CACHE 100;
-- Create Table for User Input
CREATE TABLE ODM_Progress_v1 (
-- General Details:
ID int NOT NULL AUTO_INCREMENT,
TRAINEE varchar(50) NOT NULL, --1
COACH varchar(50) NOT NULL, --2
STATUS varchar(50) NOT NULL, --3
REGION varchar(5) NOT NULL, --4
-- Actions:
ACTION_TAKEN varchar(100) NOT NULL, --5
ACTION_DETAILS varchar(250), --6
ACTIONED_BY varchar(50) NOT NULL, --7
ACTIONED_DATE DATE NOT NULL, --8
-- Constraints that perform checks for each column:
CONSTRAINT CHK_GeneralDetails CHECK (TRAINEE!=COACH AND (STATUS IN('New', 'In Progress', 'Completed')) AND (REGION IN('EMEA', 'APAC', 'AMER'))),
-- Set Primary Key (Trainee+Coach):
CONSTRAINT PK_ODMProgress PRIMARY KEY (TRAINEE,REGION,ID)
);
-- Create Trigger
CREATE trigger_for_pk_odm_progress
BEFORE INSERT ON ODM_Progress_v1
FOR EACH ROW
WHEN (new.ID is null)
BEGIN
select seq_odm_for_pk.nextval into :new.ID from DUAL;
-- :new.PK_ODMProgress := seq_odm_for_pk.nextval;
END;
The script finishes running with 3 errors, see below:
CREATE OR REPLACE SEQUENCE seq_odm_for_pk START WITH 1
INCREMENT BY 1 CACHE 100
ORA-00922: missing or invalid option
CREATE TABLE ODM_Progress_v1 ( -- General Details: ID int NOT
NULL AUTO_INCREMENT, TRAINEE varchar(50) NOT NULL, --1 COACH
varchar(50) NOT NULL, --2 STATUS varchar(50) NOT NULL, --3
REGION varchar(5) NOT NULL, --4 -- Actions: ACTION_TAKEN
varchar(100) NOT NULL, --5 ACTION_DETAILS varchar(250), --6
ACTIONED_BY varchar(50) NOT NULL, --7 ACTIONED_DATE DATE NOT NULL,
--8 -- Constraints that perform checks for each column: CONSTRAINT CHK_GeneralDetails CHECK (TRAINEE!=COACH AND (STATUS
IN('New', 'In Progress', 'Completed')) AND (REGION IN('EMEA', 'APAC',
'AMER'))), -- Set Primary Key (Trainee+Coach): CONSTRAINT
PK_ODMProgress PRIMARY KEY (TRAINEE,REGION,ID) )
ORA-00907: missing right parenthesis
CREATE OR REPLACE trigger_for_pk_odm_progress BEFORE INSERT ON
ODM_Progress_v1 FOR EACH ROW WHEN (new.ID is null) BEGIN SELECT
seq_odm_for_pk.nextval INTO :new.ID FROM DUAL; --
:new.PK_ODMProgress := seq_odm_for_pk.nextval; END;
ORA-00922: missing or invalid option
Can you please help me unravel this (to me, complete) mystery?
The final application should at least contain 1 table with primary key and sequence (created from scratch, see above) and have at least 2 pages, one is for data input, the other is for data display with use tabs or navigation menu.
Thank you in advance!
That code looks OK, more or less. Here you go:
SQL> CREATE SEQUENCE seq_odm_for_pk
2 START WITH 1
3 INCREMENT BY 1
4 CACHE 100;
Sequence created.
Table: I'm on 11g which doesn't support auto-incremented columns, so I removed that clause:
SQL> CREATE TABLE ODM_Progress_v1 (
2 -- General Details:
3 ID int NOT NULL AUTO_INCREMENT,
4 TRAINEE varchar(50) NOT NULL, --1
5 COACH varchar(50) NOT NULL, --2
6 STATUS varchar(50) NOT NULL, --3
7 REGION varchar(5) NOT NULL, --4
8 -- Actions:
9 ACTION_TAKEN varchar(100) NOT NULL, --5
10 ACTION_DETAILS varchar(250), --6
11 ACTIONED_BY varchar(50) NOT NULL, --7
12 ACTIONED_DATE DATE NOT NULL, --8
13 -- Constraints that perform checks for each column:
14 CONSTRAINT CHK_GeneralDetails CHECK (TRAINEE!=COACH AND (STATUS IN('New', 'In Progress', 'Completed')) AND (REG
ION IN('EMEA', 'APAC', 'AMER'))),
15 -- Set Primary Key (Trainee+Coach):
16 CONSTRAINT PK_ODMProgress PRIMARY KEY (TRAINEE,REGION,ID)
17 );
ID int NOT NULL AUTO_INCREMENT,
*
ERROR at line 3:
ORA-00907: missing right parenthesis
SQL> l3
3* ID int NOT NULL AUTO_INCREMENT,
SQL> c/auto_increment//
3* ID int NOT NULL ,
SQL> /
Table created.
Trigger contains an error in line #1: it is not "trigger_for" but "trigger for" (no underscore):
SQL> CREATE trigger_for_pk_odm_progress
2 BEFORE INSERT ON ODM_Progress_v1
3 FOR EACH ROW
4 WHEN (new.ID is null)
5 BEGIN
6 select seq_odm_for_pk.nextval into :new.ID from DUAL;
7 -- :new.PK_ODMProgress := seq_odm_for_pk.nextval;
8 END;
9 /
CREATE trigger_for_pk_odm_progress
*
ERROR at line 1:
ORA-00901: invalid CREATE command
SQL> l1
1* CREATE trigger_for_pk_odm_progress
SQL> c/er_/er /
1* CREATE trigger for_pk_odm_progress
SQL> l
1 CREATE trigger for_pk_odm_progress
2 BEFORE INSERT ON ODM_Progress_v1
3 FOR EACH ROW
4 WHEN (new.ID is null)
5 BEGIN
6 select seq_odm_for_pk.nextval into :new.ID from DUAL;
7 -- :new.PK_ODMProgress := seq_odm_for_pk.nextval;
8* END;
SQL> /
Trigger created.
SQL>
So:
sequence is OK, but - for vast majority of cases - a simple create sequence seq_odm_for_pk; is enough
for CREATE TABLE remove AUTO_INCREMENT (if you aren't on 12c)
trigger: remove underscore
Now, depending on where you executed those commands, you might have got errors. If you ran them in Apex SQL Workshop, run them one-by-one (and keep only one command in the window). Doing so, it should be OK.
Also, I've noticed that you used VARCHAR datatype - switch to VARCHAR2.
Finally, there's no use in constraining primary key columns with the NOT NULL clause - primary key will enforce it by default.
As of Apex itself: the way you described it, you should create an Interactive Report; the Wizard will create a report (to view data), along with a form (to insert/modify/delete data).
The query you ran in your script is not the same as you posted in your code, as can be read in error text.
Code for creating your sequence as you wrote it in your code should be fine:
CREATE SEQUENCE seq_odm_for_pk
START WITH 1
INCREMENT BY 1
CACHE 100;
As of 11g you cannot use AUTO_INCREMENT in Oracle when creating table. It is not even necessary since you're having a trigger populating your :new.ID with nextval from sequence. So, in your CREATE TABLE remove AUTO_INCREMENT for your ID and everything should be fine.
While creating a trigger you omitted TRIGGER keyword (CREATE OR REPLACE TRIGGER trigger_for_pk_odm_progress).
Also, I'm not sure if you did or did not put END; at the end of your create trigger command. if not, put it.
I hope that helped :)

ORA-00955 during SQL Table creation

I have been getting the error during a table creation. I know it means that the table name needs to change, but I don't see any object with the same name. A copy of the .lst is below.
Thanks
SQL> CREATE TABLE CUSTOMERtable
2 (
3 CUSTOMERID INT NOT NULL,
4 CUSTNAME VARCHAR2 (50) NOT NULL,
5 ADDRESS VARCHAR2 (100) NOT NULL,
6 PHONENUMBER VARCHAR2 (10) NOT NULL,
7 CONSTRAINT IDS_CUST_PK PRIMARY KEY (CUSTOMERID)
8 );
CREATE TABLE CUSTOMERtable
*
ERROR at line 1:
ORA-00955: name is already used by an existing object
SQL>
SQL>
SQL> CREATE TABLE RENTALStable
2 (
3 RENTALID INT NOT NULL,
4 OUTDATE DATE NOT NULL,
5 INDATE DATE NOT NULL,
6 LATEFEE INT,
7 DAMAGEFEE INT,
8 REWINDFEE INT,
9 ID_CUSTOMER INT,
10 CONSTRAINT RentalsTable_IDS_PK PRIMARY KEY (RENTALID),
11 FOREIGN KEY (ID_CUSTOMER) REFERENCES CUSTOMERtable(CUSTOMERID)
12 );
Table created.
This should find the object that's creating the problem:
select *
from user_objects
where object_name = 'CUSTOMERTABLE'
Notice that your statement, even if you write CUSTOMERtable ( upper and lower case), will try to create a table named CUSTOMERTABLE (upper case).
If you want to keep two objects with the same names but different case (and it seems not a good idea to me) you should use double quotes:
CREATE TABLE "CUSTOMERtable" ( ...