当前位置:网站首页>Indexes, constraints and views in Oracle Database
Indexes, constraints and views in Oracle Database
2022-06-21 14:45:00 【The head is really heavy y】
constraint , It refers to various restrictions on inserting data , for example : The person's name cannot be empty 、 The age of a person can only be 0~150 Between the ages of 、 Constraints can protect the data in the database 、 standard .
Constraints can be declared directly when creating tables , You can also add constraints to the created tables .
One 、 constraint
1) Non empty constraint
CREATE TABLE TEST
(
ID VARCHAR2(36) NOT NULL, // This field cannot be empty
NAME VARCHAR2(200)
)
/
INSERT INTO TEST(NAME) VALUES ('jane'); // [23000][1400] ORA-01400: Cannot be NULL Insert ("SNOW_ZY"."TEST"."ID")
2) Primary key constraint
CREATE TABLE TEST
(
ID VARCHAR2(36) PRIMARY KEY, // Can't repeat 、 Can't be empty
NAME VARCHAR2(200)
)
/
INSERT INTO TEST(ID, NAME) VALUES ('123', 'jane');
INSERT INTO TEST(ID, NAME) VALUES ('123', 'jane'); // [23000][1] ORA-00001: Violate the only constraint (SNOW_ZY.SYS_C00124287)
3) Unique constraint
CREATE TABLE TEST
(
ID VARCHAR2(36) UNIQUE, // Value cannot be duplicate ( Except for null values )
NAME VARCHAR2(200)
)
/
INSERT INTO TEST(ID, NAME) VALUES ('123', 'jane');
INSERT INTO TEST(ID, NAME) VALUES ('123', 'jane'); // [23000][1] ORA-00001: Violate the only constraint (SNOW_ZY.SYS_C00124287)
4) Conditionality
CREATE TABLE TEST
(
ID VARCHAR2(36),
NAME VARCHAR2(200),
AGE NUMBER CHECK ( AGE BETWEEN 0 AND 150) // The inserted data must meet certain conditions
)
/
INSERT INTO TEST(ID, NAME, AGE) VALUES ('123', 'jane', 100);
INSERT INTO TEST(ID, NAME, AGE) VALUES ('123', 'jane', 200); // [23000][2290] ORA-02290: Violation of inspection constraints (SNOW_ZY.SYS_C00124289)
5) Foreign keys (references : Reference resources 、 prove )
CREATE TABLE PERSON
(
ID VARCHAR2(36) PRIMARY KEY ,
NAME VARCHAR2(200)
)
/
INSERT INTO PERSON(ID, NAME) VALUES ('123', 'jane');
INSERT INTO PERSON(ID, NAME) VALUES ('456', 'kobe');
CREATE TABLE BOOK
(
BID VARCHAR2(36),
BNAME VARCHAR2(200),
PID VARCHAR2(36) REFERENCES PERSON(ID) -- Books belong to only one person , When inserting this value, go back to the parent table to query whether there is a corresponding record
-- Establish constraints : book_pid_fk, And person Medium pid Form master + Foreign key relationships
--CONSTRAINT b00k_pid_fk FOREIGN KEY(PID) REFERENCES PERSON(ID)
)
/
INSERT INTO BOOK(BID, BNAME, PID) VALUES ('000', ' The kite runner ', '123');
INSERT INTO BOOK(BID, BNAME, PID) VALUES ('001', ' Relief grocery store ', '111'); // [23000][2291] ORA-02291: Violation of full constraints (SNOW_ZY.SYS_C00124291) - Parent key not found
6) cascading deletion
Connect , There is already Person Table and Book surface , And Book In the table PID Fields and Person Tabular ID Foreign key relationships are established , Suppose now Person A record in the table disappeared , This is the time PID stay Book The row in the table should also disappear .
DELETE FROM PERSON WHERE ID = '123'; // [23000][2292] ORA-02292: Violation of full constraints (SNOW_ZY.SYS_C00124293) - Subrecord found
Delete Person A row record of a table , You will be prompted that the child record has been found , Because in book Of the person in the table id It's been used , So when you want to delete this person , Should be in the first place book Delete the person's book information in .、
If you want to finish deleting person Data in the table , At the same time book This... Is used in the table id Delete the records of , You need to use cascading deletion (ON DELETE CASCADE).
CREATE TABLE BOOK
(
BID VARCHAR2(36),
BNAME VARCHAR2(200),
PID VARCHAR2(36),
-- Establish constraints : book_pid_fk, And person Medium pid Form master + Foreign key relationships
CONSTRAINT b00k_pid_fk FOREIGN KEY(PID) REFERENCES PERSON(ID) ON DELETE CASCADE // cascading deletion , Delete the primary key , Records that use this primary key as a foreign key will also be deleted synchronously
)
/
INSERT INTO BOOK(BID, BNAME, PID) VALUES ('000', ' The kite runner ', '123');
DELETE FROM PERSON WHERE ID = '123'; //Person In the table ID=123 The record of was deleted , book In the table PID=123 The record of was deleted
7) Statement to add constraints
- by Person Add a table named
PERSON_PID_PK, The primary key isIDConstraints
ALTER TABLE PERSON ADD CONSTRAINT PERSON_PID_PK PRIMARY KEY(ID);
- by Person Tabular
NAMEAdd a field namedPERSON_NAME_UKThe only constraint
ALTER TABLE PERSON ADD CONSTRAINT PERSON_NAME_UK UNIQUE(NAME);
- by Person Tabular
AgeAdd a field namedPERSON_AGE_CKCheck constraints for
ALTER TABLE PERSON ADD CONSTRAINT PERSON_AGE_CK CHECK(AGE BETWEEN 0 AND 150);
- by Book In the table
PIDField addition and Person Master of table - Foreign key constraints , be known asPERSON_BOOK_FK, Cascade deletion is required
ALTER TABLE BOOK ADD CONSTRAINT PERSON_BOOK_FK FOREIGN KEY (PID) REFERENCES PERSON(PID) ON DELETE CASCADE;
8) Delete constraints
ALTER TABLE BOOK DROP CONSTRAINT B00K_PID_FK; -- Constraints are deleted directly
9) Forbid / Enable constraints
ALTER TABLE BOOK DISABLE CONSTRAINT B00K_PID_FK; -- Constraints are disabled , But constraints still exist
ALTER TABLE BOOK ENABLE CONSTRAINT B00K_PID_FK; -- Enable constraints , The premise is that all the data in the table meet the constraint conditions
10) View the constraints in the table
SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE FROM ALL_CONSTRAINTS WHERE TABLE_NAME = UPPER('BOOK');

