Oracle database basic learning

Oracle database basic learning

I have studied mysql sqlserver before, but the notes may not be on the CSDN, and there may be some jumps~ I
don't know where you can see the notes of this big guy~ It's not mine .

Introduction to Oracle

OracleDatabaseAlso known as Oracle RDBMS, it is a relational database management system of Oracle. (The best database system in the world; (long history)) It supports multi-user high-performance transaction processing, and has excellent performance in maintaining data security and integrity. It supports distributed database and distributed processing with portability, Oracle can Used on multiple operating systems such as window Linux~ (SqlServer Microsoft database can only be used on window!)
优点:

缺点:Charges! Service charges... Later installation and maintenance are also charged... Small and medium-sized companies generally do not use ~
RDBMS: relational databases.
There is a relationship between data in multiple tables, and the data operations on these tables depend on the relationship (the relationship is used to Describe the data dependencies between multiple tables, including one-to-one, one-to-many, and many-to-many relationships)
These relationships are expressed in Oracle databases such as primary keys and foreign keys...
RDBMS is based on these relationships Based on the model, Oracle has fully supported the relational database
Mysql SqlServer db2 from the 7.3 version, Oracle is a relational database;

Basic concepts of Oracle:

The concept of Oracle: It is a bit difficult for individuals to learn at the beginning~
Mainly because after learning Mysql SqlServer, there are many different concepts and theories from Oracle, which are different from the previous ones; it is recommended to abolish martial arts! Don't think other databases are learning;

Oracle database

oracle数据库Comprising 逻辑结构and 物理结构
physical structure of the database is a collection of physical means for storing data comprising: a data file or the DBF ORA, control files, online files, log files, parameter files ...
logical structure refers to a set of logical data organization described concepts therebetween and The
concept of oracle database is somewhat different from other database concepts:
the process of creating a database in mysql database is-creating a database-creating a table
and the process of creating a database in oracle is-creating a table space-creating a user-creating a user/ Management table. So Oracle database is different from other databases.
It can be understood that Oracle is a large database, managed by users.
(So ​​when you use it, you must first create a database before you can use Oracle; you can create a database at the same time during installation~)
(Generally after completing the Oracle database installation and creating an Oracle instance, multiple tablespaces, system tables, system...users will be automatically created) Different Of users can be understood as different libraries!

Global database name

The global database name is used to distinguish a database. It is necessary to create a database when installing the database...
It consists of: database name + domain name , which is similar to the domain name in the network; making the name of the database unique in the entire network environment.
Database name: The
database name is the identifier (unique) of a database, which is declared after the database is installed or created; (the name from when the database is installed~)
(It is not recommended to modify it, because the database name is still written In the control file, the control file is stored in binary format, and the user cannot modify the content of the control file.)
Assume that the user has modified the database name in the parameter file, but when Oracle is started.
Because the DB_NAME in the parameter file is inconsistent with the database name in the control file, the database startup fails and an ORA-01103error will be returned .
查询当前数据库名 :select name from v$database; (system login status is recommended;)
Domain name:
In a distributed database system, between different versions of database servers, whether the operating system is unix or windows,
each server can pass the database chain The database domain name is mainly used for replication in a distributed environment.
什么时候使用域 :1. In the oracle distributed environment, the remote transmission of data between the two databases through the database link 2. In the same network environment, the database names of the two databases are the same

查询数据库的域名 : select value from v$parameter where name ='db_domain'; (recommended system login status;)

Database instance

Each started database corresponds to a database instance, and the data in the operation database is accessed through the instance;
if the database is understood as a file (application) on the hard disk, the
database instance is a group of server background processes that share the running state of the memory; (a The database can have multiple instances)

Table spacetablespace

Each Oracle database is composed of multiple table spaces; (the database created by the user is also stored in the corresponding table space)
A table space can be composed of multiple data files, but a data file can only belong to one table space; (The table space belongs to the database)
Each database has a SYSTEM system table space...SYSAUX TEMP... are automatically created when the database is created.
The administrator can create a custom table space and assign it to a specified user, or add and delete data files for the table space;

data file .dbf、.ora

Typically the file extension .dbfis a file database for storing data; (record database tables, indexes, views, ...)
a number of data files may be stored database tables, and a table of data may be derived from many data files; (absent a One-to-one relationship)

Control file .ctl

The extension of the control file .ctlis a binary file; information control file storage are many: the location and name of the data files and log files
(the database is up and running necessary for Oracle to read and write data files, is to find the corresponding file according to the control File, so a database has at least one control file;) Oracle11g defaults to three;

Log file .log

