create a constraint between tables - sql

I am new to sql and have not have much experience in it
Trying to create a relationship between two tables using a constraint.
adding a unique constraint and relationship for force the userid and consumerid between table1 and table2
any sample will help me
Thanks

You can use this FOREIGN KEY (blabla) REFERENCES secondTable(blabla) but only if the table is not created yet. Write it inside your CREATE TABLE query.
But if it already exists you can add it using ALTER TABLE tablename ADD CONSTRAINT `FK_myKey` FOREIGN KEY (`blabla`) REFERENCES `secondTable` (`blabla`) ON DELETE CASCADE ON UPDATE CASCADE;

Related

How should I create the relational schema to be able to "join" in the oracle database? Which columns do I need to associate with which key?

I created a table but forgot to select primary and foreign key to join the table.
How can I fix this process?
You can use the ALTER TABLE Statement
ALTER TABLE table_name
ADD CONSTRAINT MyPrimaryKey
PRIMARY KEY (column1, column2...);
ALTER TABLE table_name
ADD CONSTRAINT MyForeignKey
FOREIGN KEY (column1) REFERENCES Table(column);

CASCADE behaviour on the drop of a foreign key

I am not clear about what happens when a "foreign key constraint" is deleted specifying the option CASCADE.
For instance, consider this command
ALTER TABLE table1 DROP CONSTRAINT foreignKeyToTable2 CASCADE.
What the option CASCADE is supposed to do in this case? What would happen if I omitted it? And if I wrote RESTRICT instead of CASCADE?
Note: this example of query is excerpted from "Ramez Elmasri, Shamkant B. Navathe - Fundamentals of database systems, end of chapter 5".
The cascade option to drop a constraint is only needed when dropping primary keys, not when dropping a foreign key.
Consider this example in Postgres:
create table t1 (id integer, constraint pk_one primary key (id));
create table t2 (id integer primary key, id1 integer references t1);
When you try to run:
alter table t1 drop constraint pk_one;
You get:
ERROR: cannot drop constraint pk_one on table t1 because other objects depend on it
Detail: constraint t2_id1_fkey on table t2 depends on index pk_one
Hint: Use DROP ... CASCADE to drop the dependent objects too.
If you run:
alter table t1 drop constraint pk_one cascade;
you get:
NOTICE: drop cascades to constraint t2_id1_fkey on table t2
Telling you that the foreign key that needed the primary key was dropped as well.
Note that not all DBMS support a cascading drop. Postgres and Oracle do.
MySQL, SQL Server or Firebird do not. You need to drop the foreign keys manually in those DBMS.

How can I create a foreign key with Index in one single create table statement? (Oracle)

I tried to create a new table (tableB) with a foreign key constraint to another table (tableA) and just wondering if I can create along with this all constraints and indexes needed. My goal would be to have a single create table statement with no need of an alter table… statement afterwards and no other create index… statement. Is this possible? Thanks for any hint in advance :)
create table tableA
(
id number
, constraint tableApk primary key (id)
);
create table tableB
(
id number
, constraint tableBfk foreign key (id) references tableA (id)
on delete cascade
using index (
create index tableBfkidx on tableB (id)
)
);
That isn't allowed. Per the documentation a using_index_clause can only be specified for unique or primary constraints.
Best of luck.

SQL Update error. FK Conflict

I am trying to change the name of a group from ASSY to Manufacturing but am running into some dificulties. It is on a sql server database. I ran the query below.
Update groups
set group_code= 'Manufacturing'
where site_code = 'TMMBC' and group_code = 'ASSY' and group_description = 'Manufacturing'
But it returned with this error - "The UPDATE statement conflicted with the REFERENCE constraint "user_groups_FK_2". The conflict occurred in database "eci", table "dbo.user_groups"."
Is there a way I can update both tables at the same time to bypass this error?
Is there a way I can update both tables at the same time to bypass
this error?
Yes. You can define the foreign key to cascade on update.
I would consider restructuring it so that groups has an integer surrogate key though and have the textual description as a separate column.
This avoids having to repeat the relatively long string Manufacturing possibly many times in the child table.
Assuming your definition for table user_groups looks something like:
create table dbo.user_groups (
group_code varchar(100),
-- other fields
constraint user_groups_fk_2 foreign key (group_code) references dbo.groups (group_code)
);
You would change the table definition to have the foreign key cascade, like:
create table dbo.user_groups (
group_code varchar(100),
-- other fields
constraint user_groups_fk_2 foreign key (group_code) references dbo.groups (group_code) on delete cascade on update cascade
);
Or through ALTER TABLE statements:
alter table dbo.user_groups drop constraint user_groups_fk_2;
alter table dbo.user_groups add constraint user_groups_fk_2 foreign key (group_code) references dbo.groups (group_code) on delete cascade on update cascade;

