How do I clear a table with a lot of references in oracle? - sql

For instance, suppose I have table A. Then I have tables B-Z that have a foreign key to table A's primary key. Then perhaps there are also some tables that have a foreign key constraint to a table in B-Z's primary key constraint. Is there any easy way to clear out table A and all of the tables that refer to A (or that refer to a table that refers to A) without having to explicitly delete from each table or add an ON CASCADE constraint to each foreign key?
Note that this is mainly for testing purposes, not to be used in production. I would just drop the entire schema and start over again, but that simply isn't feasible for every test (considering how long it takes to build the schema).

I think the most efficient way to do this would be to drop all the FK's, truncate the tables, and then rebuild the FK's.

Related

Does adding a foreign key to a table affect its insertion time?

Is the assumption that each foreign key added a to a table also adds a CHECK constraint that ensures that values inserted in the foreign key column is from the set of values from the table where that key is the primary key.
This would imply that a table with more foreign keys would take longer to insert a value into. Is this correct?
I am using Microsoft SQL Server 2014.
Yes. Foreign key relationships are checked when data is inserted or modified in the table.
The foreign key needs to be to a primary key or unique key. This guarantees that an index is available for the check.
In general, looking up the value in the index should be pretty fast. Faster than the other things that are going on in an insert, such as finding a free page for the data and logging the data.
However, validating the foreign key is going to add some overhead.
Don't mix up foreign keys and checks - there are two different constraint types. For example check accepts nulls and foreign keys not (exception: on delete set null fk option).
When rows are inserted/updated in database set od step is beeing executed, e.g. checking existance of tables, columns, veryfing privileges. Where you have fk database engine must verify contraint before inserting/updateing data to the table - it's additional step to execute.
I have never expirienced situation, when fk painfully slowed down the database operations duration.

How to know when to create a composite constraint?

I am currently learning SQL, and I have a physical data model I need to implement in code. However, during constraint creation, the numbers appearing next to FK and U started confusing me immensely. Consider the diagram. EDIT: Added the full physical model.
I know that when the matter is Primary Keys, we must have a single PK Constraint that's all the columns marked as PK. However, when the thing is FK or Unique constraints, I'm not so sure myself.
Let's assume I want to create the FK constraints for the table Opcao.
Should I create a single constraint for multiple columns, referencing their respective columns like this:
ALTER TABLE MySchema.Opcao ADD CONSTRAINT [FK_SUPERKEY] FOREIGN KEY ([prova], [aluno], [pergunta], [dataRealizacao])
REFERENCES MySchema.Integra([prova], [aluno], [pergunta], [dataRealizacao]);
Or create a constraint for each column, like this:
ALTER TABLE MySchema.Opcao ADD CONSTRAINT [FK_OPCAO_PROVA] FOREIGN KEY ([prova])
REFERENCES MySchema.Integra([prova]);
ALTER TABLE MySchema.Opcao ADD CONSTRAINT [FK_OPCAO_ALUNO] FOREIGN KEY ([aluno])
REFERENCES MySchema.Integra([aluno]);
ALTER TABLE MySchema.Opcao ADD CONSTRAINT [FK_OPCAO_PERGUNTA] FOREIGN KEY ([pergunta])
REFERENCES MySchema.Integra([pergunta]);
ALTER TABLE MySchema.Opcao ADD CONSTRAINT [FK_OPCAO_DATAREALIZACAO] FOREIGN KEY ([dataRealizacao])
REFERENCES MySchema.Integra([dataRealizacao]);
Would the Unique constraints follow the same logic? How do I know when to do one or the other?
You want to make a foreign key consisting of three columns which have to match all the three columns in the referenced table?
Then you should use in my oppinion on constraint for the three columns, because its the semantic you want to tell.
The one constraint for each column approach has the same effect, but you have to think a little to get the intension.
Some other tips: I don't get the semantic of the schema because i don't know the language the entities are named in. It would be easier if they were named in english. One thing i saw is the pergunta column which is duplicated and needs to be consistent in opcao, Integra und Pergunta table, this may lead to problems.
I generally helped me to always make an artifical auto increment primary key for every table (even the join tables for n to m relations), and always reference this artificial key. Then you have less problems (with case insensitivity for example) and the schema is in my oppinion easier to understand.