Log file extension is .logthat it records all of the data change information, and provides a data recovery mechanism; ensure that the system crashes or other accidents restored data;
log files are used in groups, each group has a log file or more The log file is used by multiple groups in the process of work. (One group is filled with other groups~)

Patterns and pattern objects

A schema is a collection of database objects (table index...);
Oracle creates a schema for each database user, and the secondary schema is owned by the current user. Has the same name as the user~


Install Oracle

Installation tutorial .


Oacle data type

Character data type

char(size)

Specify long character data (default 1 byte if not specified), the column length is 1~2000 bytes;
if the number of input bytes is less than the specified number of bytes, the space is filled; if the number of bytes is greater than the specified number, an error will be reported~

varchar2(size)

Variable-length character data, the column length is 1~4000 bytes.
Specify the size when defining the character type, but it will change according to the number of input bytes during the actual assignment; the
number of input bytes is less than the defined number of bytes, and there will be no spaces Instead, it becomes a small number of bytes (save memory) If the number of input bytes is greater than the specified number of bytes, an error will still be reported!

nchar(size)

nchar and Chinese character sets are stored in Unicode; the
difference between nchar and char lies in the inconsistent storage method. The field length of char (1) and nchar(1) is 1 byte and 1 character (equal to 2 bytes);
input a respectively There is no problem, but the occupied bytes are 1 and 2 respectively. If all Chinese characters are inserted, char(1) cannot be inserted;

nvarchar2(size)

The storage method is similar to nchar as Unicode; on this basis, it is similar to varchar2, variable character length...

Expansion:
nvarchar2 and varchar2 are not in mysql, so I was a little uncomfortable when I first started learning...
nvarchar2 and varchar2 are optimized on the basis of nvarchar and varchar, Oracle also has nvarchar and varchar data types;
but the bottom layer is still nvarchar2 and varchar2 so In the final execution, 2 is recommended for efficiency;

Numeric data type

number(p,s)

Variable-length numerical data: number can store positive numbers, negative numbers, zero fixed-point floating-point numbers...
p represents a precision between 1 and 38 (the number refers to a valid number from left to right that does not count as 0 and does not count negative decimal points)
s is in the range -84 ~127 means that the number of digits to the right of the decimal point can be 0; (for unnecessary decimals, the principle of rounding is followed)
The valid digits of the final value ≤ p is true!
Insert picture description here

Date and time data type

Date

Date data is roughly the same as mysql, Oracle provides the SYSDATE function to return the current date and time;

TIMESTAMP

Store the year, month, day, hour, minute, and second. The function of the SYSTIMESTAMP function is to return the current date, time and time zone;

LOB data type

LOB, also known as'large object', is a particularly large object that is easy to understand. It can store up to 4GB of unstructured information such as sound clips, video clips, etc...
LOB allows efficient and random segmented access to data, LOB can be external It can also be internal depending on its position relative to the database; it
can be done through the package DBMS-LOB provided in PL/SQL. Multiple columns in a table can be defined as LOB data types;
LOB data types are: CLOB BLOB BFILE NCLOB

clob

Can store a large amount of character data, up to 4G, can store single-character data and multi-character data; (XML document news content introduction and other documents containing a lot of content)

blob

Binary data, up to 4G (picture, video, sound)

bfile

Able to store binary files in operating system files outside the database. The BFILE column stores a BFILE locator that points to the binary file located on the server file system (maximum 4GB)

nclob

Used to store a large amount of nchar character data, nclog supports both fixed-width characters and variable-width characters (Unicode character data)


Finally, a lot of theories...
to the sql statement, it is recommended to look at a little basic...

Oracle SQl statement:

Sql language is a language for databases. It can create databases, tables, views, add, delete, modify, and check... a series of operations on the database; (not case sensitive) the
full name "Structured Query Language";

SQL components:
a. DML (database operating language): used to add, delete, and modify data in the table eg: INSERT, DELETE, UPDATE
b. DDL (database definition language): create or delete database objects in the database, eg: CERATE, DROP , ALTER
c. DQL (Database Query Language): used to query the data in the database eg: SELECT
d. DCL (Database Control Language): used to control the access permissions of database components to save money eg: GRANT, REVOKE

Here are the OneNote notes~
Insert picture description here
not detailed enough, too many to send... Sql statements are generally universal... But there are a few differences
that there is no database concept in Oracle, so the above database operations can be ignored...

Pseudo column in Oracle:

The pseudo column is like a column in the Oracle table (Mysql does not have ~). Every table has ~
pseudo column can be queried from the table, cannot be modified or deleted. Add...For the time being, only ROWID ROWNUM ROWID will be introduced

