Oracle basic grammar knowledge practical learning

oracle table structure, basic sentence learning

Oracle12C version

Official document: https://docs.oracle.com/apps/search/search.jsp?q=CLOB&category=database

What is an Oracle database?

  1. Oracle Database, also known as Oracle RDBMS, or Oracle for short. It is a relational database management system launched by Oracle.
  2. The Oracle database system is currently a popular relational database management system in the world. It has the advantages of good portability, easy use, and strong functions. It is applicable in various large, medium, small, and microcomputer environments.
  3. Oracle is a highly efficient, reliable, and high-throughput database solution

What do databases and instances mean?

The Oracle database server consists of a database and at least one database instance.

1

What is the storage structure of Oracle's stored data, and what is contained in it?

1. Physical storage structure

​ Meaning: The physical storage structure is a pure file that stores data. Data file : the real data, a data structure of a logical database (e.g., tables and indexes) are physically stored in a data file. Control file : Every Oracle database has a control file containing metadata. Metadata used to describe the physical structure of the database includes the database name and file location data online redo log files : each has an Oracle database online redo log, which contains two or more online redo log file. Composed of redo entries, able to record all changes made to the data. 2, the logical storage structure of the data block (the Data Blocks) : the Oracle data stored in the data block. Data blocks are also called logical blocks, Oracle blocks or pages, which correspond to the number of bytes on the disk. Extents : Extents are the specific number of logically continuous data blocks used to store specific types of information. Segments (Segments) : a set of segments are allocated for the user object storage range (e.g., a table or index). Table space (the Tablespaces) : the database is divided into a table called logical unit of storage space. A table space is a logical container for segments. Each table space contains at least one data file.







Oracle instance is divided into several parts, what do they contain?

Oracle basic commands

Create user:

create user user05 identified by 123456 --Create a new Oracle user
grant CONNECT,RESOURCE,DBA TO user05 --GRANT statement grants user05 user permissions
drop user user04; --Delete user

alter user user01 identified by 111111;-modify user password

CONNECT user05/123456 --Connect to create a user

Data table space (Tablespace):
create tablespace table name datafile'data file name' size table space size
create tablespace data_test datafile'e:\oracle\oradata\test\data.dbf' size 2000M;
create a user and specify the table space:
CREATE USER cici IDENTIFIED BY cici PROFILE DEFAULT DEFAULT TABLESPACE CICI ACCOUNT UNLOCK;
create user jykl identified by jykl default tablespace jykl_data temporary tablespace jykl_temp;
Grant to new users:
GRANT connect, resource TO cici;
grant create session to cici;

Additions, deletions, and changes:

select * from CLASSINFO; --Query data
INSERT into CLASSINFO(CLASSNAME) values('明');
--Insert data update classinfo set CLASSID=2.0,CLASSNAME='large' where CLASSID=1.0
--Modify data delete from classinfo where id =1;-delete data

Sort:

Syntax: SELECT column name FROM indicates the ORDER BY column name

SELECT column_1 FROM table_name ORDER BY column_1 collation

Sorting rules parameters:

  • ASC means sort in ascending order
  • DESC means sort in descending order
  • NULLS FIRST puts NULL values ​​before non-NULL values
  • NULLS LAST places NULL values ​​after non-NULL values.

Filter data

● DISTINCT- describes how to eliminate duplicate rows in the query output.

select distinct column name from table name

● WHERE-Demonstrate how to specify filter conditions for rows in the result set returned by a query.

select column name from table name where conditions

● AND-Combine two or more Boolean expressions, and if all expressions are true, return true.

select column name from table name where conditions and conditions

● OR-Combine two or more Boolean expressions, and if one of the expressions is true, it returns true.

select column name from table name where condition or condition

● FETCH- Demonstrate how to use the row limit clause to limit the number of rows returned by a query.

parameter:

fetch next: Only return the number of rows or the percentage of the number of rows after FETCH NEXT (or FIRST).

返回库存数量最多的前5个产品。
SELECT
    product_name,
    quantity
FROM
    inventories
INNER JOIN products
        USING(product_id)
ORDER BY
    quantity DESC 
FETCH NEXT 5 ROWS ONLY;

with ties: returns the same sort key as the last line (returned two other lines).

查询前10个数据
SELECT
 product_name,
 quantity
FROM
 inventories
INNER JOIN products
 USING(product_id)
ORDER BY
 quantity DESC 
FETCH NEXT 10 ROWS WITH TIES;

