This question already has answers here:
How to ADD a CONSTRAINT NAME to an already EXISTING CONSTRAINT
(2 answers)
Closed 5 years ago.
I'm learning ORACLE and create a table with different columns and constraint, Now I want to give a name to already created constraint without dropping the constraint. How I can give name to them? as I see there are couple of constraints in user_constraints table, but I don't know their name like(null, unique) and their column.
Again I want to give name to my existing constraints(which have default oracle created name like ( SYS_C0010392 ).
Here is query image that I used to create table with constraints.( SQLPLUS not allowing to copy the query that's why I add image )
ALTER TABLE dept RENAME CONSTRAINT SYS_C0010392 TO new_name;
And SQL*Plus is console application as any other so you definitely can copy selected text.
Column CDB/DBA/ALL/USER_CONSTRAINT.CONSTRAINT_TYPE describes the constraint type, see http://docs.oracle.com/cloud/latest/db121/REFRN/refrn20047.htm#REFRN20047.
Constraint name can be specified in CREATE TABLE command:
create table my_table (
col1 number
constraint my_table_col1_nn not null
constraint my_table_col1_uq unique
);
Column constraint association is available in CDB/DBA/ALL/USER_CONS_COLUMNS:
SELECT * FROM ALL_CONS_COLUMNS WHERE CONSTRAINT_NAME = 'SYS_C0010392'
Related
I am working on this assignment question and it is asking me:
To create a table called (TEMP_CUST) from an existing table Customers
View the content and constraints of TEMP_CUST table
What I have done so far is I have created my table, didn't add any constraints to the table TEMP_CUST and viewed the table using the DESC command.
Here is the code for table creation
CREATE TABLE TEMP_CUST
AS
(SELECT
CUSTOMER#, LASTNAME,
FIRSTNAME, ADDRESS, CITY,
STATE, ZIP, REFERRED,
REGION, EMAIL
FROM
CUSTOMERS);
DESC TEMP_CUST;
Now that I have done that I want to view the constraints of the table. I have used this command but am not sure if it is correct.
SELECT *
FROM USER_CONSTRAINTS
WHERE TABLE_NAME = 'TEMP_CUST';
i have used this command, but not sure if it is correct.
You haven't said why you don't think it's correct so we have to guess the reason for your doubt. Perhaps it's because the set of constraints you get is smaller than the set of constraints for the original CUSTOMERS table?
That is correct. When we use CREATE TABLE ... AS SELECT the statement creates a new table with the projection, column names and datatypes of the original tables (assuming a vanilla SELECT clause) and the data (determined by the WHERE clause, if any). However, the only constraints which are created are NOT NULL constraints on the primary key column(s) and any other mandatory columns. The new table does not have primary key, foreign key or check constraints. We have to create these explicitly.
Hence, this query ...
SELECT * FROM USER_CONSTRAINTS
WHERE TABLE_NAME = 'TEMP_CUST';
... might return fewer constraints than you were expecting.
I want to know if there is some specific way to obtain a table-level check constraint in Oracle and in PostgreSQL.
I can obtain all the check constraints in a table, but I want to obtain only this specific check constraint, I don't know if there is any specific query.
Thanks!
In PostgreSQL there is a System Catalog pg_constraint.
The catalog pg_constraint stores check, primary key, unique, foreign
key, and exclusion constraints on tables. (Column constraints are not
treated specially. Every column constraint is equivalent to some table
constraint.) Not-null constraints are represented in the pg_attribute
catalog, not here.
User-defined constraint triggers (created with CREATE CONSTRAINT
TRIGGER) also give rise to an entry in this table.
Check constraints on domains are stored here, too.
SELECT
*
FROM
pg_constraint
WHERE
contype = 'c' AND -- check constraint
conrelid != 0 AND -- table constraint
conname = 'my_check';
The contype column contains the constraint type, c is for check constraint.
The conrelid column contains the oid of the table this constraint is on, 0 if not a table constraint.
For Oracle basic view is ALL_CONSTRAINTS
Query, to obtain specific constraint in specific table:
SELECT *
FROM all_constraints
WHERE constraint_name LIKE upper('%&your_costraint%')
AND table_name LIKE upper('%&your_table%');
In Oracle, if you try to explicitly define the schema for a constraint in a CREATE TABLE statement it will result in a ORA-00904: : invalid identifier error:
CREATE TABLE SCHEMA1.MY_TABLE
(
TABLE_ID NUMBER(5)
, FLAG VARCHAR2(1) DEFAULT 'F'
, CONSTRAINT SCHEMA1.MY_TABLE_PK PRIMARY KEY (TABLE_ID) -- Parser doesn't like 'SCHEMA1'
, CONSTRAINT SCHEMA1.MY_TABLE_FLAG_CK CHECK (FLAG IN ('T', 'F')) --Same issue
);
This is no big deal because the constraint OWNER defaults to the same schema as defined in the CREATE TABLE declaration (or at least in the schema you are signed into - my accounts don't have the rights to validate). This can be confirmed by pulling up the constraint in ALL_CONSTRAINTS or DBA_CONSTRAINTS and viewing the OWNER value (which would read SCHEMA1 for the two constraints above).
But if you then follow up this statement with a second duplicate statement under a different schema:
CREATE TABLE SCHEMA2.MY_TABLE
(
TABLE_ID NUMBER(5)
, FLAG VARCHAR2(1) DEFAULT 'F'
, CONSTRAINT MY_TABLE_PK PRIMARY KEY (TABLE_ID) --This constraint already exists
, CONSTRAINT MY_TABLE_FLAG_CK CHECK (FLAG IN ('T', 'F')) --This one too
);
this results in an ORA-00955: name is already used by an existing object error.
My understanding of constraints are that they are just another object on the database which I would have assumed were subject to the same ownership rules with which I'm familiar. But based on the behavior above it is clear that they do not behave like most objects on the database.
Questions
What is it about constraints that requires their names be unique across all schemas (unlike other objects on the database)?
Does anyone know the technical reason for this naming requirement?
For context, I've run into a scenario at work where I had wanted to store duplicate names under different schemas (don't ask... it was inherited duplication and I'm just trying to stay consistent until I have funding to refactor). Now, I realize that I can very simply add the schema to the name and bypass this problem quickly but this rubs my OCD the wrong way so I'd like to better understand just why I can't do what I'm trying to do.
----------------------------- UPDATE ---------------------------
Okay... so I'm a fool. Please note that the above scenario cannot be repeated given a clean environment. After trying to reproduce the issue, I now realize what happened.
I'm currently working on cleaning up some DDL statements in preparation for a production release. I'm not the only developer in this environment and my offshore team has been working on these same tables. I have been editing some preexisting DDL scripts in preparation for a production release and had added some needed constraints to a few CREATE TABLE statements.
It would appear that I had failed to run my DROP scripts before running the second statement in SCHEMA2. My confusion was due to thinking that I was getting the ORA-00955 error because of the new constraints I was adding when in actuality it was because the SCHEMA2.MY_TABLE already existed in this environment. This misdiagnosis was compounded by me changing my constraint names and then rerunning all of my scripts successfully (as I must have run my DROP statements in all schemas before retesting). As a result I thought that I had observed unforeseen behavior when I really had not.
Thank you to everyone who commented for showing me the light!
What's missing in your question is the user under which you run the script. But here's a little experiment.
Connected to the database as user system. I have schemas NGM42 and NGM41 available for the experiment.
CREATE TABLE NGM41.MY_TABLE
(
TABLE_ID NUMBER(5)
, FLAG VARCHAR2(1) DEFAULT 'F'
, CONSTRAINT MY_TABLE_PK PRIMARY KEY (TABLE_ID) -- Parser doesn't like 'SCHEMA1'
, CONSTRAINT MY_TABLE_FLAG_CK CHECK (FLAG IN ('T', 'F')) --Same issue
);
CREATE TABLE NGM42.MY_TABLE
(
TABLE_ID NUMBER(5)
, FLAG VARCHAR2(1) DEFAULT 'F'
, CONSTRAINT MY_TABLE_PK PRIMARY KEY (TABLE_ID)
, CONSTRAINT MY_TABLE_FLAG_CK CHECK (FLAG IN ('T', 'F'))
);
Both statements run succesfully. So what happened to the constraints?
select owner,constraint_name from all_constraints
where constraint_name in ('MY_TABLE_PK','MY_TABLE_FLAG_CK')
NGM42 MY_TABLE_PK
NGM41 MY_TABLE_PK
NGM41 MY_TABLE_FLAG_CK
NGM42 MY_TABLE_FLAG_CK
The constraints are created in the same schema as the table. As you can see they do not need to be globally unique in the database.
I have a oracle query as -
occupation varchar2(50) CHECK(occupation IN ('student','govt_service','private','business')));
now i need to remove the check constraint so i use the following query-
ALTER TABLE registration drop constraint occupation;
but since i haven't defined the constraint name it says invalid constraint name. Is there any way to delete the constraint ? I guess i can alter the table and add the name of the constraint, then delete it but is there any other way ?
run this query:
select * from all_constraints where table_name = 'REGISTRATION';
And you'll find the constraint name.
EDIT: I also recommend you to have a table Occupations and replace the current constraint with a foreign key. (If you are already want to do this, pls apologize me ). Further, normalising, the Occupations may have IDs and and the foreign should be defined on these ids.
Try querying USER_CONSTRAINTS table for CONSTRAINT_NAME, it must have generated a system name for the constraint you have created.
select * from USER_CONSTRAINTS
where owner='<your_schema>' and CONSTRAINT_TYPE='C';
I have a database which has a NOT NULL constraint on a field, and I want to remove this constraint. The complicating factor is that this constraint has a system-defined name, and that constraint's name differs between the production server, integration server, and the various developer databases. Our current process is to check in change scripts, and an automated task executes the appropriate queries through sqlplus against the target database, so I'd prefer a solution that could just be sent straight into sqlplus.
On my own database, the SQL to drop this would be:
alter table MYTABLE drop constraint SYS_C0044566
I can see the constraint when I query the all_constraints view:
select * from all_constraints where table_name = 'MYTABLE'
but I am not sure how to work with the SEARCH_CONDITION's LONG data type or how best to dynamically delete the looked-up constraint even after I know its name.
So, how can I create a change script that can drop this constraint based on what it is, rather than what its name is?
EDIT:
#Allan's answer is a good one, but I am concerned (in my lack of Oracle expertise) that it may not be universally true that any constraint that might have a system-generated name will have associated with it a way to remove the constraint without having to know its name. Is it true that there will always be a way to avoid having to know a system-named constraint's name when logically dropping that constraint?
alter table MYTABLE modify (MYCOLUMN null);
In Oracle, not null constraints are created automatically when not null is specified for a column. Likewise, they are dropped automatically when the column is changed to allow nulls.
Clarifying the revised question: This solution only applies to constraints created for "not null" columns. If you specify "Primary Key" or a check constraint in the column definition without naming it, you'll end up with a system-generated name for the constraint (and the index, for the primary key). In those cases, you'd need to know the name to drop it. The best advice there is to avoid the scenario by making sure you specify a name for all constraints other than "not null". If you find yourself in the situation where you need to drop one of these constraints generically, you'll probably need to resort to PL/SQL and the data-definition tables.
Try:
alter table <your table> modify <column name> null;
Just remember, if the field you want to make nullable is part of a primary key, you can't.
Primary Keys cannot have null fields.
To discover any constraints used, use the code below:
-- Set the long data type for display purposes to 500000.
SET LONG 500000
-- Define a session scope variable.
VARIABLE output CLOB
-- Query the table definition through the <code>DBMS_METADATA</code> package.
SELECT dbms_metadata.get_ddl('TABLE','[Table Described]') INTO :output FROM dual;
This essentially shows a create statement for how the referenced table is made. By knowing how the table is created, you can see all of the table constraints.
Answer taken from Michael McLaughlin's blog: http://michaelmclaughlin.info/db1/lesson-5-querying-data/lab-5-querying-data/ From his Database Design I class.
I was facing the same problem trying to get around a custom check constraint that I needed to updated to allow different values. Problem is that ALL_CONSTRAINTS does't have a way to tell which column the constraint(s) are applied to. The way I managed to do it is by querying ALL_CONS_COLUMNS instead, then dropping each of the constraints by their name and recreate it.
select constraint_name
from all_cons_columns
where table_name = [TABLE_NAME]
and column_name = [COLUMN_NAME];
Something like that happened to me when I made copies of structures to temporary tables, so I removed the not null.
DECLARE
CURSOR cur_temp_not_null IS
SELECT table_name, constraint_name FROM all_constraints WHERE table_name LIKE 'TEMP_%' AND owner='myUSUARIO';
V_sql VARCHAR2(200);
BEGIN
FOR c_not_null IN cur_temp_not_null
LOOP
v_sql :='ALTER TABLE ' || c_not_null.table_name || ' DROP CONSTRAINT '|| c_not_null.constraint_name;
EXECUTE IMMEDIATE v_sql;
END LOOP;
END;
If constraint on column STATUS was created without a name during creating a table, Oracle will assign a random name for it. Unfortunately, we cannot modify the constraint directly.
Steps involved of dropping unnamed constraint linked to column STATUS
Duplicate STATUS field into a new field STATUS2
Define CHECK constraints on STATUS2
Migrate data from STATUS into STATUS2
Drop STATUS column
Rename STATUS2 to STATUS
ALTER TABLE MY_TABLE ADD STATUS2 NVARCHAR2(10) DEFAULT 'OPEN';
ALTER TABLE MY_TABLE ADD CONSTRAINT MY_TABLE_CHECK_STATUS CHECK (STATUS2 IN ('OPEN', 'CLOSED'));
UPDATE MY_TABLE SET STATUS2 = STATUS;
ALTER TABLE MY_TABLE DROP COLUMN STATUS;
ALTER TABLE MY_TABLE RENAME COLUMN STATUS2 TO STATUS;