Each row of data in the table of the oracle database has a unique identifier, or rowid,
which is usually used to access the data inside oracle. Rowid requires 10 bytes of storage space and uses 18 characters to display.
use:

  1. Quickly access a row of data in the table 2 to show how the row in the table is stored 3. It can be used as a unique identifier for the row in the table~

ROWID format:
Insert picture description here

ROWNUM

It is the serial number of the rows in the result set returned by the query. You can use it to limit the number of rows returned by the query (paged query).
Note that the pseudo column ROWNUM is used as a conditional query:
Insert picture description here

-- scott 用户下,随便查看一个系统表,及伪列  rowid   rownum
select e.*,rowid ,rownum  from emp e; 

CREATE TABLE command

The table created by Qracle is somewhat different from Mysql because the table is managed by the user~

/*
  多行注释
*/

--单行注释
CREATE TABLE [用户.]表名(
	列 类型[ 属性,约束,索引,注释 ],
)

-- [] 为可选选项, 用户可选,不指定情况下默认当前登录用户~

Create a new table from an existing table

CREATE TABLE 新表
AS
SELECT * FROM 旧表;
-- 创建一个新表 和 旧表一模一样包括数据(可以指定列,来改变创建表的列...)
-- 一般用于:日表 (有些项目,非常大 每天会有非常多的数据, 如果都放在一个表中时间久了就会异常大越来越多   不利于备份数据..
-- 而对于日表 每天都有 其表结构是一定每天都一样的!
CREATE TABLE 新表
AS
SELECT * from 旧表 where 1=2; 	-- 加上条件使没有符合条件的数据赋值给新表,新表就是一个只有表结构的表了~

Transaction operation statement TCL

The transaction control statement TCL in Oracle is mainly composed of:

COMMIT: Commit the transaction, that is, to permanently save the database modification operations in the
transaction ~ ROLLBACK: Roll back the transaction and cancel any modification to the database;
SAVEPOINT: Create a storage point in the transaction, which is equivalent to clicking the save point of the game~
ROLLBACK TO <storage point>: Roll back the transaction to the specified storage point. It is equivalent to clicking the game's back file !


Oracle Sql operator

Arithmetic operators Addition, subtraction, multiplication, and division ±*/ …
Comparison operator = != <<=> >= BETWEEN~AND (between…) IS NULL (null or not) LIKE (fuzzy query) IN (range query)
logical operator AND (and) OR (or) NOT (not)
set operator

Combine the two query results into a result set: (the concept of high school mathematics ~)
some rules need to be followed before use: 1. The number of table columns in the two queries, and the types must match and correspond... 2. This query operation is not suitable For LOG type data, the column headings displayed at the end are subject to the first select;
UNION ( Union: Combine the two query results together, and delete duplicate rows)
UNION ALL (Union: combine the two query results Combined together, including duplicate data)
INTERSECT (Intersection: only returns the same data that both tables have)
MINUS (Minus: in the first query result, exclude rows that appear in the second query result eg: Table 1 Data ABC Table 2 Data A minus set is BC)

Concatenation operator ||

The use of || in Oracle to concatenate strings is similar to the + sign in Mysql;
example: scott login ~
select EName || Job from emp; (concatenate the EName column and the Job column)

-- 以dept表举例
select * from dept 
 
-- 事务操作语句 TCL
-- 新增
insert into dept values (50,'开发','');
insert into dept values (60,'测试','');
savepoint a ;                             -- 设置存储点;
insert into dept values (70,'人事','');   -- 新增
rollback to a;                            -- 回滚到存储点;
commit;                                   -- 提交事务;
   
-- 模拟分页  5~6条记录;
select * from (
       select d.*, rownum as r  from dept d   
) dd where r>4 and r<=6

SQL function

Function, easy to understand, is used to complete a specific operation. Oracle implements this operation, just like the Java method;
Oracle's commonly used functions are: Single-line function, aggregate function, conversion function...

Conversion function

Will refer to the operation of a number type -> conversion to -> another data type;

function Features
TO_CHAR() Convert a data type to a string type;
TO_DATE() Convert char or varchar type to time type
TO_NUMBER() Convert the character type of a number to a numeric type;

TO_CHAR()

Syntax
TO_CHAR( d|n, [,fmt] );
Parameter, d or n is optional [,fmt ]; d represents date type data, n is numeric type data; optional [,fmt] refers to the format type of the parameter;

TO_DATE( char,[fmt] )
TO_NUMBER( char|varchar )

select * from dual
-- TO_CHAR(d|n,[,fmt]);

-- dual 提供的最小的工作表,任何用户都可以访问; 只有一行一列,具有某bai些特殊功用。常用来通过select语句计算常数表du达式。
-- sysdate 获取当前系统时间;
-- fmMM  fmDD: fm是指把 01 09这种,使用空格或者0填充给替换调不需要!
SELECT TO_CHAR(sysdate,'YYYY"年"fmMM"月"fmDD"日" HH24:MI:SS') FROM dual;  -- 将当前时间转换成字符类型 年月日时分秒~;

select TO_CHAR(sysdate,'MM') FROM dual;                                   -- 只获取当前月份!

-- 9:表示数值的格式   S:表示 + - 数符号  
select To_CHAR(123,'$999.99S') FROM dual;                                 -- 把数字123 转换为字符 $123.00 加$符号字符串;

-- B:如果数值是给小数整数部分是0 就显示为空格;
select TO_CHAR(0.44,'B999.9') FROM dual;                                  
-- ...还有很多不一一举例;


-- TO_DATE( char,[fmt] )

-- 将字符类型 转换成 时间格式(就可以参与比较~但Oracle以及对字符进行隐式转换了..);   fm去0!
select TO_DATE('2000-09-09','yyyy-fmmm-fmdd') FROM dual;

-- TO_NUMBER( char|varchar )

-- 将字符类型 转换成 数值格式(就可以参与运算了~  Oracle貌似已将进行隐式转换了..) 
select  SQRT(To_NUMBER('100')) FROM dual;                                 -- 将100字符转换成数值,并 sqrt(); 获取其平方根;
-- 10*10=100;  

Other functions:

In addition to date functions, number functions, and conversion functions, Oracle also provides some one-line functions generally called "other functions";

function Features
NVL( expl1, expl2 ) If the value of expl1 is null, return the value of expl2; if it is not null, return the value of expl1;
NVL2( expl1, expl2, expl3 ) If expl1 is null, return the value of expl3; if it is not null, return the value of expl2;
DECODE( value, if1, then1, if2, then2, …else ) If the value is if1, return the value of if1; if the value is if2, return the value of if2... If there is no match, return else;
-- NVL( expl1, expl2 )
select nvl(null,1) from dual;

-- NVL2( expl1, expl2, expl3 )
select nvl2(null,1,2) from dual;

-- DECODE( value, if1, then1, if2, then2, …else )
select decode(
       1,         -- value    
       1 ,1,      -- if1 ,then1
       2,2,       -- if2 ,then2,
       3          -- else
) from dual;

--实战: scott用户下emp表;
select * from emp;

-- 查询emp表: ename sal comm
select ename , sal , comm  ,
    sal + nvl(comm,0) as s1 ,                     -- 如果comm列为null 就是0,与sal加;
    nvl2(comm , sal+comm , sal ) as s2 ,          -- 如果comm列为null 就sal 不是null就sal+comm;
    to_char(hiredate,'mm') as m,                  -- 获取入职的月份;
    decode(to_char(hiredate,'mm'),'01','一月',    -- 根据月份判断,并输出字符...
                                  '02','二月',
                                  '03','三月',
                                  '04','四月',
                                  '05','五月',
                                  '06','六月',
                                  '下半年'            
    ) as mm,
 from emp 

Analysis function:

Oracle 8.1.6 version provides analysis functions, which operate on a set of query results, and then obtain the results...
Syntax:

Function name ([parameter]) OVER( [partition clause] [sort clause])
function name: analysis function name
parameter: parameter
partition clause (PARTITION BY column) that the function needs to pass in : divide the query result into different Group, the function is similar to GROUP BY statement.
Sorting clause (ORDER BY asc|desc): sort each partition

Common functions:

-Group by deptno, sort by sal;

function Features
RANK Rows with equal values ​​are ranked the same, and the ordinal number then jumps,:1~3.. 如果,1记录与2记录相同则序号都是 1,不同的数据序号是3
DENSE_RANK Rows with equal values ​​are ranked the same, and the serial numbers are consecutive:不会因为相同的记录跳跃排序,会出现多个相同的序号
ROW_NUMBER Returns consecutive ranks, regardless of whether the values ​​are equal

EMP表是 Scott用户下都有的一个系统测试表! 放心使用~

-- 分析函数
-- emp表,以deptno 列分析~
select 
e.*,   
-- 根据deptno 分组, sal排序;
rank()       over(partition by deptno order by sal desc ) as r1,    -- 具有相等值的行排位相同,序数随后跳跃
dense_rank() over(partition by deptno order by sal desc ) as r2 ,   -- 具有相等值的行排位相同,序号是连续的
row_number() over(partition by deptno order by sal desc ) as r3     -- 返回连续的排位,不论值是否相等
from emp e;

Guess you like

Origin blog.csdn.net/qq_45542380/article/details/108994126