Sub topic 13
Inspecting constraints and identity columns in the data dictionary
Oracle records every table, constraint, and identity column in the data dictionary. The dictionary is a set of read-only views that you query with ordinary SELECT statements. This chapter shows how to check what a table enforces, which constraints are disabled, and which sequence feeds an identity column.
This chapter assumes you can write SELECT queries with joins and GROUP BY. It also assumes you have created the departments and employees tables from earlier chapters in your own schema.
Choosing a dictionary view family
Each dictionary view comes in three prefixes:
| Prefix | Shows | Needs |
|---|---|---|
| `USER_` | Objects your schema owns | Nothing extra |
| `ALL_` | Objects you own or have been granted access to | Nothing extra |
| `DBA_` | Every object in the database | A privilege such as `SELECT_CATALOG_ROLE` |
ALL_ and DBA_ views add an OWNER column. Without it, two schemas can have tables with the same name and you cannot tell the rows apart. This chapter uses the USER_ views, so no owner filter is needed.
Object names are stored in uppercase unless you created them with double quotes. Filter with table_name = 'EMPLOYEES', not 'employees'.
The views used here relate to each other as follows.
Listing the constraints on a table
USER_CONSTRAINTS has one row per constraint. This is the query from the chapter's examples:
SELECT constraint_name, constraint_type, status, validated
FROM user_constraints
WHERE table_name = 'EMPLOYEES'
ORDER BY constraint_name;The columns you will use most are:
CONSTRAINT_NAME: the name you chose, or a system-generated name such asSYS_C0012345.CONSTRAINT_TYPE: a one-letter code, listed in the next table.STATUS:ENABLEDorDISABLED.VALIDATED:VALIDATEDorNOT VALIDATED.DEFERRABLEandDEFERRED: whether the check can wait until commit, and whether it currently does.DELETE_RULE: for foreign keys,CASCADE,SET NULL, orNO ACTION.INDEX_NAME: for primary key and unique constraints, the index that enforces them.GENERATED:USER NAMEorGENERATED NAME.
| Code | Constraint |
|---|---|
| `P` | Primary key |
| `U` | Unique |
| `R` | Foreign key (referential) |
| `C` | Check, including `NOT NULL` |
| `V` | Check option on a view |
| `O` | Read-only on a view |
NOT NULL is stored as a check constraint, so it appears with type C. A column declared email VARCHAR2(255) NOT NULL with no name gets a row like SYS_C0012346. Its SEARCH_CONDITION is "EMAIL" IS NOT NULL.
Reading check conditions
SEARCH_CONDITION is a LONG column. You can display it, but you cannot use it in a WHERE clause with LIKE. From Oracle Database 12.2 on, SEARCH_CONDITION_VC holds the same text as a VARCHAR2:
SELECT constraint_name, search_condition_vc
FROM user_constraints
WHERE table_name = 'EMPLOYEES'
AND constraint_type = 'C'
AND search_condition_vc NOT LIKE '%IS NOT NULL'
ORDER BY constraint_name;This returns only the real CHECK rules, employees_salary_ck and employees_status_ck, and leaves out the NOT NULL rows.
Finding constrained columns
USER_CONSTRAINTS does not list columns. Join to USER_CONS_COLUMNS, which has one row per column in each constraint. POSITION gives the order in a composite key and is NULL for check constraints.
SELECT c.constraint_name,
c.constraint_type,
LISTAGG(cc.column_name, ', ')
WITHIN GROUP (ORDER BY cc.position) AS columns_list
FROM user_constraints c
JOIN user_cons_columns cc
ON cc.constraint_name = c.constraint_name
AND cc.table_name = c.table_name
WHERE c.table_name = 'EMPLOYEES'
GROUP BY c.constraint_name, c.constraint_type
ORDER BY c.constraint_type, c.constraint_name;Constraint names are unique within a schema, but joining on table_name as well is a cheap safeguard.
Tracing a foreign key to its parent
A foreign key row has CONSTRAINT_TYPE = 'R'. Its R_CONSTRAINT_NAME is the name of the primary key or unique constraint it references. Join USER_CONSTRAINTS to itself to find the parent table:
SELECT c.constraint_name,
cc.column_name AS child_column,
p.table_name AS parent_table,
p.constraint_name AS parent_constraint,
c.delete_rule
FROM user_constraints c
JOIN user_cons_columns cc
ON cc.constraint_name = c.constraint_name
AND cc.table_name = c.table_name
JOIN user_constraints p
ON p.constraint_name = c.r_constraint_name
WHERE c.constraint_type = 'R'
AND c.table_name = 'EMPLOYEES'
ORDER BY c.constraint_name;For employees_dept_fk, delete_rule is SET NULL. Oracle has no ON UPDATE action, so the dictionary has no column for one. NO ACTION means you declared no ON DELETE clause. Deleting a parent that still has children then fails with ORA-02292.
To go the other way and find the children of a table, filter on p.table_name. Do this before dropping or truncating a parent table.
Finding generated names and unhealthy constraints
Two queries are worth keeping. The first finds constraints with system-generated names. These make error messages harder to read, and the name can differ between environments:
SELECT table_name, constraint_name, constraint_type
FROM user_constraints
WHERE generated = 'GENERATED NAME'
ORDER BY table_name, constraint_name;The second finds constraints that are not fully enforced. It catches anything left disabled or enabled without validation after a data load:
SELECT table_name, constraint_name, constraint_type,
status, validated, deferrable, deferred
FROM user_constraints
WHERE status = 'DISABLED'
OR validated = 'NOT VALIDATED'
OR deferrable = 'DEFERRABLE'
ORDER BY table_name, constraint_name;After the ALTER TABLE statements from the previous chapter, employees_manager_fk shows DEFERRABLE and DEFERRED. While it is disabled, STATUS is DISABLED. A constraint that is ENABLED and NOT VALIDATED checks new changes but has not checked the rows that were already in the table.
Inspecting identity columns
USER_TAB_IDENTITY_COLS has one row per identity column:
SELECT table_name, column_name, generation_type, sequence_name
FROM user_tab_identity_cols;GENERATION_TYPEisALWAYSorBY DEFAULT.SEQUENCE_NAMEis the system-managed sequence, named likeISEQ$$_73215.IDENTITY_OPTIONSis a single text string. It contains the start value, increment, minimum and maximum, cycle flag, cache size, and order flag.
Telling BY DEFAULT from BY DEFAULT ON NULL
Both BY DEFAULT and BY DEFAULT ON NULL appear as BY DEFAULT in GENERATION_TYPE. The ON NULL part is stored on the column definition. Read it from USER_TAB_COLUMNS:
SELECT i.table_name,
i.column_name,
i.generation_type,
c.default_on_null,
i.sequence_name
FROM user_tab_identity_cols i
JOIN user_tab_columns c
ON c.table_name = i.table_name
AND c.column_name = i.column_name
ORDER BY i.table_name, i.column_name;For employees.employee_id you get BY DEFAULT with DEFAULT_ON_NULL = YES. For departments.department_id you get ALWAYS with NO. USER_TAB_COLUMNS also has an IDENTITY_COLUMN flag, which is useful when you list all columns of a table and want to see which one is generated.
Looking at the backing sequence
The sequence behind an identity column is a real sequence. Its settings are in USER_SEQUENCES:
SELECT s.sequence_name, s.increment_by, s.cache_size, s.last_number
FROM user_sequences s
WHERE s.sequence_name IN (SELECT sequence_name
FROM user_tab_identity_cols);Gaps in identity values are normal. A rolled-back insert and a restart of the instance both consume numbers. If you see gaps in employee_id, they do not mean rows were lost.
Common mistakes
- Querying with lowercase names.
WHERE table_name = 'employees'returns no rows. A query that returns nothing does not mean the table has no constraints. - Expecting
NOT NULLto be absent fromUSER_CONSTRAINTS. It is there as typeC. Filter it out withSEARCH_CONDITION_VCif you only want business rules. - Using
USER_views from another schema. You only see your own objects. Switch toALL_and addowner = 'HR'(or the schema you want). - Trusting
ENABLEDalone. Also checkVALIDATED. A table can contain old rows that break a rule the constraint now enforces. - Reading
ON NULLfromGENERATION_TYPE. It is not shown there. UseDEFAULT_ON_NULL.
Exercise
Write a query that lists every foreign key in your schema that has no ON DELETE action, showing the child table, the constraint name, and the parent table.
Show answer
SELECT c.tablename AS childtable, c.constraintname, p.tablename AS parenttable FROM userconstraints c JOIN userconstraints p ON p.constraintname = c.rconstraintname WHERE c.constrainttype = 'R' AND c.deleterule = 'NO ACTION' ORDER BY c.tablename, c.constraintname; Foreign keys declared without an ON DELETE clause have DELETE_RULE = 'NO ACTION'. Deleting a parent row that still has children then fails with ORA-02292.
Exercise
Which two dictionary views do you need to tell whether employees.employee_id is GENERATED ALWAYS, BY DEFAULT, or BY DEFAULT ON NULL, and which column in each view holds the answer?
Show answer
USERTABIDENTITYCOLS has GENERATIONTYPE, which is ALWAYS or BY DEFAULT. USERTABCOLUMNS has DEFAULTONNULL, which is YES when ON NULL was specified. BY DEFAULT with DEFAULTONNULL = YES means BY DEFAULT ON NULL.
Exercise
A load script finished, and you suspect a constraint was left in a weak state. Which query finds constraints that are disabled or that were enabled without checking existing rows?
Show answer
SELECT tablename, constraintname, status, validated FROM user_constraints WHERE status = 'DISABLED' OR validated = 'NOT VALIDATED'; STATUS = 'DISABLED' means the rule is not enforced at all. VALIDATED = 'NOT VALIDATED' means existing rows were never checked against it.