SQl foreign key disabling - sql

Is there a way i can declare a disabled foreign key in the table creation in SQL
i don't want to do it by altering the table if possible.

From the CONSTRAINT documentation, use the DISABLE keyword:
CREATE TABLE table1 (
ID NUMBER PRIMARY KEY
)
CREATE TABLE table2 (
OTHER_ID CONSTRAINT table2__other_id__fk REFERENCES table1 (id) DISABLE
);
fiddle

Related

Phantom Table being created in Teradata

I'm using Teradata 16.20.05.01 to run the following script:
create table t1(v int not null);
create table t2(w int null);
alter table t1 add constraint pk primary key (v);
alter table t2 add constraint t2_fk foreign key (w) references t1 (v);
After adding the foreign key, I suddenly get one excess table in my schema:
select TableName, RequestText
from "DBC".Tables
where DatabaseName = 'test'
and (TableName like 't1%' or TableName like 't2%')
Output:
TableName |RequestText |
----------|----------------------------------------------------------------------|
t1 |alter table t1 add constraint pk primary key (v) |
t2 |create table t2(w int null) |
T2_0 |alter table t2 add constraint t2_fk foreign key (w) references t1 (v) |
This is especially annoying when re-creating that foreign key:
alter table t2 drop constraint t2_fk;
alter table t2 add constraint t2_fk foreign key (w) references t1 (v);
Which isn't possible because of:
SQL Error [5303] [HY000]: [Teradata Database] [TeraJDBC 15.00.00.33] [Error 5303] [SQLState HY000] Error table 'TEST.t2_0' already exists.
Workaround:
The problem does not appear when using inline constraint definitions
create table t1(v int not null, constraint pk primary key (v));
create table t2(w int null, constraint t2_fk foreign key (w) references t1 (v));
Is this a known issue? Is there a reliable workaround?
This is documented behaviour, when you add a Foreign Key to an existing table there's an error table created and all all rows violating the constraint are copied into it. And it's not dropped automatically after the ALTER.
The workaround is simple: Don't use Standard Foreign Keys, you will hardly find any site using it. Switch to Batch FKs, i.e. REFERENCES WITH CHECK OPTION, which applies the check on a request level (not row by row), or to a Soft/Dummy FK, REFERENCES WITH NO CHECK OPTION, which simply defined the constraint without enforcing it (you must check for PK/FK violations in your load scripts anyway).

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.

Enforce a foreign-key constraint to columns of same table

