当前位置:网站首页>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

  1. by Person Add a table named PERSON_PID_PK, The primary key is ID Constraints
ALTER TABLE PERSON ADD CONSTRAINT PERSON_PID_PK PRIMARY KEY(ID);
  1. by Person Tabular NAME Add a field named PERSON_NAME_UK The only constraint
ALTER TABLE PERSON ADD CONSTRAINT PERSON_NAME_UK UNIQUE(NAME);
  1. by Person Tabular Age Add a field named PERSON_AGE_CK Check constraints for
ALTER TABLE PERSON ADD CONSTRAINT PERSON_AGE_CK CHECK(AGE BETWEEN 0 AND 150);
  1. by Book In the table PID Field addition and Person Master of table - Foreign key constraints , be known as PERSON_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');

 Insert picture description here

CONSTRAINT_TYPEUSE
CCheck on a table Column( Check constraint )
ORead Only on a view Object( Read only constraints )
PPrimary Key Object( Primary key constraint )
RReferential AKA Foreign Key Column( Foreign key constraints )
UUnique Key Column( Unique constraint )
VCheck 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';

 Insert picture description here

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 :
 Insert picture description here
   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

  1. 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 .

  1. Index classification

   Indexes fall into two broad categories , Uniqueness index And Non unique index .

  1. 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 :

  1. It greatly speeds up the data retrieval speed .
  2. Create a unique index , Ensure the uniqueness of each row of data in the database table .
  3. Accelerate the connection between tables .
  4. When using grouping and sorting words for data retrieval , It can significantly reduce the time of grouping and sorting in queries .

Disadvantages of indexes :

  1. Index needs to be occupied Physical space .
  2. 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 .

  1. stay SELECT Create an index on a table where operations are the majority .
  2. stay WHERE Create an index on the column that appears most frequently in a sentence .
  3. Create an index on the column with the highest selection query ( Supplementary index selectivity , Is the highest 1,eg:primary key).
  4. The main column of the composite index should be the most selective and WHERE The 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 .

  1. 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 .

  1. 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 NULLIS NOT NULLNOT IN!=LIKENUMERIC_COL+0DATE_COL+0CHAR_COL || ''TO_CHARTO_DATETO_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

原网站

版权声明
本文为[The head is really heavy y]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202221357068823.html