● IN- Determine whether the value matches any value in the list or subquery.

select column name from table name where not in (parameter)

select column name from table name where in (parameter)

  1. not in (parameter)
  2. in (parameter)

● BETWEEN- Filter data based on a series of values ​​(interval values). ,

select column name from table name where column name BETWEEN conditions and conditions

 SELECT product_name,standard_cost 
 FROM  products
 WHERE standard_cost 
 BETWEEN 500 AND 600 
 ORDER BY standard_cost; 

​ Return data between 500-600 and sort

  1. BETWEEN conditions and conditions
  2. BETWEEN not condition and condition

● LIKE- Perform matching based on a specific pattern.

 SELECT  first_name,last_name,phone 
 FROM contacts 
 WHERE last_name 
 LIKE 'St%' 
 ORDER BY last_name; 

Column name not like'condition%'

Column name like'condition%'

Oracle aggregate functions (use group by grouping)

The name of the aggregate function in Oracle The role of the function
Count Used to find the number of valid data
Max Used to find the largest data in the given data
Min Used to find the smallest data in the given data
Avg Used to average the given data
Sum Used to sum the given data
Variance Used to find the standard deviation of the given data
Stddev Used to find the variance of the given data

Null values ​​will be ignored

Oracle basic data types

Character type Numerical Date type Other types
CHAR(n) NUMBER(p,s) DATE (including the century, year, month, day, hour, minute, and second) BLOB (Unstructured Binary Large Object Data Type Storage)
NCHAR(n) binary_float TIMESTAMP (date and time, including decimals) CLOB (Character Large Object)
VARCHAR2(n) binary_double
NVARCHAR2(n)

Oracle constraints

  • ​ Non-null constraint (NOT NULL)
  • Primary key constraint (PRIMARY KEY)
  • Foreign key constraints (primary key references)
  • Unique constraint (UNIQUE)
  • Check constraints (CHECK)

Oracle index

create 索引名 index  自定义索引名称 on 表名(列)

logically:

Single column single row index

Concatenated multi-row index

  create index 索引名 on 表名(列名....) 

Unique index (unique index)

 create unique index 索引名 on 表名(列名)

Non Unique Non unique index (non unique index)

 非唯一索引中,数据库通过将rowid作为额外的列附加到键中来存储它 |唯一索引中,索引键不包含rowid
 CREATE INDEX 索引名 on 表名(列名 DESC)

Function-based function index (function-based index)

 这些就是 B* 树索引或位图索引,它将一个函数计算得到的结果存储在行的列中,而不是存储列数据本身 
 查询函数索引:
 SELECT * FROM DBA_INDEXES D WHERE D.INDEX_TYPE LIKE 'FUNCTION-BASED%';
 函数需要满足的条件:
 不能使用SUM、COUNT等聚合函数
 不能在LOB类型的列、NESTED TABLE列上创建函数索引
 不能使用SYSDATE、USER等非确定性函数。
 对于任何用户自定义函数必须显式的声明DETERMINISTIC关键字
 语法:
 CREATE TABLE 表名(ID NUMBER,SCHR VARCHAR2(10));
 CREATE INDEX IND_FUN ON 表名(UPPER(SCHR));
  INSERT INTO TESTFINDEX_LHR VALUES(1,'ddddd');
   SELECT  * FROM 表名 WHERE UPPER(SCHR)='ddddd';

Domain index (domain index)

应用域索引是你自己构建和存储的索引,可能存储在Oracle 中,也可能在 Oracle 之外。
方式:
CREATE INDEX text_idx ON table_index(object_name) indextype is ctxsys.context;
Logical statement
1. Insert data in FOR cycles (use him for the specific number of braking cycles)
BEGIN
		   FOR i IN  1..1000 LOOP 
			  INSERT INTO TEST_USER VALUES(sys_guid(),'MING','123456');
			 END LOOP;
			 COMMIT;
		END;
BEGIN
   FOR i IN  1..5 LOOP 
	   FOR j IN 1..i LOOP   
		  DBMS_OUTPUT.put('*');
		 END LOOP;
		  DBMS_OUTPUT.put_line('');
	 END LOOP;
	 