| CONSTRAINT_TYPE | USE |
|---|---|
| C | Check on a table Column( Check constraint ) |
| O | Read Only on a view Object( Read only constraints ) |
| P | Primary Key Object( Primary key constraint ) |
| R | Referential AKA Foreign Key Column( Foreign key constraints ) |
| U | Unique Key Column( Unique constraint ) |
| V | Check Option on a view Object( View constraints ) |
Two 、 View
View : It is a statement that encapsulates various complex queries , It's called a view .
1) Create view
CREATE OR REPLACE VIEW EMP(EMP00, EMP01) AS (SELECT EMP00, EMP01 FROM EMPLOYEE);
2) View view
SELECT TEXT FROM USER_VIEWS WHERE VIEW_NAME = 'EMP';

3) Modify the view
Views created by default , If it's updated , This data will be automatically deleted from the view , Then the original data will be updated .
UPDATE EMP SET EMP.EMP01=' Zhou Kang 2' WHERE EMP00='7350F9DE-F5BC-461A-B499-F86680D2DA4E'; --EMP View vs EMPLOYEE The data in the table has been modified
Although the view can be modified to achieve the purpose of modifying database data , But there are still hidden dangers . It is better not to update the view .
4) View protection mechanism
When creating views , You can specify two parameters , Protection view creation rules :WITH CHECK OPTION; View is read-only :WITH READ ONLY
--1. Protection view creation rules
CREATE OR REPLACE VIEW EMP(EMP00, EMP01) AS SELECT EMP00, EMP01 FROM EMPLOYEE
WHERE EMP00='7350F9DE-F5BC-461A-B499-F86680D2DA4E' WITH CHECK OPTION CONSTRAINT EMP_CK;
The view is :
At this point, if you want to update EMP00, Will report a mistake , because EMP00 Is to create views WHERE Field , Protected , So it can't be modified , But it can be modified EMP01;
UPDATE EMP SET EMP.EMP00='7350F9DE-F5BC-461A-B499-F86680D2DA4A' WHERE EMP00='7350F9DE-F5BC-461A-B499-F86680D2DA4E';
--[44000][1402] ORA-01402: View WITH CHECK OPTION where Clause violation
UPDATE EMP SET EMP.EMP01=' Zhou Kang 3' WHERE EMP00='7350F9DE-F5BC-461A-B499-F86680D2DA4E'; -- Normal execution
--2. Read only view
CREATE OR REPLACE VIEW EMP(EMP00, EMP01) AS SELECT EMP00, EMP01 FROM EMPLOYEE
WHERE EMP00='7350F9DE-F5BC-461A-B499-F86680D2DA4E' WITH READ ONLY; -- All fields of the view cannot be modified
UPDATE EMP SET EMP.EMP01=' Zhou Kang 3' WHERE EMP00='7350F9DE-F5BC-461A-B499-F86680D2DA4E';
--[99999][42399] ORA-42399: Cannot execute... On read-only view DML operation
3、 ... and 、 Indexes
- What is index (Index)
Index is a method to improve query efficiency Database objects . By quickly locating data , To reduce the number of disks I/O operation . Index information and tables are stored separately , also Oracle Database automatically uses and maintains indexes .
- Index classification
Indexes fall into two broad categories , Uniqueness index And Non unique index .
- How indexes are created
① Automatically create : When defining primary key or unique key constraints , The system will automatically create a unique index on the corresponding field .
② Manually create : Users can create non unique indexes on other columns , To improve query efficiency .
1) Index advantages and disadvantages
Advantages of indexing :
- It greatly speeds up the data retrieval speed .
- Create a unique index , Ensure the uniqueness of each row of data in the database table .
- Accelerate the connection between tables .
- When using grouping and sorting words for data retrieval , It can significantly reduce the time of grouping and sorting in queries .
Disadvantages of indexes :
- Index needs to be occupied Physical space .
- When adding, deleting, modifying, and querying the data in the table , At the same time, it also needs to maintain the index dynamically , Reduce the speed of data maintenance .
2) Principles for creating and using indexes
Create index : Indexes are generally created for two purposes , Maintain uniqueness of indexed columns and provide quick access to data in tables . Less than 5M Table of , It is best not to use indexes to query , The smaller the watch , It is more suitable to scan the whole table .
- stay
SELECTCreate an index on a table where operations are the majority . - stay
WHERECreate an index on the column that appears most frequently in a sentence . - Create an index on the column with the highest selection query ( Supplementary index selectivity , Is the highest 1,eg:primary key).
- The main column of the composite index should be the most selective and
WHEREThe most commonly used columns for qualification , And so on the second column .
Use index : The query result is the result of all data rows 5% Following time , Use index The query effect is the best .WHERE When multiple columns of a table are often used in conditions , Using a composite index will work better than several single column indexes , Because when sql The column queried by the , All appear in the composite index , At this time due to oracle Just query the index block to get all the data , Of course, it is much faster than using multiple single column indexes . The index is good for SELECT, But often Add, replace and delete Your watch will reduce efficiency .
- The difference between using and not using indexes
SELECT EMP00, EMP01 FROM EMPLOYEE WHERE EMP00 NOT IN (SELECT EMP00 FROM EMP) -- sentence A
SELECT EMP00, EMP01 FROM EMPLOYEE WHERE NOT EXIST (SELECT EMP00 FROM EMP WHERE EMPLOYEE.EMP00 = EMP.EMP00) -- sentence B
These two sql The result of statement implementation is the same , But when the amount of data is very large , The execution efficiency of the two statements will be much lower . In execution A When ,Oracle It will be for the whole EMP Scan the table , Will not use built on EMP Upper EMP00 Indexes , perform B When , Because the union query is used in the subquery ,Oracle Just for EMP Table for partial data scanning , And used EMP00 Column index , therefore B Is more efficient than A high .
- Notes on composite indexes , And implicit writing of invalid indexes
WHERE The field in the sentence , Must be the first field of the composite index . An index is based on f1, f2, f3 Established in the order of , If WHERE The words are f2 = val2, Because of f2 Is not the first field of the index, so the index cannot be used .
WHERE The field in the sentence , Should not participate in any form of calculation , Any operation on a column will result in a table scan , It includes database functions 、 Calculating expressions, etc , When querying, try to move the operator to the right of the equal sign . The following operator will appear to block oracle Use index :IS NULL、IS NOT NULL、NOT IN、!=、LIKE、NUMERIC_COL+0、DATE_COL+0、CHAR_COL || ''、TO_CHAR、TO_DATE、TO_NUMBER etc. .
SELECT EMP01 FROM EMPLOYEE WHERE EMP02 = '0' AND TO_DATE(UPDATETIME) > to_DATE('2022-01-01', 'YYYY-MM-DD');
--UPDATETIME The index of the column will fail
3) establish \ Delete index
CREATE INDEX ABC ON EMPLOYEE(EMP00, EMP01);
CREATE INDEX CBA ON EMPLOYEE(EMP01, EMP00);
Indexes ABC And CBA It's different , Indexes ABC about WHERE EMP00 = '1' Such query statements are more effective , and CBA The index is for WHERE EMP01 = ' Zhou Kang ' Such query statements are more effective . So when indexing , The combination order of fields is very important , Generally, the fields that need to be accessed frequently are placed in front of the composite index fields .
DROP INDEX ABC; -- Delete index
4) Look at the index
SELECT * FROM USER_INDEXES; -- Query existing indexes
SELECT * FROM USER_IND_COLUMNS; -- The available indexes are built on those fields
Note that both indexes and tables exist independently , When specifying a tablespace for an index , Do not point the indexed table and index to the same tablespace , This can avoid the occurrence of IO Conflict . send oracle It can access index data and table data stored in different hard disks in parallel , Better improve query speed .
5) Index type
6) Manage index
边栏推荐
- Clickhouse cluster installation has too many dry goods
- 100% troubleshooting and analysis of Alibaba cloud hard disk
- Application GDB debugging
- Use OpenCV to decompose the video into single frame pictures and synthesize the video with pictures
- Mr. Ali taught you how to use JMeter for pressure test (detailed drawing)
- Win10 installation and configuration mongodb
- Summary of statistical learning methods
- Dplayer development barrage background
- T32 add toolbar button
- USB message capture tcpdump
猜你喜欢