Add new column with foreign key constraint in one command

I am trying to add a new column that will be a foreign key. I have been able to add the column and the foreign key constraint using two separate ALTER TABLE commands:
ALTER TABLE one
ADD two_id integer;
ALTER TABLE one
ADD FOREIGN KEY (two_id) REFERENCES two(id);
Is there a way to do this with one ALTER TABLE command instead of two? I could not come up with anything that works.
As so often with SQL-related question, it depends on the DBMS. Some DBMS allow you to combine ALTER TABLE operations separated by commas. For example...
Informix syntax:
ALTER TABLE one
ADD two_id INTEGER,
ADD CONSTRAINT FOREIGN KEY(two_id) REFERENCES two(id);
The syntax for IBM DB2 LUW is similar, repeating the keyword ADD but (if I read the diagram correctly) not requiring a comma to separate the added items.
Microsoft SQL Server syntax:
ALTER TABLE one
ADD two_id INTEGER,
FOREIGN KEY(two_id) REFERENCES two(id);
Some others do not allow you to combine ALTER TABLE operations like that. Standard SQL only allows a single operation in the ALTER TABLE statement, so in Standard SQL, it has to be done in two steps.
In MS-SQLServer:
ALTER TABLE one
ADD two_id integer CONSTRAINT fk FOREIGN KEY (two_id) REFERENCES two(id)
In MS SQL SERVER:
With user defined foreign key name
ALTER TABLE tableName
ADD columnName dataType,
CONSTRAINT fkName FOREIGN KEY(fkColumnName)
REFERENCES pkTableName(pkTableColumnName);
Without user defined foreign key name
ALTER TABLE tableName
ADD columnName dataType,
FOREIGN KEY(fkColumnName) REFERENCES pkTableName(pkTableColumnName);
For SQL Server it should be something like
ALTER TABLE one
ADD two_id integer constraint fk foreign key references two(id)
In Oracle :
ALTER TABLE one ADD two_id INTEGER CONSTRAINT Fk_two_id REFERENCES two(id);
2020 Update
It's pretty old question but people are still returning to it I see. In case the above answers did not help you, make sure that you are using same data type for the new column as the id of the other table.
In my case, I was using Laravel and I use "unsigned integer" for all of my ids as there is no point of having negative id LOL.
So for that, the raw SQL query will change like this:
ALTER TABLE `table_name`
ADD `column_name` INTEGER UNSIGNED,
ADD CONSTRAINT constrain_name FOREIGN KEY(column_name) REFERENCES foreign_table_name(id);
I hope it helps
PostgreSQL DLL to add an FK column:
ALTER TABLE one
ADD two_id INTEGER REFERENCES two;
For DB2, the syntax is:
ALTER TABLE one ADD two_id INTEGER FOREIGN KEY (two_id) REFERENCES two (id);
ALTER TABLE TableName
ADD NewColumnName INTEGER,
FOREIGN KEY(NewColumnName) REFERENCES [ForeignKey_TableName](Foreign_Key_Column)
You can do it like below in SQL Server
ALTER TABLE one
ADD two_id int foreign key
REFERENCES two(id)
If you also need to add default values in case you already have some rows in the table then add DEFAULT val
ALTER TABLE one
ADD two_id int DEFAULT 123,
FOREIGN KEY(two_id) REFERENCES two(id);
Try this:
ALTER TABLE product
ADD FOREIGN KEY (product_ID) REFERENCES product(product_ID);
For SQL Server with constraint name
ALTER TABLE one
ADD two_id INT NOT NULL,
CONSTRAINT FK_name FOREIGN KEY (two_id) REFERENCES two(id);