How to CREATE TABLE with disjoint relationship in SQL - sql

I am trying to create a table using a disjoint subtype relationship.
For example, if the Supertype is furniture, and I have 3 Subtypes of furniture: chair, couch, and table.
Then:
CREATE TABLE Furniture
(order_num NUMBER(15), desc VARCHAR2(20), type VARCHAR2(10));
How do I make an option to pick type of chair, couch or table?

You can use REFERENCES in the CREATE TABLE.
CREATE TABLE Furniture_SubTypes
(
sub_type VARCHAR(10) PRIMARY KEY
);
INSERT INTO Furniture_SubTypes VALUES ('Chair');
INSERT INTO Furniture_SubTypes VALUES ('Couch');
INSERT INTO Furniture_SubTypes VALUES ('Table');
CREATE TABLE Furniture
(
order_num NUMBER,
description VARCHAR(20),
sub_type REFERENCES Furniture_SubTypes(sub_type)
);

Use a check constraint:
CREATE TABLE Furniture (
order_num NUMBER(15),
description VARCHAR2(20),
type VARCHAR2(10),
check (type in ('chair', 'couch', 'table'))
);
Note that desc is a poor choice for a column name, because it is a keyword in SQL (used for order by).

Related

Can I change an attribute name from a table derived from a type?

Folowing the Object-Relational Database model, I wanted to create the tables or_doctor and or_recepcionist derived from the type t_employee.
Here, follows the type structure:
DROP TYPE t_employee FORCE;
CREATE OR REPLACE TYPE t_employee AS OBJECT (
num_employee INTEGER,
name_employee VARCHAR2(50),
birthdate_employee DATE
);
And here, the tables' structure:
DROP TABLE or_doctor CASCADE CONSTRAINTS;
CREATE TABLE or_doctor OF t_employee (
PRIMARY KEY (num_employee),
name_employee NOT NULL,
birthdate_employee NOT NULL
) OBJECT IDENTIFIER IS SYSTEM GENERATED;
DROP TABLE or_recepcionist CASCADE CONSTRAINTS;
CREATE TABLE or_recepcionist OF t_employee (
PRIMARY KEY (num_employee),
name_employee NOT NULL,
birthdate_employee NOT NULL
) OBJECT IDENTIFIER IS SYSTEM GENERATED;
Doing so, the attributes names, on both tables, will end up with "employee". Could I change the attribute name so they are specific in each table at the moment I'm creating the table?
E.G.:
Table or_doctor: num_doct, name_doct, birthdate_doct.
Table or_recepcionist: num_recep, name_recep, birthdate_recep.
As a frame challenge, don't add a suffix to your identifiers then you don't need to worry about the suffix being incorrect:
CREATE TYPE t_employee AS OBJECT (
num INTEGER,
name VARCHAR2(50),
birthdate DATE
);
CREATE TABLE or_doctor OF t_employee (
PRIMARY KEY (num),
name NOT NULL,
birthdate NOT NULL
) OBJECT IDENTIFIER IS SYSTEM GENERATED;
CREATE TABLE or_receptionist OF t_employee (
PRIMARY KEY (num),
name NOT NULL,
birthdate NOT NULL
) OBJECT IDENTIFIER IS SYSTEM GENERATED;
If you try to rename the column:
ALTER TABLE or_doctor RENAME COLUMN name TO name_doctor;
Then you will get the error:
ORA-23291: Only base table columns may be renamed
If you are using object-derived tables then you appear to be stuck with the identifiers from the object; so, make the object names generic so that they are appropriate in every place they are going to be used.

SQL add a new column and its values only can be in several fixed options