Word thesis typesetting tutorial

Two of my essays

So many statistical charts? This visualizer is great~~

Pyqt5 learning notes of orange_ Basic structure of pyqt5 GUI program

Sliding validation tool class

Qt-5-multi window programming
![NPM package management configuration file [package.json and node\u modules configuration details and how to develop their own packages and publish them on NPM]](/img/ff/2b92de728494542f614d4d5a57d20c.jpg)
NPM package management configuration file [package.json and node\u modules configuration details and how to develop their own packages and publish them on NPM]

Record the processing process of slow response of primary system

Record the troubleshooting process of excessive CPU usage

Read distributed consistency protocols 2pc and 3pc
随机推荐
Pyqt environment in pycharm
!!** The test is valid * *:vscode "the terminal will be reused by the task, press any key to close" /vscode the terminal runs NPM to pop up the select program dialog box / try a new cross platform Pow
Fundamentals of C language 13: file input / output
Chapter 5 - application layer
JS written test question: this
Qt-3-basic assembly 2
Mysql5.7 setup password and remote connection
Chart. JS 2.0 doughnut tooltip percentage - chart js 2.0 doughnut tooltip percentages
Compile time annotation
Three questions for learning new things
Write a compile time annotation
Viewing tcp/ip network communication from the sending of an email
2022 Fujian latest fire protection facility operator simulation test question bank and answers
Machine learning model training template
Solution of difficult and miscellaneous problems in MVN packaging
Chapter 2 - physical layer (I)
Nmap scan port tool
Redis introduction and Practice (with source code)
[font multi line display ellipsis] and [dialog box] implementation ----- case explanation, executable code
Office operation sorting notes