What's the reason / usefulness is to use ENABLE keyword in oracle database statements - sql

I would like to know what's the advantage or usefulness of using ENABLE keyword, in statements like:
CREATE TABLE "EVALUATION" (
"EVALUATION_ID" NUMBER(20, 0) NOT NULL ENABLE,
OR
ALTER TABLE "EVALUATION"
ADD CONSTRAINT("EVALUATION_FK")
FOREIGN KEY ("CREW_ID")
REFERENCES "CREW" ("CREW_ID") ENABLE;
For what I read in the documentation, ENABLE is on by default.
Could I assume it is just to enable something that has been previously disabled?

Constraint doc:
CREATE TABLE "EVALUATION" (
"EVALUATION_ID" NUMBER(20, 0) NOT NULL ENABLE,
ENABLE/DISABLE indicates that constraint is on or off. By default ENABLE is used.
ENABLE Clause Specify ENABLE if you want the constraint to be applied
to the data in the table.
DISABLE Clause Specify DISABLE to disable the integrity constraint.
Disabled integrity constraints appear in the data dictionary along
with enabled constraints. If you do not specify this clause when
creating a constraint, Oracle automatically enables the constraint.
Constraints are used to ensure data integrity, but there are scenarios we may need to disable them.
Managing Integrity:
Disabling Constraints
To enforce the rules defined by integrity constraints, the constraints
should always be enabled. However, consider temporarily disabling the
integrity constraints of a table for the following performance
reasons:
When loading large amounts of data into a table
When performing batch operations that make massive changes to a table (for example, changing every employee's number by adding 1000 to
the existing number)
When importing or exporting one table at a time
In all three cases, temporarily disabling integrity constraints can
improve the performance of the operation, especially in data warehouse
configurations.
It is possible to enter data that violates a constraint while that
constraint is disabled. Thus, you should always enable the constraint
after completing any of the operations listed in the preceding bullet
list.
Efficient Use of Integrity Constraints: A Procedure
Using integrity constraint states in the following order can ensure
the best benefits:
Disable state.
Perform the operation (load, export, import).
Enable novalidate state.
Some benefits of using constraints in this order are:
No locks are held.
All constraints can go to enable state concurrently.
Constraint enabling is done in parallel.
Concurrent activity on table is permitted.
EDIT:
The question is rather why to use obvious keyword when it is turn on by default:
I would say:
For clarity (Python EIBTI rule Explicit Is Better Than Implicit)
For completness
Personal taste and/or coding convention
This is the same category as:
CREATE TABLE tab(col INT NULL)
Why do we use NULL if column is nullable by default.

Related

disable foreign key constraint trigger in one transaction

I am trying to make a delete call that triggers a recursive foreign key (which doesn't have an index). The query is very slow.
I've been searching for a while and it seems my options are
add index on fk -- this is not ideal because the write speed for this table is very important, and already not very good
disable trigger for session -- again not ideal because it's exposed to other transactions, would prefer this only applies to an isolated transaction where others are not affected
extend trigger --- this one i'm curious about. Is it possible to store a local variable with set_config which we then check against i.e if var=== true run trigger else don't? Something like this answer https://stackoverflow.com/a/62010745/7530306
You can change the parameter session_replication_role to replica, then only replica triggers will fire, and foreign key constraints won't be checked. That requires superuser permissions, because it endangers the integrity of the database.
I don't see your point. If you disable the foreign key, why keep it around at all? If you are not ready to pay the price, do without referential integrity.
My advice is:
If you need to delete rows frequently, create the index. The risk of violating the constaint by repeatedly disabling it is too high.
If this is a one-time affair, accept the sequential scan on the referencing table.

Why would someone need to enable/disable constraints?

Just starting to learn basics of SQL. In some versions of SQL (Oracle, SQL server etc.) there are enable/disable constraints keywords. What is the difference between these and add/drop constraints keywords? Why do we need it?
Constraint validation has a performance penalty when performing a DML operation. It's common to disable a constraint before a bulk insert/import of data (especially if you know that data is "OK"), and then enable it after the bulk operation is done.
I use disabled constraints in a special situation. I have an application with many tables (around 1000). The records in these table have "natural keys", i.e. identifiers and relations which are given by external source. Some tables use even different natural keys as foreign key references to different tables.
But I like to use common surrogate keys as primary key and for foreign references.
Here is one example (not 100% sure about correct syntax):
CREATE TABLE T_BTS (
OBJ_ID number constraint BTS_PK (OBJ_ID) PRIMARY KEY,
BTS_ID VARCHAR2(20) CONSTRAINT BTS_UK (BTS_ID) UNIQUE,
some more columns);
CREATE TABLE T_CELL (
OBJ_ID number constraint BTS_PK (OBJ_ID) PRIMARY KEY,
OBJ_ID_PARENT number,
BTS_ID VARCHAR2(20),
CELL_ID VARCHAR2(20) CONSTRAINT CELL_UK (BTS_ID, CELL_ID) UNIQUE,
some more columns);
ALTER TABLE T_CELL ADD CONSTRAINT CELL_PARENT_FK
FOREIGN KEY (OBJ_ID_PARENT)
REFERENCES T_BTS (OBJ_ID);
ALTER TABLE T_CELL ADD CONSTRAINT CELL_PARENT
FOREIGN KEY (BTS_ID)
REFERENCES T_BTS (BTS_ID) DISABLE;
In all my tables the primary key column is always OBJ_ID and the key to parent table is always OBJ_ID_PARENT, not matter how the natural key is defined. This makes me easier to have common PL/SQL procedures and compose dynamic SQL Statements.
One example: In order to set OBJ_ID_PARENT after insert, following update would be needed
UPDATE T_CELL cell SET OBJ_ID_PARENT =
(SELECT OBJ_ID
FROM T_BTS bts
WHERE cell.BTS_ID = bts.BTS_ID)
I am too lazy to write 1000+ such individual statements. By using views USER_CONSTRAINTS and USER_CONS_COLUMNS I am able to link the natural keys and the surrogate keys and I can execute these updates via dynamic SQL.
All my keys and references are purely defined by constraints. I don't need to maintain any extra table where I track relations or column names. The only limitation in my application design is, I have to utilize a certain naming convention for the constraints. But the countervalue for this is almost no maintenance is required to keep the data consistent and have good performance.
In order to use all above, some constrains needs to be disabled - even permanently.
I [almost] never disable constraints during the normal operation of the application. The point of the constraints is to preserve data quality.
Now, during maintenance, I can disable them temporarily while adding or removing massive amounts of data. Once they data is loaded I make sure they are enabled again before restarting the application.

How to add a length constraint to a text field

It seems it is preferable to use the TEXT datatype when using PostgreSQL (or some other databases which support it as well) rather than character varying(NN) because there is no performance penalty, and the maximum possible length can be adjusted by dropping and re-applying constraints without effecting any views etc. which use the field.
But, how is this constraint applied (SQL code)?
When you create the table you can do something of this sort,
CREATE TABLE names (
name text CONSTRAINT namechk CHECK (char_length(name) <= 255)
)
(namechk is just a name for the constraint)
Same goes for ALTER TABLE for example:
ALTER TABLE names
ADD CONSTRAINT namechk CHECK (char_length(name) <= 255);
There are really three things here:
Is it better to use text + a check constraint, or varchar(N)?
How would you write an appropriate check constraint?
Should you name your constraints, or let an automatic name be assigned?
Answers:
A varchar(N) will be more obvious when inspecting the schema, and what developers coming from other DBs will expect to see. However, as you say, it is harder to change later. Bear in mind that applying a new/modified check constraint is not free - all existing rows must be checked against the constraint, so on a large table, a lot of reading is necessary.
The syntax for a check constraint is CONSTRAINT name CHECK (condition) (or just CHECK (condition) and Postgres itself will come up with a name) in a CREATE TABLE statement, and ALTER TABLE table_name ADD CONSTRAINT name CHECK (condition);. condition would be an expression using an appropriate string function, e.g. char_length(foo) <= 255.
Adding a name for a constraint is very useful if you want to manage the constraint later. In particular, since you're using this for flexibility, you may well want to write code to drop and recreate the constraint with a new length. If you only ever use graphical tools, this isn't a problem, but managing multiple servers (e.g. development, testing, and production copies) becomes much easier if you can script your changes. With a named constraint, this would like ALTER TABLE foo DROP CONSTRAINT ck_bar_length; ALTER TABLE foo ADD CONSTRAINT ck_bar_length CHECK ( char_length(bar) <= 100 ); I can't actually think of a disadvantage of naming your constraint.

SQL Server - add foreign key relationship

I have an already existing database with tables. I added foreign key relationships (because they were referring data from another table, just that relationship was not explicit in the way tables were created) for one of the tables.
How does this change impact the existing database? Does the database engine have to do some extra work on existing data in the database? Can this change be a "breaking change" if you already have an application that uses the current database schema?
If you added a referential constraint, then the database stores that constraint and ensures it is maintained. For example, if table A has a foreign key referring to table B, then you cannot insert a row into table A that refers to a key that does not exist in table B.
There is indeed some extra work (though very minimal, depending on your database server) to enforce referential integrity. In practice, the performance impact is almost never something you'd notice.
It can be a "breaking change" - your client code may insert data that doesn't meet the referential constraints. If the DB allowed you to create the constraints in the first place, it's not likely, but it is possible.
You can specify WITH NOCHECK when creating a foreign key constraint:
The WITH NOCHECK option is useful when the existing data already meets
the new FOREIGN KEY constraint, or when a business rule requires the
constraint to be enforced only from this point forward.
However, you should be careful when you add a constraint without
checking existing data because this bypasses the controls in the
Database Engine that enforce the data integrity of the table.

What are database constraints? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
What is a clear definition of database constraint? Why are constraints important for a database? What are the types of constraints?
Constraints are part of a database schema definition.
A constraint is usually associated with a table and is created with a CREATE CONSTRAINT or CREATE ASSERTION SQL statement.
They define certain properties that data in a database must comply with. They can apply to a column, a whole table, more than one table or an entire schema. A reliable database system ensures that constraints hold at all times (except possibly inside a transaction, for so called deferred constraints).
Common kinds of constraints are:
not null - each value in a column must not be NULL
unique - value(s) in specified column(s) must be unique for each row in a table
primary key - value(s) in specified column(s) must be unique for each row in a table and not be NULL; normally each table in a database should have a primary key - it is used to identify individual records
foreign key - value(s) in specified column(s) must reference an existing record in another table (via it's primary key or some other unique constraint)
check - an expression is specified, which must evaluate to true for constraint to be satisfied
To understand why we need constraints, you must first understand the value of data integrity.
Data Integrity refers to the validity of data. Are your data valid? Are your data representing what you have designed them to?
What weird questions I ask you might think, but sadly enough all too often, databases are filled with garbage data, invalid references to rows in other tables, that are long gone... and values that doesn't mean anything to the business logic of your solution any longer.
All this garbage is not alone prone to reduce your performance, but is also a time-bomb under your application logic that eventually will retreive data that it is not designed to understand.
Constraints are rules you create at design-time that protect your data from becoming corrupt. It is essential for the long time survival of your heart child of a database solution. Without constraints your solution will definitely decay with time and heavy usage.
You have to acknowledge that designing your database design is only the birth of your solution. Here after it must live for (hopefully) a long time, and endure all kinds of (strange) behaviour by its end-users (ie. client applications). But this design-phase in development is crucial for the long-time success of your solution! Respect it, and pay it the time and attention it requires.
A wise man once said: "Data must protect itself!". And this is what constraints do. It is rules that keep the data in your database as valid as possible.
There are many ways of doing this, but basically they boil down to:
Foreign key constraints is probably the most used constraint,
and ensures that references to other
tables are only allowed if there
actually exists a target row to
reference. This also makes it
impossible to break such a
relationship by deleting the
referenced row creating a dead link.
Check constraints can ensure that only specific values are allowed in
certain column. You could create a constraint only allowing the word 'Yellow' or 'Blue' in a VARCHAR column. All other values would yield an error. Get ideas for usage of check constraints check the sys.check_constraints view in the AdventureWorks sample database
Rules in SQL Server are just reusable Check Constraints (allows
you to maintain the syntax from a
single place, and making it easier to
deploy your constraints to other
databases)
As I've hinted here, it takes some thorough considerations to construct the best and most defensive constraint approach for your database design. You first need to know the possibilities and limitations of the different constraint types above. Further reading could include:
FOREIGN KEY Constraints - Microsoft
Foreign key constraint - w3schools
CHECK Constraints
Good luck! ;)
Constraints are nothing but the rules on the data. What data is valid and what is invalid can be defined using constraints. So, that integrity of data can be maintained.
Following are the widely used constraints:
Primary Key : which uniquely identifies the data . If this constraint has been specified for certain column then we can't enter duplicate data in that column
Check : Such as NOT NULL . Here we can specify what data we can enter for that particular column and what is not expected for that column.
Foreign key : Foreign key references to the row of other table. So that data referred in one table from another table is always available for the referencing table.
Constraints can be used to enforce specific properties of data. A simple example is to limit an int column to values [0-100000]. This introduction looks good.
Constraints dictate what values are valid for data in the database. For example, you can enforce the a value is not null (a NOT NULL constraint), or that it exists as a unique constraint in another table (a FOREIGN KEY constraint), or that it's unique within this table (a UNIQUE constraint or perhaps PRIMARY KEY constraint depending on your requirements). More general constraints can be implemented using CHECK constraints.
The MSDN documentation for SQL Server 2008 constraints is probably your best starting place.
UNIQUE constraint (of which a PRIMARY KEY constraint is a variant). Checks that all values of a given field are unique across the table. This is X-axis constraint (records)
CHECK constraint (of which a NOT NULL constraint is a variant). Checks that a certain condition holds for the expression over the fields of the same record. This is Y-axis constraint (fields)
FOREIGN KEY constraint. Checks that a field's value is found among the values of a field in another table. This is Z-axis constraint (tables).
A database is the computerized logical representation of a conceptual (or business) model, consisting of a set of informal business rules. These rules are the user-understood meaning of the data. Because computers comprehend only formal representations, business rules cannot be represented directly in a database. They must be mapped to a formal representation, a logical model, which consists of a set of integrity constraints. These constraints — the database schema — are the logical representation in the database of the business rules and, therefore, are the DBMS-understood meaning of the data. It follows that if the DBMS is unaware of and/or does not enforce the full set of constraints representing the business rules, it has an incomplete understanding of what the data means and, therefore, cannot guarantee (a) its integrity by preventing corruption, (b) the integrity of inferences it makes from it (that is, query results) — this is another way of saying that the DBMS is, at best, incomplete.
Note: The DBMS-“understood” meaning — integrity constraints — is not identical to the user-understood meaning — business rules — but, the loss of some meaning notwithstanding, we gain the ability to mechanize logical inferences from the data.
"An Old Class of Errors" by Fabian Pascal
There are basically 4 types of main constraints in SQL:
Domain Constraint: if one of the attribute values provided for a new
tuple is not of the specified attribute domain
Key Constraint: if the value of a key attribute in a new tuple
already exists in another tuple in the relation
Referential Integrity: if a foreign key value in a new tuple
references a primary key value that does not exist in the referenced
relation
Entity Integrity: if the primary key value is null in a new tuple
constraints are conditions, that can validate specific condition.
Constraints related with database are Domain integrity, Entity integrity, Referential Integrity, User Defined Integrity constraints etc.