I want to add a new column with SQL in my data table as below,
CREATE TABLE brands (
Brand varchar(255),
Contact varchar(150),
Address varchar(255),
Location varchar(50),
)
:
I wish to add a new column called country, and the value only can be selected from the following values: "Japan", "New Zealand", "US", "France"
I can add the new column but I don't know how to set the limited optional values for the column. Please help if you have ideas. Many thanks
You could use a check constraint, or a foreign key.
Check constraint:
alter table brands add country_name varchar(64) not null;
alter table brands add constraint ck_country_list
check (country_name in ('Japan', 'New Zealand', 'US', 'France'));
With a check constraint, the values that are allowed never change (unless you change the constraint code). With a foreign key, the allowed values are stored in another table. As long as the value exists in the other table, they are allowed in this table.
create table countries(country_name varchar(64) not null primary key);
insert countries (country_name)
values ('France'), ('New Zealand') -- etc
alter table brands add country_name varchar(64) not null;
alter table brands add constraint fk_brands_countries
foreign key (country_name) references countries (country_name);
But we can actually do even better that! Countries already have a well defined "thing" which uniquely identifies them: ISO3166 country codes. You can use the 2 char, 3 char, or int versions. Using well defined standards where you can is always a good idea for primary keys.
This is the next level up beyond what you are currently trying to learn. But here's what it might look like:
create table countries
(
country_code char(2) not null primary key clustered,
country_name varchar(64) not null
);
insert countries (country_code, country_name)
values ('FR', 'France'), ('NZ', 'New Zealand') -- etc etc;
alter table brands add country_code char(2) not null;
alter table brands add constraint fk_brands_countries
foreign key (country_code) references countries (country_code);
When you want to get the country name, you join the brands table to the countries table using the country_code column.
After you added the column you could add a check constraint
ALTER TABLE brands
ADD CONSTRAINT chk_country check (Country IN ('Japan', 'New Zealand', 'US', 'France'));

Using joins in complex queries

I have three tables customer_cars, bookings, and replaced_parts ad below:
CREATE TABLE customer_cars(
pk_car_id NUMBER(11) NOT NULL,
car_plate_number VARCHAR2(15) NOT NULL
);
CREATE TABLE bookings(
pk_booking_id NUMBER(11),
fk_car_id NUMBER(11),
);
CREATE TABLE replaced_parts(
pk_parts_id VARCHAR2(25),
fk_booking_id NUMBER(11),
replaced_parts parts_varray_type
);
CREATE OR REPLACE TYPE parts_type AS OBJECT (
name VARCHAR2(25),
price NUMBER(10),
);
/
CREATE TYPE parts_varray_type AS
VARRAY(40) OF parts_type;
/
I am trying to get parts name from parts_varray_type of a car. All i have is car_plate_number. Using this plate number i want to find pk_car_id in customer_cars and then that pk_car_if id should match with fk_car_id in bookings to find bookings_id. Then the found booking id should match with fk_booking_id in replaced_parts to get the parts_name.
INSERT INTO customer_cars (pk_car_id, car_plate_number)
VALUES(200000,'5651L');
INSERT INTO bookings(pk_booking_id, fk_car_id)
VALUES(700000,200000);
INSERT INTO replaced_parts (pk_parts_id, fk_booking_id, replaced_parts)
VALUES(700000,600000,
parts_varray_type(
parts_type('CLUTCH', 2000)));
Above is the insert statements. Now using plate number '5651L' i want to display clutch , 2000 from parts parray type.
Something like:
SELECT..
FROM..(Usings joins or any other methods)
WHERE pk_car_id = '5651L';
It should display name and price from parts varray type.

how to create a Foreign-Key constraint to a subset of the rows of a table?

