Storing foreign key linked in a separate table? SQL - sql

So I went through Odoo database design and I saw that they stored the relationship between 2 tables in a separate table that doesn't have primary key. How are you able to do this? I want to replicate this kind of behavior in SQL Server. Is it auto-inserted?

A table should always have a primary key. Look at the thousands of questions on Stackoverflow that ask how to delete one of two identical rows in a database table.
You typically model m-to-n relationships between tables with a separate table that has foreign keys to both tables:
CREATE TABLE person (
person_id bigint PRIMARY KEY,
name text,
...
);
CREATE TABLE game (
game_id bigint PRIMARY KEY,
name text NOT NULL,
...
);
CREATE TABLE likes_to_play (
person_id bigint REFERENCES person NOT NULL,
game_id bigint REFERENCES game NOT NULL,
PRIMARY KEY (person_id, game_id)
);
CREATE INDEX ON likes_to_play (game_id);
The primary key on the table makes sure there are no superfluous double entries and backs one of the foreign keys. The other index is created for the other foreign key.

Related

Sql creating table consisting of keys from other tables

this is probably a simple question but I am quite new to SQL and databases, so I have been following this site: https://www.postgresqltutorial.com/postgresql-foreign-key/ to try and create a table that consist of primary keys from other tables.
Here I have the structure of the database in an excel overview. With colors showing the relations. i am having problems with the One-To-Many tables. As I get the same error every time "ERROR: column "id" referenced in foreign key constraint does not exist
SQL state: 42703".
The SQL query:
DROP TABLE IF EXISTS ingredient_to_unit_relations;
DROP TABLE IF EXISTS ingrediens;
CREATE TABLE ingrediens (
id serial,
name_of_ingredient varchar(255),
price_per_unit int,
PRIMARY KEY (id)
);
CREATE TABLE ingredient_to_unit_relations (
ingredient_relation_id int GENERATED ALWAYS AS IDENTITY,
PRIMARY KEY (ingredient_relation_id),
constraint Fk_ingredient_id
FOREIGN KEY (id)
REFERENCES ingrediens (id)
);
You need to define the column in order to declare it as a foreign key:
CREATE TABLE ingredient_to_unit_relations (
ingredient_relation_id int GENERATED ALWAYS AS IDENTITY,
ingredient_id int,
PRIMARY KEY (ingredient_relation_id),
constraint Fk_ingredient_id FOREIGN KEY (ingredient_id) REFERENCES ingrediens (id)
);
I might recommend some somewhat different naming conventions (I changed the name id in the table above):
CREATE TABLE ingredients (
ingredient_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name varchar(255),
price_per_unit int
);
CREATE TABLE ingredient_to_unit_relations (
ingredient_relation_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
ingredient_id int,
CONSTRAINT Fk_ingredient_id FOREIGN KEY (ingredient_id) REFERENCES ingredients (ingredient_id)
);
Notes:
I am a fan of naming primary keys after the table they are in. That way, foreign keys and primary keys usually have the same name (and you can use using if you choose).
Avoid SERIAL. GENERATED ALWAYS AS IDENTITY is now recommended.
You can inline primary key constraints (as well as other constraints).
There is not generally a need to repeat the table name in a column (other than the primary key). So, name instead of name_of_ingredient.
Using int for a monetary column is suspicious. It doesn't allow smaller units. That might work for some currencies but in general I would expect a numeric/decimal type.

How to reference two foreign key attributes within one column?

I'm working on building a database in Oracle SQL developer. In context to the scenario I have a primary table which holds two rovers.
Here is the code for that table:
CREATE TABLE "ROVER" (
Rover_Model_ID varchar(7) NOT NULL,
Rover_Name varchar(50),
Manufacturer varchar(50),
CONSTRAINT Rover_PK PRIMARY KEY (Rover_Model_ID)
);
The way I currently have it, is that there are two rovers in this table. (Refer to the image at the end of the post)
There is also another table called Thermal_System_Components. Which has 3 component entries that both of the rovers use.
CREATE TABLE "THERMAL_SYSTEM_COMPONENT" (
Component_ID INT,
Component_Type varchar(20),
Rover_Model_ID INT NOT NULL,
CONSTRAINT TSC_PK PRIMARY KEY (Component_ID),
CONSTRAINT TSC_FK FOREIGN KEY (Rover_Model_ID) REFERENCES
ROVER(Rover_Model_ID)
);
My question relates to this scenario. There are 3 components which both rovers use, so I wondered how do I go about successfully inputting data into these tables to highlight that BOTH rovers use each of the 3 components. I've inserted the table of my initial concept down below.
If anyone could help clarify this for me I'd be most appreciative.
This is called a many-to-many relationship.
What you need is a third table, mapping rovers to components. Each pair of rover/component takes one row in this table, so there will be six rows total.
CREATE TABLE "ROVER_HAS_COMPONENT" (
Component_ID INT NOT NULL,
Rover_Model_ID INT NOT NULL,
CONSTRAINT TSC_PK PRIMARY KEY (Component_ID, Rover_Model_ID),
CONSTRAINT TSC_FK FOREIGN KEY (Component_ID) REFERENCES
THERMAL_UNIT_COMPONENT(Component_ID),
CONSTRAINT TSC_FK FOREIGN KEY (Rover_Model_ID) REFERENCES
ROVER(Rover_Model_ID)
);
You don't need the Rover_Model_ID in your component table.
PS: You also need the data type in each foreign key column to match the data type of the primary key they reference.