END;
2. Insert data in WHILE cycle (if the cycle is not executed once, this is the cycle)
declare
		 p_sql varchar2(500);
		 i number;
		 begin
		   i:=0;
		   WHILE(i<12000) LOOP
		       p_sql:= 'INSERT INTO TEST_USER VALUES(SYS_GUID(),''' || 'tt' || ''',
					 ''' || '123456' || ''')';  
		       i:=i+1;
		      execute immediate p_sql;
		    commit;
		   end loop;
		  end;
3. Loop to insert data in a loop (do not know the exact number of times this is using loop)

exit: Exit the loop

DECLARE 
 v integer:=10;
BEGIN
   LOOP
	    v:=v-1;
			DBMS_OUTPUT.put_line('这个值时:'|| v);
		 IF v<3 THEN
		   dbms_output.put_line('已循环到目标值:'|| v);
			 EXIT;
			 END IF;
	 END LOOP;

END;

Physically:

Partitioned partition index

分区键为id
partition by range (id)  
(
  partition part_1 values less than (5),
  partition part_2 values less than (10)
)
  • - Locally partitioned index(局部分区索引)
    局部分区索引随表对索引完成相应的分区(即索引会使用与底层表相同的机制分区),每个表分区都有一个索引分区,并且只索引该表分区。
    		Local prefixed index(局部前缀索引)
    			以分区键作为索引定义的第一列(分区键在第一列)
    			create index 自定义索引名 on 表名 (id, name) local;
    		Local nonprefixed index(局部非前缀索引)
                分区键没有作为索引定义的第一列(分区键没有在第一列)
                create index 自定义索引名 on 表名 (name, id) local;
    - Globally partitioned index(全局分区索引)
    针对整个表空间(全局)
    create index 自定义索引名 on 表名(age) global
    
    partition by range (age) 
    (
      partition index_part_1 values less than (20),
      partition index_part_2 values less than (maxvalue)
    )
    
    

NonPartitioned non-partitioned index

B-tree: Normal B-tree

CREATE INDEX语句时,默认就是在创建b-tree索引

Rever Key reverse transformation B tree

反转了索引码中每列的字节,降低索引叶块的争用; 

Bitmap bitmap index

 含义:只有很少的索引条目,每个索引条目指向多行 
影响因素:
位图索引不适合并发环境,在并发环境下可能会造成大量事务的阻塞。
位图索引适合只有几个固定值的列,如性别、婚姻状况、行政区
位图索引在读密集的环境中能很好地工作,但是对于写密集的环境则极不适合

 create bitmap index 自定义索引名 on 表名(列名); 

Oracle view

​ **Meaning: **The view is called a virtual table and does not occupy physical space. The statement defined by the view is stored in the data dictionary and is re-executed each time it is used.

​ Views can get data from one table or multiple related tables. The obtained table is called the base table. View nesting can also be taken

​ View has query, modify, add, and delete functions. Need to obtain the corresponding permissions, you can also set with read only to block DML operations.

Remarks:

​ (The function of group function, group by, distinct and rownum in the definition statement cannot be used to delete data.)

(In the definition statement, there are group functions, group by, distinct, rownum fake and inferior elements, and columns are defined as expressions and cannot use the function of modifying data)

(There are group functions, group by, distinct, rownum shoddy elements in the definition statement, the definition of the column is an expression, and the non-empty column in the table is not included in the view definition. The function of inserting data cannot be used)

​ **Create a view: **create view view name as select column name from table name where conditions

Query view: the SELECT column names from view name

​ **Modify the view: **create or replace view view name as select column name from table name where conditions (ROWNUM can only use <or <=)

​ **DROP VIEW: **DROP VIEW view name

​ **Modify view data: **update view name set modified column where conditions

​ **Delete view data: **delete view name where conditions

Oracle trigger

​ **Meaning: ** Trigger is a technology provided in relational databases. Triggers in Oracle are similar to stored procedures and functions. They have SQL blocks for declaration and execution and exception handling. The only difference with stored procedures and functions is that stored procedures and functions need to be called by the user to execute, and triggers are executed by The event is controlled.

​ Triggers are similar to triggering and firing. Events refer to DML operations on base tables or views and monitor various operations on the database.

**DML Trigger: ** Trigger before or after DML operation

					create [or replace] trigger trigger_name
​							{before | after} trigger_event
​							on table_name
​							[for each row]
​							[when trigger_condition]
​							trigger_body

trigger_name:触发器名称

before | after : 指定触发器是在触发事件发生之前触发还暗示发生之后触发

trigger_event:触发事件,在DML触发器中主要为insert、update、delete等

table_name:表名,表示发生触发器作用的对象

for each row:指定创建的是行级触发器,若没有该子句则创建的是语句级触发器

when trigger_condition:添加的触发条件

trigger_body:触发体,是标准的PL/SQL语句块

Instead of triggers : for operation by one or more than two views.

create [or replace] trigger trigger_name --触发器名称
instead of trigger_event --触发事件
on view_name --视图名称
for each row  --替代触发器必须指定为行级的触发器
[when trigger_condition] --触发条件
trigger_body --触发体,PL/SQL块

​ System trigger: When the system is operated, it is triggered. Such as: closing and starting of the database

Database system trigger

 CREATE OR REPLACE TRIGGER [sachema.]trigger_name

{BEFORE|AFTER} 
{ddl_event_list | database_event_list}
ON { DATABASE | [schema.]SCHEMA }
[WHEN condition]
PL/SQL_block | CALL procedure_name; 
 ddl_event_list:一个或多个DDL 事件,事件间用 OR 分开 ;database_event_list:一个或多个数据库事件,事件间用 OR 分开;

DDL operation:

grant(授权),
revoke(撤销授权),
create(创建),
drop(删除),
alter(修改),
comment(注释),
audit(审核),
rename(重命名)

Database events:

SET SERVEROUTPUT ON
DECLARE
 err_msg VARCHAR2(120);
BEGIN
 dbms_output.enable (1000000);
 FOR err_num IN 10000..10999
 LOOP
  err_msg := SQLERRM (-err_num);
  IF err_msg NOT LIKE '%Message '||err_num||' not found%' THEN
   dbms_output.put_line (err_msg);
  END IF;
 END LOOP;
END;*
event Time allowed Description
STARTUP AFTER Triggered after the database instance is started
SHUTDOWN BEFORE Triggered before closing the database instance (not triggered by abnormal shutdown)
SERVERERROR AFTER Triggered after a database server error
LOGON AFTER Triggered after successful login and connection to the database
LOGOFF BEFORE Triggered before starting to disconnect the database
CREATE BEFORE,AFTER Triggered before and after executing the CREATE statement to create the database object
DROP BEFORE,AFTER Triggered before and after executing the DROP statement to delete database objects
ALTER BEFORE,AFTER Triggered before and after executing ALTER statement to update database objects
DDL BEFORE,AFTER Triggered before and after most DDL statements are executed
GRANT BEFORE,AFTER Triggered before and after executing the GRANT statement to grant permissions
REVOKE BEFORE,AFTER Before and after the execution of REVOKE statement to receive permission, the offending
RENAME BEFORE,AFTER Before and after the execution of the RENAME statement to change the name of the database object
AUDIT / NOAUDIT BEFORE,AFTER Triggered before and after performing AUDIT or NOAUDIT audit or stopping audit

Users flip-flop

User trigger query:

SELECT NAME
FROM USER_SOURCE
WHERE TYPE='TRIGGER'
GROUP BY NAME 

Oracle transaction

Isolation layer Misread|dirty read Non-repeatable read|non-repeatable read Fake Reading|Phantom Reading
READ UNCOMMITTED (non-committed read) Yes Yes Yes
READ COMMITTED no Yes Yes
Repeatable READ no no Yes
Serializable (serial read) no no no

Oacle is the second type by default, supporting two types of submission read and serial read

1、set transaction :设置事物属性。

2、commit:提交事物。

3、rollback:回滚事物。

4、savepoint:设置保存点。

5、rollback to savepoint :回滚到保存点。
事物的类型
1、显式事物:顾名思义就是开发者主动控制事物的提交和回滚,可以利用命令来控制事物的提交,如:常见的PL/SQL语句块就是这种类型的事物。必须利用commit提交。

2、隐式事物:指的是oracle数据库自己控制事物的提交和回滚。比如oracle的DDL语句(create、drop、alter等)、DCL语句(grant、revoke)等都是一经执行直接持久化到数据库,不需要开发者自己手动提交。或者是DML语句在oracle数据库设置了自动提交:set autocommit on,也可以不需要主动提交就可以直接持久化到数据库。


SET TRANSACTION [ READ ONLY | READ WRITE ]
[ ISOLATION LEVEL [ SERIALIZE | READ COMMITED ]
[ USE ROLLBACK SEGMENT 'segment_name' ]
[ NAME 'transaction_name' ];
语法释义:
*EAD ONLY* - 可选的。 如果指定,它将事务设置为只读事务。
*READ WRITE* - 可选的。 如果指定,它将事务设置为读/写事务。
ISOLATION LEVEL
\- 可选的。 如果指定,它有两个选项:
`ISOLATION LEVEL SERIALIZE` - 如果事务尝试更新由另一个事务更新并未提交的资源,则事务将失败。
`ISOLATION LEVEL READ COMMITTED` - 如果事务需要另一个事务持有的行锁,则事务将等待,直到行锁被释放。
*USE ROLLBACK SEGMENT* - 可选的。 如果指定,它将事务分配给由`'segment_name'`标识的回退段,该段是用引号括起来的段名称。

*NAME* - 为`'transaction_name'`标识的事务分配一个名称,该事务用引号括起来。

Oracle stored procedures

declare

​    说明部分

begin

​    语句序列(dml语句)

exception

​    例外处理语句

end;

constant:

char,varchar2,date,number,boolean,long

Reference variable:

pname test_procedure.name%type; -- 变量名:pname   test_procedure表中的name列的类型


declare 
  pname test_procedure.name%type;
  psal test_procedure.money%type;
begin
  
  select t.name,t.money
    into pname,psal       --往变量注入值 顺序必须一致
    from test_procedure t 
   where t.name = 'XX天';
  
  dbms_output.put_line('名字是:'||pname||',薪水是:'||psal);
end;

Record variable

emp_rec    TEST_PROCEDURE%rowtype   记录一行的类型,可以理解为一个数组。数组中的每一个元素就是一列。 

declare 
  tablerow test_procedure%rowtype;
begin

  select *
    into tablerow
    from test_procedure t 
   where t.name = 'XX天';

  dbms_output.put_line('名字是:'||tablerow.name||',薪水是:'||tablerow.money);

  dbms_output.put_line('职位是:'||tablerow.job||',薪水是:'||tablerow.dept);

end;

Define constant

Constant refers to the amount that does not change

<常量名>constant<数据类型>:=<常量值>;
myname constant varchar(4):='sola';

Oracle paging

Physical paging

第一种:
SELECT * FROM  
(  
SELECT A.*, ROWNUM RN  
FROM (SELECT * FROM TABLE_NAME) A  
WHERE ROWNUM <= 40  
)  
WHERE RN >= 21  
第二种:
SELECT * FROM   
(  
SELECT temp.*, ROWNUM RN   
FROM (SELECT * FROM emp) temp   
)  
WHERE RN BETWEEN 10 AND 15

rownum不能以任何基表的名称作为前缀。 
子查询中的rownum必须要有别名,否则还是不会查出记录来,这是因为rownum不是某个表的列,如果不起别名的话,无法知道rownum是子查询的列还是主查询的列。   

Front page tab:

当前页

数据总数=数据集合总数

总页数=数据总数%前台页数			|true  ||总页数=数据总数%前台页数+1  ||false   总页数=数据总数%前台页数

前台页数

首页

尾页
//当前页
private Integer current;

//总记录数
private Integer totalCount;

//总页数
private Integer sumPages;
//页面记录数
 private Integer pageSize; 

//判断是不是首页

  private Boolean isFirstPage = false;

判断是不是最后一页
  private Boolean isLastPage = false;
  private List<T> list;
  int startIndex = 0;
  int endIndex = 0;
  public PageList(List<T> list, Integer current, Integer pageSize) {
this.current = current;
this.pageSize = pageSize;
this.totalCount = list.size();
// 计算总页数
boolean isFullPages = totalCount % pageSize == 0;
if (!isFullPages) {
    // 若当前数据总数与页面数据大小相除不为整数,则增加一页显示剩余的数据
    this.sumPages = totalCount / pageSize + 1;
} else {
    this.sumPages = totalCount / pageSize;
}
startIndex = current * pageSize - pageSize;
if (current <= 0) {
    // 若查询的页数是小于等于0的则直接取第一页
   this.startIndex = 0;
   this.current = 1;
   endIndex = this.current * pageSize;
    // throw new ArithmeticException("当前页无法查询");
} else if (current > sumPages) {
    // 若查询的页数大于总页数,则置list为空
    list = new ArrayList<>();
} else if (current.equals(sumPages)) {
    endIndex = totalCount;
} else {
    endIndex = current * pageSize;
}
  // 判断是否为首页
    if (this.current == 1) {
        isFirstPage = true;
    }
 
    // 判断是否为最后一页
    if (this.current.equals(sumPages)) {
        isLastPage = true;
    }
 
    if (CollectionUtils.isEmpty(list)) {
        this.list = new ArrayList<>();
    } else {
        this.list = list.subList(startIndex, endIndex);
    }
}

Guess you like

Origin blog.csdn.net/YHM_MM/article/details/105354261