I have a reference table, say OrderType that collects different types of orders:
CREATE TABLE IF NOT EXISTS OrderType (name VARCHAR);
ALTER TABLE OrderType ADD PRIMARY KEY (name);
INSERT INTO OrderType(name) VALUES('sale-order-type-1');
INSERT INTO OrderType(name) VALUES('sale-order-type-2');
INSERT INTO OrderType(name) VALUES('buy-order-type-1');
INSERT INTO OrderType(name) VALUES('buy-order-type-2');
I wish to create a FK constraint from another table, say SaleInformation, pointing to that table (OrderType). However, I am trying to express that not all rows of OrderType are eligible for the purposes of that FK (it should only be sale-related order types).
I thought about creating a view of table OrderType with just the right kind of rows (view SaleOrderType) and adding a FK constraint to that view, but PostgreSQL balks at that with:
ERROR: referenced relation "SaleOrderType" is not a table
So it seems I am unable to create a FK constraint to a view (why?). Am I only left with the option of creating a redundant table to hold the sale-related order types? The alternative would be to simply allow the FK to point to the original table, but then I am not really expressing the constraint as strictly as I would like to.
I think your schema should be something like this
create table order_nature (
nature_id int primary key,
description text
);
insert into order_nature (nature_id, description)
values (1, 'sale'), (2, 'buy')
;
create table order_type (
type_id int primary key,
description text
);
insert into order_type (type_id, description)
values (1, 'type 1'), (2, 'type 2')
;
create table order_nature_type (
nature_id int references order_nature (nature_id),
type_id int references order_type (type_id),
primary key (nature_id, type_id)
);
insert into order_nature_type (nature_id, type_id)
values (1, 1), (1, 2), (2, 1), (2, 2)
;
create table sale_information (
nature_id int default 1 check (nature_id = 1),
type_id int,
foreign key (nature_id, type_id) references order_nature_type (nature_id, type_id)
);
If the foreign key clause would also accept an expression the sale information could omit the nature_id column
create table sale_information (
type_id int,
foreign key (1, type_id) references order_nature_type (nature_id, type_id)
);
Notice the 1 in the foreign key
You could use an FK to OrderType to ensure referential integrity and a separate CHECK constraint to limit the order types.
If your OrderType values really are that structured then a simple CHECK like this would suffice:
check (c ~ '^sale-order-type-')
where c is order type column in SaleInformation
If the types aren't structured that way in reality, then you could add some sort of type flag to OrderType (say a boolean is_sales column), write a function which uses that flag to determine if an order type is a sales order:
create or replace function is_sales_order_type(text ot) returns boolean as $$
select exists (select 1 from OrderType where name = ot and is_sales);
$$ language sql
and then use that in your CHECK:
check(is_sales_order_type(c))
You don't of course have to use a boolean is_sales flag, you could have more structure than that, is_sales is just for illustrative purposes.

Create a table of two types in PostgreSQL

I have created two types:
Create Type info_typ_1 AS (
Prod_id integer,
category integer);
Create Type movie_typ AS(
title varchar(50),
actor varchar(50),
price float);
And I want to create a table that consists of these two types. I know that for a table that consists of one type, it's:
CREATE TABLE Table1 of type1
(
primary key(prod_id)
);
Is there any way to do that for the two types I created above?
What I tried doing(which is wrong), is creating a third type that contains the first two:
Create Type info_ AS (
info info_typ_1,
movie movie_typ);
and then creating the table:
CREATE TABLE table1 of info_
(
primary key(Prod_id)
);
But it doesn't work. I get this error:
ERROR: column "prod_id" named in key does not exist
LINE 3: primary key(Prod_id)
^
********** Error **********
ERROR: column "prod_id" named in key does not exist
SQL state: 42703
Character: 43
You cannot make prod_id the primary key of table1 because the only columns are the two composite types info and movie. You cannot access the base types of these composite types in a PRIMARY KEY clause.
What you were trying to do works with a pk constraint on info or movie.
Except, it's probably not what you were looking for, which is not possible this way.
You could implement something like this with ...
Inheritance
Here you can inherit from multiple parent tables (substitute for your types). Example:
CREATE TABLE info (
prod_id integer
,category integer
);
CREATE TABLE movie (
title text
,actor text
,price float
);
CREATE TABLE movie_info (
PRIMARY KEY(prod_id) -- now we can use the base column!
)
INHERITS (info, movie);
INSERT INTO movie_info (prod_id, category, title, actor, price)
VALUES (1, 2, 'who donnit?', 'James Dean', '15.90');
SELECT * FROM movie_info;
-> SQLfiddle demonstrating both.
Be sure to read about limitations of inheritance in the manual.