Composite key for a one-to-many relationship?

For a store I have many store_offers which is a one-to-many relationship.
However, for a table
create table store (
id bigserial primary key
);
I can use a single primary key id (SQLfiddle):
create table store_offer (
id bigserial primary key,
store_id bigint not null,
constraint fk__store_offer__store
foreign key (store_id)
references store(id)
);
or a composite primary key (id, store_id) (SQLFiddle):
create table store_offer (
id bigserial not null,
store_id bigint not null,
constraint fk__store_offer__store
foreign key (store_id)
references store(id),
primary key(id, store_id)
);
My question is "what does make more sense here?". Imho the composite key should be the correct way to do it since a store_offer is actually "bound" to as store. But one can argue that this is already the case since the first version has a foreign key. On the other hand a store_offer primary key actually must not change once it's created. You have to create a new store_offer and delete the old one if you want discard one. But you cannot simply change store_id in the second approach.
So what is the correct answer here?
Using primary key(id, store_id) is a bad idea. This will make many queries more complicated and more prone to error. It sounds like what you are really trying to make is a many-to-many relationship between stores and offers. If this is the case you should have a store table with unique store_id as a primary key, an offer table with unique offer_id as a primary key and a store_offer table that has a primary key of store_id and offer_id.

what is meaning of oracle database query: primary key references t_name(col_name)?

create table books
(
bid number(5) primary key,
name varchar2(30)
);
create table members
(
mid number(5) primary key,
name varchar2(30)
);
create table issues
(
bid number(5) primary key
references books(bid),
mid number(5)
references members (mid)
);
I have 3 tables first two tables are simple but what is the meaning of third table as I know foreign key references t_name(col_name); but what is meaning of primary key references t_name(col_name) and col_name references t_name(col_name); ?
It is no special case. Here the primary key bid of table issues is referencing to the column bid of table books. This simply means that bid of issues will have only those values which are present in bid of books. It will act as the primary key of table issues so it will have unique value and it's values will be limited to those contained in books table.
So it simply means it is primary key value with it's values in table books.
It is the same as any other references statement. This is saying that the primary key also references Books(bid).
I can think of two reasons why this type of construct would be used. First, the "issues" entity could be a subset of the "book" entity. This would allow additional issues-specific columns to be stored in issues, without cluttering up books. It also allows foreign keys to either issues or books.
The second reason is that this is one way of implementing vertical partitioning. This occurs when a table has a lots of columns. For performance reasons, you want to separate them into different storage areas. This is sort of similar to what columnar databases do, but it has the overhead of the additional primary key.

Is there always a need for a Primary Key in sql table creations?

I don't know if I created these tables in sql correctly. Can someone confirm I am doing this correctly or incorrectly? Can a table just have a foreign key or does it have to have a primary key? Thanks in advance.
CREATE TABLE Job(
JobId integer,
ToolName varchar(40),
status varchar(100),
start_time time,
finish_time time
PRIMARY KEY(JobId));
CREATE TABLE ErrorLog(
JobId integer,
ErrCode integer,
Description varchar(200),
PRIMARY KEY(ErrCode)
FOREIGN KEY(JobId) REFERENCES Job(JobId));
CREATE TABLE BLAST(
input varchar(100),
database varchar(100),
evalue varchar(100),
JobId integer,
FOREIGN KEY (JobId) REFERENCES Job(JobId));
CREATE TABLE MitoLoc(
input varchar(100),
specificity varchar(100),
JobId integer,
FOREIGN KEY (JobId) REFERENCES Job(JobId));
It is best practice to create a primary key column on a table in a SQL RDBMS. Although SQL does not require tables to have primary keys.
Primary keys allow for a unique identifier to be set for each row in the table. This is the only way you can uniquely identify a specific row in the table, and the only way you'll be able to utilize a foreign key relationship.
Database servers, like SQL Server, also optimize both the storage and querying of tables better when they have primary keys defined.
Primary keys are a very good idea, but not required. Almost every table that I create has an automatically incremented primary key. This is in addition to several other columns that I keep around, such as CreatedAt and CreatedBy.
Foreign key relationships are typically to primary keys but can also be to unique keys.
Why do you want a primary key?
So you can delete a row that is a duplicate, easily.
So you can readily update a single row.
An auto incremented primary key gives you an idea of the order that rows were inserted into the table.
A single column primary key is much easier to handle with foreign key references.
There are, undoubtedly, other reasons. But those are a few.
As for your tables, I think Mitoch and Blast should have id columns that are primary keys. You can also declare other columns (or combinations) to be unique, if appropriate.
Not needed. But It is not good for table structure.
you can create tables without primary key. and it can be have foreign key.
But some DBMS don't allow to save table without primary key
if you are not using primary key then
It is difficult to identify each record
Its record can't references to other tables
when creating table structure some time you have to create composite primary key that mean two or more columns together (combination ) can be primary key