Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add new column or additional table to join two existed tables?

I need to add a new "clmX" column to an existing "tb1" table, which would be a foreign key to another "tb2" table, but some rows will have a null value in the "clmX" column.

Which option is better if we are thinking about designing a database:

a) – add a new column "clmX" to an existing table (as i described above) or

b) – add a new table "tb3", which contains two columns: id_t1, id_tb2 and serves as a connection table between "tb1" and "tb2"?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There is no need to create another table unless it is a many-to-many relation. ie:

CREATE TABLE t1 (id INT IDENTITY PRIMARY KEY NOT NULL, dummy VARCHAR(10));
INSERT dbo.t1(dummy)VALUES('a'), ('b'), ('c'), ('d'), ('e');
CREATE TABLE t2 (id INT IDENTITY PRIMARY KEY NOT NULL, [name] VARCHAR(100) NOT NULL);
INSERT INTO dbo.t2([name])VALUES('c1'), ('c2'), ('c3'), ('c4');
ALTER TABLE t1
ADD clmX INT CONSTRAINT t1_t2 FOREIGN KEY(clmX)REFERENCES t2(id)ON UPDATE CASCADE ON DELETE SET NULL;
UPDATE t1 SET clmX=1 WHERE id=1;
UPDATE t1 SET clmX=2 WHERE id=2;
UPDATE t1 SET clmX=3 WHERE id=3;
SELECT * FROM t1;
SELECT * FROM t2;

id dummy clmX
1 a 1
2 b 2
3 c 3
4 d null
5 e null
id name
1 c1
2 c2
3 c3
4 c4

fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading