oracle database (three)

One, build a table (DDL)

  • create table 表名(

    ​ Field name 1 data type [default value] [constraint],

    ​ Field name 2 data type [default value],

    ​ Field name 3 data type [default value] [constraint]

    );

    Note: no comma in the last field

  1. Identifier naming rules:

    (1) It is composed of letters, numbers, _ (underscore), $, #, and cannot start with a number

    (2) There is a length limit, up to 30 characters

    (3) Not case sensitive

    (4) It cannot be a keyword or the same name as other objects

  2. type of data

    (1) Number type:

    • number(m,n): decimal type, the total length of the data is m, where the number of digits after the decimal point is n (the number of digits exceeds n, rounding off)

      number(5,2): 123.45 can be stored; 123.4567 can be stored, and the final storage content is 123.46; 1234.5 can’t be stored, and the number of integers is up to 3

    • number(m): integer type, the data length is m

      • number(5): 123 can be stored; 12345 can be stored; 123456 can not be stored, the maximum length is exceeded
    • number: The default decimal type, the maximum data that the database can store, equivalent to double in Java.

    • integer: equivalent to number(38)

    (2) String type:

    • char(n): fixed-length character string type (the maximum value of n is 2000), and the length of n bytes is allocated

      • char(10):'abcdef', less than 10 bits are filled with blank characters
      • Features:
        • Advantages: high data management efficiency
        • Disadvantages: White space wastes a lot of space
    • varchar2(n): Variable-length character string type (the maximum value of n is 4000), and up to n bytes of space length are allocated.

      • Note: Oracle unique data types
      • varchar2(10):'abcdef', the length of the space after storage is 5.
      • Features:
        • Advantages: save data storage space
        • Disadvantages: relatively low data management efficiency
    • Examples: Name varchar2(100) Mobile phone number char(11) Mailbox varchar2(200)

    (3) Date type:

    • date: year, month, day, hour, minute, second, week, accurate to the second
    • timestamp: accurate to the millisecond

    (4) Boolean type:

    • Oracle does not support boolean type, you can use number(1) to express with 0 and 1 or

    Use char(1) to represent y/n or use char(3) to represent male/female

    • Note: The encoding method of oracle is utf-8 by default, and Chinese characters occupy 3 bytes

    (5) Big data type:

    • clob: character big data (up to 4G), such as text files, etc.
    • blob: Maximum binary data (maximum 4G), such as video
  3. constraint

    (1) Primary key constraint: Primary key, referred to as PK

    • Role: uniquely identify a row of data in the table. Such as student ID, job ID, etc.
    • Features: unique, non-empty
    • Syntax: field name data type primary key
    • Note: During development, each table usually has a primary key constraint.

    (2) Unique constraint: unique

    • Role: Identifies that the value of this field cannot be repeated. Such as province certificate number, mobile phone number
    • Features: unique, can be empty
    • Syntax: field name data type unique

    (3) Non-empty constraint: not null

    • Role: To identify the required content of the field. Such as student name
    • Features: non-empty, repeatable
    • Syntax: field name data type not null

    (4) Check constraints: custom constraints

    • Function: Restrict the content of this field according to custom rules. For example, gender can only be male or female

    • Syntax: field name data type check (check constraint expression)

      • Gender can only be male or female: check( sex in ('male','female'))

    ​ check( sex ='male' or sex='female')

    • Email must have @:check (email like'%@%')

    • The phone number must be 11 digits: phone char(11) check(phone like'_____________')

    (5) Foreign key constraint: foreign key referred to as FK

    • Function: The value of the identification field is not allowed to be entered casually, it must be the primary key or unique key in another table

      The value present in. (Identifies the relationship between the current table [slave table] and another table [master table])

    • Features: can be repeated, can be null

    • Syntax: field name data type references main table name (primary key/unique key field name)

    • Understand the idea map:
      Insert picture description here

  4. Defaults:

    Function: Identifies the content that the system assigns by default without filling in any content in this field.

    Syntax: field name data type defualt value

    Note: The type of the given default value must be consistent with the data type of the field

  5. Comprehensive example:

    Class table information: class number, class name

    • create table t_class(
         cls_id  number(5) primary key,
         cls_name varchar2(20) not null
      );
      

    Student form information: student ID, name, email (must have @), date of birth (default current date), ID number,

    ​ Class number

    • create table t_student(
      stu_id number(5) primary key,
      stu_name varchar2(20) not null,
      email varchar2(50) not null check(email like ‘%@%’),
      birthday date default sysdate,
      card_id char(18) unique,
      cls_id number(5) references t_class(cls_id)
      );

    • Note: Query all tables in the library: select * from tabs;


    以上主键约束、非空约束、唯一约束、检查约束、外键约束都是字段级的约束。
    所谓的字段级约束是定义在某一个字段的后面。
    
  6. Joint constraint

    Union constraint: Use a combination of multiple keys when the primary key or unique constraint cannot be identified using any column of the table

    ​ Constraint

    Common joint constraints: joint primary key, joint unique constraint

    grammar:

    • Joint primary key: primary key (field name 1, field name 2)
    • Union unique constraint: unique (field name 1, field name 2)

    Code case: realize the distribution of the above elective courses

    • – 学生表
      create table student(
      s_id number(5) primary key,
      s_name varchar2(20) not null
      );
      – 课程表
      create table courses(
      c_id number(5) primary key,
      c_name varchar2(20) not null
      );
      – 学生和课程的关系
      create table student_courses(
      s_id number(5) references student(s_id),
      c_id number(5) references courses(c_id),
      primary key (s_id,c_id)
      )

    Idea map analysis:

    > * [External link image transfer failed. The source site may have an anti-hotlinking mechanism. It is recommended to save the image and upload it directly (img-GJJnQrJX-1589017547099) (E:\02_Second stage\Lecture preparation\oracle\1574323826841.png) ]


Second, add, delete and modify data (DML)

  1. adding data

    Syntax: insert into table name (column 1, column 2, …) values ​​(value 1, value 2, …)

    Role: Insert a piece of data into the table.

    Case:

    • insert into t_class(cls_id,cls_name) values(1,‘Java86’);

    • insert into t_student (stu_id,stu_name,email,birthday,card_id,cls_id)

      values (100,‘zs’,‘[email protected]’, to_date(‘1989-09-10’,‘yyyy-mm-dd’),‘370818198904152922’,1);

    note:

    • The column name after the table name must be a field that exists in the table, in no order

    • The value list after values, the order, type, and number must be exactly the same as the previous field list

    • When inserting data, all non-empty fields without default values ​​must specify values

    • If when inserting data, all fields are assigned values ​​in turn, the column name after the table name can be omitted, but the value

    • The order, type, and number of the list must be exactly the same as the field list in the table structure

      • insert into table name values ​​(value 1, value 2);
      • insert into t_student values (101,‘lisi’,‘[email protected]’, to_date(‘1996-09-10’,‘yyyy-mm-dd’),‘370818198904152952’,2);
    • If the data of the foreign key column (FK) does not exist in the main table when inserting the data of the foreign key column (FK), the operation will report an error, the error message:

    > [External link image transfer failed, the source site may have an anti-hotlink mechanism, it is recommended to save the image and upload it directly (img-udlGkG2S-1589017547100) (E:\02_second stage\prep\oracle\1574330734813.png)]

  2. change the data

    Syntax: update table name set column name 1=new value, column name 2=new value where filter conditions

    Function: According to where filter conditions, modify the specified column in the eligible data to the new value

    Case: Transfer student number 100 to class 2

    • update t_student set cls_id = 2 where stu_id = 100;

    Note: When modifying data, you also need to comply with constraints and data types.

  3. delete data

    Syntax: delete from table name where filter condition

    Role: Delete data that meets the filter criteria from the table

    Case 1: Delete student number 100.

    • delete from t_student where stu_id=100

    Case 2: Delete the data of class number 2 from the class table.

    • delete from t_class where cls_id = 2;

    • Note: If the deleted data has found a sub-record (apply to the data in the slave table), the error message is as follows:
      Insert picture description here

    • Solution:

      • Transfer students in this class to other classes, and then delete class data
      • Delete the corresponding data in the slave table first, and then delete the data in the master table. (First delete the students in class 2 and then delete class 2)

    Supplement: delete table:

    • delete from 表名;
      • Features: Delete the entire table data, the efficiency is low.
    • Table truncation: truncate table table name;
      • Features: Directly clear the space of the storage table data part, and then delete the data [non-DML]

Three, sequence

  1. Function: Used to automatically generate a set of database objects with sequential numbers.

  2. Application: Usually used for insert statements to automatically generate the value of the primary key field.

  3. grammar:

    (1) create sequence sequence name;

    • Create a default sequence, starting from 1, increasing by 1 each time

    (2) create sequence 序列名 start with n increment by m

    • Create a sequence, starting from n, incrementing m each time

    Example: Create a sequence, starting from 1, and incrementing by 2 each time

    • create sequence stu_seq start with 1 increment by 2;
  4. use:

    (1) Get the next valid value in the sequence: sequence name.nextval

    (2) Get the current value in the sequence: sequence name.currval

    • Before getting the current value of the sequence, nextval must be used at least once

    note:

    • After the sequence is created, it is shared by all tables
    • Once the value in the sequence is used, it cannot be regenerated

    Case: Use sequence to automatically generate the primary key in the t_student table.

    • insert into t_student values (stu_seq.nextval,‘ww’,‘[email protected]’, to_date(‘1989-09-10’,‘yyyy-mm-dd’),‘370818198904153366’,2);

    supplement:

    (1) View the sequence related to the current user: select sequence_name from user_sequences;

    (2) Delete a sequence: drop sequence sequence name;


Fourth, the view

  1. Concept: A named query statement.

  2. grammar:

    (1) Define the view: create view view name as select statement

    • create view emp as
      select employee_id,last_name,salary,department_id from employees;

    (2) Use view: select column name, column name, column name from view name;

    • select * from emp;-You can also write specific column names

    (3) Note:

    • View is to define names for sql query statements to facilitate reuse and simplify SQL
    • Views are equivalent to query statements, do not store actual data, and are not improved in efficiency

    (4) Delete view: drop view view name;

    • drop view aa;

Five, index (inder)

  1. understanding:

    (1) Question: How to solve the problem that the query efficiency will drop sharply if the data volume is 1000w (oracle)?

    (2) Solution: Use index to solve select query efficiency.

    (3) Analysis of core ideas:

    > * [External link image transfer failed. The source site may have an anti-hotlinking mechanism. It is recommended to save the image and upload it directly (img-uQQyXkfL-1589017547101) (E:\02_Second stage\Preparation\oracle\1574408282978.png) ]

  2. grammar:

    (1) Create index: create index index name on table (field)

    • create index last_name_index on employees(last_name);

    (2) Use index: No manual use is required. When the indexed field is used in the query, the index will be automatically used to improve the query efficiency.

    (3) Delete index: drop index index name;

  3. Features of the index:

    (1) The index is not created as many as possible: the index will occupy hard disk space; when adding, deleting, and changing data at the same time,

    ​ The data in the index needs to be maintained at the same time to reduce the efficiency of addition, deletion and modification operations

    (2) Usually create indexes on columns that are frequently queried

    (3) For columns with primary keys and unique constraints, the database will automatically add indexes.


Six, affairs

  1. Introduce:

    (1) Operation: Transfer 10000 from Zhang San's CCB account to Li Si.

    • account:[id , name , balance]
    • user:
      • 100 sheets three 20000.0
      • 101 Li Si 1000.0

    (2) Ideas:

    • Modify Zhang San's balance to 10000.0

      update account set balance = 10000.0 where id = 100

    • At the same time, the balance of Li Si is revised to 11000.0

      update account set balance = 11000.0 where id = 101

    (3) Problem: If multiple sql statements complete a function, half of the sql statements will be executed, which affects the realization of the function.

    (4) Summary: Multiple SQLs in the transfer need to be regarded as a whole, either all succeed or all fail.

  2. concept:

    (1) Transaction: the smallest execution unit of the database, usually consisting of one or more SQL statements

    ​ Composition, all sql are executed successfully (commit); if there is a sql execution failure, it represents transaction rollback (rollback)

    (2) Role: to ensure the correctness of the business.

    (3) Size: Depends on actual business needs.

  3. Transaction boundary

    Start: After the client and DB establish a connection, the last transaction ends.

    End:

    • End of display: commit-submit / rollback-rollback
    • Implicit end: create / drop / alter
  4. principle:

    Rollback:

    Rollback segment: The database server DBServer will open up a small memory space (called the rollback segment) for each connected client, which is used to temporarily store the execution results of the SQL statement. When the transaction commits, it will roll back itself The data is actually written into the DB; when the transaction rollback, the data in the rollback segment will be emptied.

    principle:
    Insert picture description here

    lock:

    (1) When inserting/update/delete data in a transaction, the lock mark of the data will be acquired, and the lock mark will not be released until the transaction is completed (commit/rollback);

    (2) When a transaction holds the lock mark of the data, multiple transactions are operated concurrently, and other transactions cannot perform insert/update/delete operations on the data until the lock mark is obtained, but the select query operation can be performed. The query operation is default Do not participate in affairs.

    Case: When different clients update the same data in the same table, the execution is successful first, but before the commit is executed, the follow-up statement in another client is executed, the following phenomenon occurs:
    Insert picture description here

  5. Four characteristics of business (ACID) [Interview Questions]

    (1) Atomic (atomicity): multiple SQL in the transaction as a whole, all successfully commit (commit), if one fails, rollback (rollback) -->A

    (2) Consistency (consistency): After the transaction ends, the data state in the database must be consistent. —>C

    (3) Isolation: When multiple users operate concurrently, the user and user data do not affect each other. —>I

    (4) Durability: The impact of the transaction on the database is permanent and cannot be temporary.

Guess you like

Origin blog.csdn.net/Java_lover_zpark/article/details/106024622
Recommended