How to enforce a constraint of foreign key on columns of same table in SQL while entering values in the following table:
employee:
empid number,
manager number (must be an existing employee)
Oracle call this a self-referential integrity constraint. The documentation is here for a description,
You create a self-referential constraint in the same manner you would a normal one:
alter table employees
add constraint employees_emp_man_fk
foreign key ( manager_no )
references employees ( emp_id )
on delete set null
;
I'm assuming that your manager_no is nullable. I've added set null here as a delete cascade would probably wipe out a significant amount of your table.
I can't think of a better way of doing this. Deleting a manager should not result in the deletion of all their employees so you have to set null and have a trigger on the table to alert you to anyone with no manager.
I always like this site, which is good for simple references. and don't forget to have an index on the FK as well or Tom will yell at you :-).
One can also utilise standard Oracle syntax to create a self-referential FK in the create table statement, which would look like the following.
create table employees
( emp_id number
, other_columns ...
, manager_no number
, constraint employees_pk
primary key (emp_id)
, constraint employees_man_emp_fk
foreign key ( manager_no )
references employees ( emp_id )
on delete set null
);
EDIT:
In answer to #popstack's comment below:
Whilst you can do this in one statement not being able to alter a table is a fairly ridiculous state of affairs. You should definitely analyze a table that you're going to be selecting from and you will still want an index on the foreign key ( and possibly more columns and / or more indexes ) otherwise whenever you use the foreign key you're going to do a full table scan. See my link to asktom above.
If you're unable to alter a table then you should, in descending order of importance.
Find out how you can.
Change your DB design as a FK should have an index and if you can't have one then FKs are probably not the way to go. Maybe have a table of managers and a table of employees?
SELF REFERENCES QUERY...
Alter table table_name ADD constraints constraints_name foreign key(column_name1,column_name2..) references table_name(column_name1,column_name2...) ON DELETE CASCADE;
EX- ALTER TABLE Employee ADD CONSTRAINTS Fr_key( mgr_no) references employee(Emp_no) ON DELETE CASCADE;
CREATE TABLE TABLE_NAME (
`empid_number` int ( 11) NOT NULL auto_increment,
`employee` varchar ( 100) NOT NULL ,
`manager_number` int ( 11) NOT NULL ,
PRIMARY KEY (`empid_number`),
CONSTRAINT `manager_references_employee`
FOREIGN KEY (`manager_number`) REFERENCES (`empid_number`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
Hope it helps!

How to create composite primary key in SQL Server 2008

I want to create tables in SQL Server 2008, but I don't know how to create composite primary key. How can I achieve this?
create table my_table (
column_a integer not null,
column_b integer not null,
column_c varchar(50),
primary key (column_a, column_b)
);
CREATE TABLE UserGroup
(
[User_Id] INT NOT NULL,
[Group_Id] INT NOT NULL
CONSTRAINT PK_UserGroup PRIMARY KEY NONCLUSTERED ([User_Id], [Group_Id])
)
Via Enterprise Manager (SSMS)...
Right Click on the Table you wish to create the composite key on and select Design.
Highlight the columns you wish to form as a composite key
Right Click over those columns and Set Primary Key
To see the SQL you can then right click on the Table > Script Table As > Create To
I know I'm late to this party, but for an existing table, try:
ALTER table TABLE_NAME
ADD CONSTRAINT [name of your PK, e.g. PK_TableName] PRIMARY KEY CLUSTERED (column1, column2, etc.)
For MSSQL Server 2012
CREATE TABLE usrgroup(
usr_id int FOREIGN KEY REFERENCES users(id),
grp_id int FOREIGN KEY REFERENCES groups(id),
PRIMARY KEY (usr_id, grp_id)
)
UPDATE
I should add !
If you want to add foreign / primary keys altering, firstly you should create the keys with constraints or you can not make changes. Like this below:
CREATE TABLE usrgroup(
usr_id int,
grp_id int,
CONSTRAINT FK_usrgroup_usrid FOREIGN KEY (usr_id) REFERENCES users(id),
CONSTRAINT FK_usrgroup_groupid FOREIGN KEY (grp_id) REFERENCES groups(id),
CONSTRAINT PK_usrgroup PRIMARY KEY (usr_id,grp_id)
)
Actually last way is healthier and serial. You can look the FK/PK Constraint names (dbo.dbname > Keys > ..) but if you do not use a constraint, MSSQL auto-creates random FK/PK names. You will need to look at every change (alter table) you need.
I recommend that you set a standard for yourself; the constraint should be defined according to the your standard. You will not have to memorize and you will not have to think too long. In short, you work faster.
First create the database and table, manually adding the columns. In which column to be primary key. You should right click this column and set primary key and set the seed value of the primary key.
To create a composite unique key on table
ALTER TABLE [TableName] ADD UNIQUE ([Column1], [Column2], [column3]);
CREATE TABLE UserGroup
(
[User_Id] INT Foreign Key,
[Group_Id] INT foreign key,
PRIMARY KEY ([User_Id], [Group_Id])
)

Alter Sql table (Change foreign key to Second primary of the table)

I've a sql table with a primary key(Auto Incremented) and a foreign key.Now I need to modify the table by modifying the foreign key to second primary key so that its values are not allowed to duplicate.
How do i alter my table without affecting the data? Need the sql code.
Regards,
Vix
If I understand your request, you want to force the foreign key to be unique within the given table so your schema looks like:
Create Table Table1
(
Id int not null primary key clustered
, ForeignId not null
, ...
, Constraint FK_Table1_Table2
Foreign Key ( ForeignId )
References Table2( Id )
)
And you now want to force ForeignId to be unique in this table, correct? You would do the following:
Alter Table Table1
Add Constraint UC_Table1_ForeignId Unique Nonclustered ( ForeignId )