Changing column to just a regular column instead of foreign key

I have a specific situation where I have a column type in my DB where the column is currently of type int and it is a foreign key type that allows nulls...
My question is: is it possible to change now this column simply to a int type which isn't a foreign key without messing up the data in both tables, and leaving the values intact?
For example:
alter table xy
alter column ForeignKeyIdColumn int null
Would something like this work?
Can someone help me out?
A foreign key is not a property of the columns of a table, it's a database object that defines the relationship between tables.
You can drop the foreign key constraint (though I wouldn't recommend it) using ALTER TABLE with DROP CONSTRAINT, but you have to know the name of the constraint to do it (this is why it's best practice to name everything in SQL SERVER):
ALTER TABLE xy
DROP CONSTRAINT <constraint name here>;
However, as I wrote, I wouldn't recommend dropping foreign key constraints.
Foreign keys are the database way to enforce referential integrity - meaning that a value referenced by another table can't be changed or deleted without changing or deleting the referencing value as well.
Dropping foreign keys means your database will not be able to enforce referential integrity any more and that might lead to corrupt data.
For more information, read Delete Foreign Key Relationships

SQL What is the Purpose of 1 to 1 self reference on primary key? [duplicate]

I went over a legacy database and found a couple of foreign keys that reference a column to itself. The referenced column is the primary key column.
ALTER TABLE [SchemaName].[TableName] WITH CHECK ADD
CONSTRAINT [FK_TableName_TableName] FOREIGN KEY([Id])
REFERENCES [SchemaName].[TableName] ([Id])
What is the meaning of it?
ALTER TABLE [SchemaName].[TableName] WITH CHECK ADD
CONSTRAINT [FK_TableName_TableName] FOREIGN KEY([Id])
REFERENCES [SchemaName].[TableName] ([Id])
This foreign key is completely redundant and pointless just delete it. It can never be violated as a row matches itself validating the constraint.
In a hierarchical table the relationship would be between two different columns (e.g. Id and ParentId)
As for why it may have been created quite likely through use of the visual designer if you right click the "Keys" node in object explorer and choose "New Foreign Key" then close the dialogue box without deleting the created foreign key and then make some other changes in the opened table designer and save it will create this sort of redundant constraint.
In some cases this is a preferred way to reduce redundancy in your model. In using the self referencing foreign key (as shown in you example) you create a hierarchical relationship between rows in your table. Pay attention to what happens when you delete a row from the table, cascading on delete might remove rows you still want.
Using these sort of keys moves some of the data validation to the DB model as opposed to making this a responsibility of the program/programmer. Some outfits prefer this way of doing things. I prefer to make sure programs and programmers are responsible - data models can be hard to refactor and upgrade in production environments.

How to delete unique index referenced by foreign keys?

I have a table, let's call it Users. This table has primary key called Id. Despite having Id as primary key (unique clustered), it has other index (unique nonclustered) on the same column(Id).
I would like to drop this constraint, but foreign keys reference this unique nonclustered index and I get The constraint ... is being referenced by table... error.
What is the best way to drop such index? Do you have any scripts that drop, do something, and recreate foreign key on specific column in specific table? There is a lot of foreign keys, so it would be nice if I could do it automatically. I could use INFORMATION_SCHEMA and other system object to extract information about these keys, but I don't want to write, what have already been written or can be done in other way.
In order to drop a nonclustered index that is referenced by a foreign key you must furst drop the foreign key constraint.
Take a look at the following scrips available from a poster over at SQL Server Central. They may require some tweaking for your "exact" requirements however they provide the basis for scripting out and then subsequently rebuilding foreign keys.
Scrip out Foreign Keys
The two-index approach can make sense:
The second index is probably much smaller than the clustered index, and would more easily fit into memory
The second index might include a selection of columns that benefit specific queries
For dropping the second index, you'll have to drop all foreign keys that refer to it first. Here is a link to the script I use to drop & recreate foreign keys.