Differences between Oracle and MySQL

Small chat: This article will introduce the difference between Oeacle and MySQL in the use of Xiaobai when learning to use it. Because most people will come into contact with MySQL first, although both use SQL as the programming language, there is not much difference in the process of roughly operating the database. However, because Oracle's data structure is different from other databases, some sql operations are written differently from MySQL. This article will only introduce the differences between Oracle and MySQL, so you need to understand the basics of MySQL using sql first, and then use it in conjunction with Oracle to avoid confusing the usage habits of the two databases.

MySQL's sql use, if necessary, recommend "MSQL Use sql Encyclopedia (Complete + Details)"


1. The architecture is different

1.1. MySQL storage structure

Take InnoDB as an example

  • Action Hierarchy

1) database

As a relational database, MySQL uses DBMS (DataBase Management System) to manage and operate database storage, and SQL (Structured Query Language) as a programming language.
You can create multiple database stores, create tables and other structures in each database, and each table has a table space.

2) User

Then there are users. The user with the highest authority in MySQL is root, which exists at the beginning. There are also some other system users. The root user can create other users and grant them rights. The level is above the database. Users jointly manage databases and tables according to their own authority. .

  • logical storage structure

1) table space

At the highest level of the logical structure of the InnoDB storage engine, ibd files are actually tablespace files. Each ibd file corresponds to a table, and a tablespace can contain multiple segments.

2) segment

The table space is composed of various segments, common segments include data segment, index segment, rollback segment, etc. The management of segments in InnoDB is done by the engine itself, without manual control. A segment contains multiple areas.

3) District

The area is the unit structure of the table space, and the size of each area is 1M. By default, the InnoDB storage engine page size is 16K, that is, there are 64 consecutive pages in an area.

4) page

A page is the smallest unit of an area, and a page is the smallest unit of InnoDB storage engine disk management. The default size of each page is 16KB. In order to ensure the continuity of pages, the InnoDB storage engine applies for 4-5 areas from the disk each time.

5) OK

The InnoDB storage engine is row-oriented, that is to say, data is stored by row. In addition to the fields specified when defining the table, each row contains two hidden fields (described in detail later).


1.2. Oracle storage structure

  • Action Hierarchy

1) database

The concept of the Oracle database is different from other databases. The database here is an operating system with only one library. It can be seen that Oracle has only one large database. An Oracle instance (Oracle Instance) consists of a series of background processes (Backguound Processes) and memory structures (Memory Structures). A database can have n instances.

2) Table space

Oracle's tablespace concept is different from MySQL's because there is only one library, and Oracle allows multiple tablespaces to be created to store management data. The table space is Oracle's logical mapping to the related data files (ORA or DBF files) on the physical database. A database is logically divided into one or several table spaces, and each table space contains a set of logically related structures. Each database has at least one table space (called the system table space).

Each table space consists of one or more files on the same disk, these files are called data files (datafile). A data file can belong to only one tablespace.

3) Data file (dbf)

A data file is the physical storage unit of a database. The data of the database is stored in the table space, which is actually in one or more data files. A tablespace can consist of one or more data files, and a data file can only belong to one tablespace. Once a data file is added to a tablespace, the file cannot be deleted. If you want to delete a data file, you can only delete the tablespace it belongs to.

4) User

Oracle's maximum authority user is system, which initially exists. Users are created under tablespaces. After logging in, users can only see and operate their own tables. ORACLE users are similar to MYSQL databases. Every time an application is created, a user needs to be created.

Table data is put into a certain table space by the user, and this table space will randomly put these table data into one or more data files.
Because the oracle database is not an ordinary concept, oracle has users and table spaces to manage and store data. But the table is not queried by the table space, but by the user. Because different users can create tables with the same name in the same table space! The distinction here is the user!

insert image description here

  • logical storage structure

insert image description here

  • Summarize

The Oracle database is different from the MySQL database. Oracle can be compared to a mirror image. It can generate multiple database instances (that is, background processes, which means that we can start multiple instances after installing a database application. Generally, we do not do this, but Explain that it can do this); each instance is equivalent to a database, and it can only have one database and can have multiple table spaces; unlike MySQL, MySQL can have multiple users and the Root user creates and allocates databases and Table operation permissions, while Oracle creates users at the table space level, and assigns users the permissions to operate the data tables in the table space; table spaces can have levels such as districts, segments, and data blocks according to storage, but the data is actually It exists in the data file ( ①dbf/ora ), but we indirectly use the table space to operate the data file.

Because of ORacle's unique data structure, Oracle introduced the concept of table space to facilitate the management of Oracle data. Its idea is that "a table space is a logical unit, but it manages many physical units". Why? Because these physical files can be allocated to different servers, in this way, multiple servers can be used to reduce the overall pressure on an Oracle database disk. If you want to use multiple servers like MySQL, you can only achieve horizontal and vertical database partitioning or read Write separation. Regardless of where my data files are stored, Oracle always operates only one table space. The design of the table space is also one of the powerful manifestations of Oracle.

(Note ①: ORACLE8iThe suffix name of the previous data file is .orafollowed by .dbf; whether .oraor .dbf, there is no difference in actual use, and you can also use no extension or specify any extension, just use the extension to identify the type of the file. So for data files Either way ora/dat/dbf, it's the same, there's no difference)


2. The following is the difference between Oracle using SQL statements

3. DDL (Data Definition Language)

3.1. Oracle create tablespace

Oracle unique table space, Mysql does not

create tablespace waterboss
datafile 'c:\waterboss.dbf'
size 100m
autoextend on
next 10m

waterboss is the tablespace name

datafile is used to set the physical file name

size is used to set the initial size of the tablespace

autoextend on is used to set automatic growth, if the storage capacity exceeds the initial size, automatic expansion will start

next is used to set the size of the expansion space


3.2. Oracle table-specific field types

  • character type

Oracle has char, varchar2, and nuarchar2 character types, and it is usually recommended to use varchar2

type name byte size default byte size illustrate
char() 0 ~ 2000 1 The fixed-length string will be filled with spaces to reach the maximum length of the device, and an error will be reported if the length exceeds.
varchar2() 0 ~ 4000 1 Variable-length string, when storing data, if the given data does not occupy the given space, it will be automatically truncated to save space.
If the length exceeds, it will make up the length, and no error will be reported;
and it converts the original feature of varchar that can store empty strings into one that can store null values, providing backward compatibility;
nuarchar2() 0 ~ 4000 2 A variable-length string containing data in unicode format, a space occupies 2 bytes, and the maximum length is twice that of NCHAR.
The length does not mean the number of bytes, but the number of characters. For example, nuarchar2(10) means that 10 characters can be stored

Extended Q&A:

Q: Why not use all varchar2 directly?

Answer: 1) Although VARCHAR2 is more space-saving than CHAR, if a VARCHAR2 column is frequently modified, and the length of the data modified each time is different, this will cause the phenomenon of 'row migration' (RowMigration), which will cause redundant I /O is something that should be avoided in database design and adjustment. In this case, it would be better to replace VARCHAR2 with CHAR;

2) Also, when we store data of known fixed length, such as: mobile phone number (11 digits), ID card number (18 digits), etc., we can consider using char. Because, when querying data, for char type fields, it is a whole character match; and varchar2 is a character by character match;

3) And the efficiency of char is higher than that of varchar2, and some space must be sacrificed in order to improve efficiency.

  • number type
type name illustrate
number In Oracle, the int type in mysql is canceled and number is used instead. If you use int type when creating a database table, it will be automatically converted to number type, and Oracle does not have this "auto_increment" attribute, so it cannot be like MySQL. Generally, an auto-increment primary key is defined in the table. However, the sequence (SEQUENCE) in Oracle can indirectly realize the role of the auto-increment primary key.
number(p,s) p is the English abbreviation of precision, that is, the precise abbreviation, indicating the number of significant digits, and the maximum number of effective digits cannot exceed 38; s
is the English abbreviation of scale, indicating the number of digits at the decimal point, and the extra digits must be rounded off.
  • floating point
type name default byte size illustrate
binary_float 32 Single-precision floating-point numeric data type. Can support at least 6-bit precision, each binary_float value requires 5 bytes, including the length byte.
binary_double 64 Double-precision floating-point numeric data type. Each binary_double value requires 9 bytes, including the length byte.

3.3. Oracle has no auto_increment attribute

Solution: use sequences and triggers.

Example of use

-- 1.建立一个表,menuId是需要自增的字段
create table menu( 
menuId number(10) not null primary key,
name varchar2(40) not null,
id_parent number(10) not null,
);

-- 2.然后建立一个序列,最小值是minvalue,最大值是maxvalue,从1开始,步进为1递增,无循环,无缓存。
-- 关于create sequence的详细用法。
create sequence menu_autoinc_seq
minvalue 1
maxvalue 999999999
start with 1
increment by 1
nocycle;

-- 3.然后建立一个触发器,在插入tun_menu表之前触发,选取序列的nextval作为新值。
-- 关于create trigger的详细用法。
create or replace trigger menu_autoinc_tg
before insert on menu
for each row
begin
select menu_autoinc_seq.nextval into :new.menuId from dual;
end menu_autoinc_tg;

-- 4.最后检验成果,看是否能让字段自动增加,向menu表中添加数据,无论menuId是什么值都会被替换掉
insert into menu values(null, '宫保鸡丁',1);
insert into menu values(null, '红烧茄子',6);
insert into menu values(null, '麻辣香锅',3);

3.4. Differences in the use of quotation marks in Oracle

  • MySQL

1) Single quotes: Enclose string constants. If the constant itself has single quotes, in addition to the escape function, you can also use double quotes to enclose the whole;

'student' 
stu'dent转义: 'stu\'dent' 或 'stu''dent'(单引号对其转义)
stu'dent双引号括起: "stu'dent" 

2) Double quotes: Enclose string constants. If the constant itself has double quotes, in addition to escaping, you can also use single quotes to enclose it as a whole;

say:"Hello"的转义: "say:\"Hello\"""say:""Hello"""(两个双引分别转义)
say:"Hello"单引号括起: 'say:"Hello"'

In mysql, double quotation marks will report errors in some versions. To avoid this, try to use single quotation marks to manipulate strings.

3) Backticks: A symbol that distinguishes reserved words (that is, keywords) from ordinary characters;

create table desc;   报错
create table `desc`; 创建成功

Even if the table name and field name are not reserved words in the database, it is a good habit to add backquotes as much as possible, which can avoid mistakes and ensure the smooth progress of development

  • Oracle

1) Single quotes: enclose string constants;

2) Double quotes: Mandatory case-sensitive, that is, Oracle also supports lowercase;

CREATE TABLE "StUdEnT" (...);
# 建表时使用双引号严格指定大小写,在查询时就要使用相同的方式,如下,否则报错
SELECT * FROM "StUdEnT";

3) backtick: does not exist


3.5. Oracle does not exist: “drop table if exists”

Mysql determines whether the table exists before creating the table, and deletes the existing table if it exists

DROP TABLE IF EXISTS tableName;

Set triggers, Oracle determines whether the table exists before creating the table, and deletes the existing table if it exists

declare  -- 声明
      num number; -- 定义变量
begin  -- 开始
    select count(1) into num from user_tables where table_name = upper('tableName');  -- 给自己定义的变量赋值
    if num > 0 then	-- 语法
        execute immediate 'drop table tableName' ;
    end if;
end; -- 结束

This is very troublesome. If you save a little trouble, just check it to see if it has been recreated.


4. DML (Data Manipulation Language)

4.1. Oracle cannot batch insert

  • MySQL adds multiple pieces of data at once
insert into 表名 (字段名1, 字段名2, 字段名3) values (1,2,3), (1,2,3), (1,2,3) .....;
  • Oracle cannot add multiple pieces of data at one time, it will report an error, only one insert can add one row of data
insert into department values(null, '指挥部'),(null, '侦查部');
报错:ORA-00933: SQL command not properly ended
insert into department values(null, '指挥部');
insert into department values(null, '侦查部');
执行成功!

5. DQL (Data Query Language)

5.1. Oracle query based on pseudo column - ROWID

During the use of Oracle tables, there are some additional columns in the actual table, which are called pseudo-columns. Pseudo-columns are like table columns, but are not stored in the table. Pseudo-columns can only be queried, and cannot be added, deleted or modified.

Each row in the table has a physical address in the data file, and the ROWID pseudo-column returns the physical address of the row. Use ROWID to quickly locate a row in the table. ROWID value can uniquely identify a row in the table. Since ROWID returns the physical address of the row, using ROWID shows how the row is stored.

  • example
select t.ROWID, t.* from GIRL t;

insert image description here

  • We can query records by specifying ROWID
select t.ROWID, t.* from GIRL t; where ROWID='AAAM1fAAGAAAAAuAAA';

insert image description here

Note: When we add the xxx.rowid query field in the query sql, we can directly perform graphical keyboard input update operations in the graphical result table, for example:

select r.* from role r;  # 不可修改图形化返回结果表
select r.rowid, r.* from role r; # 解锁后,可修改图形化返回结果表



5.2. Oracle query based on pseudo column - ROWNUM

In the result set of the query, ROWNUM identifies a row number for each row in the result set, the first row returns 1, the second row returns 2, and so on. The ROWNUM pseudo-column can limit the number of rows returned in the query result set.

  • example
select rownum, g.* from GIRL g;

insert image description here


5.3. Oracle's outer join query

In left/right joinaddition also provides a +super-intuitive and convenient query method with , which is not supported by MySQL.

  • SQL1999 standard extra-syntactic join query
-- outer 可以省略
select 字段名 from 左表 left [ outer ] join 右表 on 条件;  # 左外连接查询
select 字段名 from 左表 right [ outer ] join 右表 on 条件;  # 右外连接查询
  • Oracle unique query
select 字段名 from 左表 a, 右表 b, where a.属性 = b.属性(+);  # 左外连接查询
select 字段名 from 左表 a, 右表 b, where a.属性(+) = b.属性;  # 右外连接查询

+Remember not to get the order wrong, the trick is: the left outer join query needs to ensure that all the data in the left table is displayed, and the data on the right is supplemented, so it must be added to the conditions of the right table +; the same is true for the right outer join query.


5.4. Oracle paging and sorting pagination query

Because Oracle does not have the limit keyword, the implementation of paging needs to use other methods to write sql, and the rowsum is used, which has been introduced above.

  • Query the first five pieces of data in the table
select rownum,t.* from users t where rownum<=5;

insert image description here

  • 6th to 10th data of the query table
-- select rownum,t.* from users t where rownum>5 and rownum<=10; -- 错误sql,查询无结果
-- 子查询方式实现
select * from 
(select rownum r,t.* from users t where rownum<=10) 
where r>5;

insert image description here

Why is there no result for the first sql?

This is because the rownum is generated when the query statement scans each record, so the symbol "greater than" cannot be used, only "less than" or "less than or equal to" can be used, and "equal to" is not enough.

  • Sorting-based pagination query: query the 5th to 10th records in descending order by age
 -- 错误SQL,结果没有按要求正确排序
select * from (select rownum r, t.* from users t where rownum<=10 order by age desc) where r>5 ;

insert image description here

Why is it not sorted normally?

Because the generation of the ROWNUM pseudo-column is generated when the table records are scanned, and the sorting is performed later, the ROWNUM has already been generated during the sorting, so the ROWNUM is messed up after the sorting. So it needs to be sorted first, and then the paged data is taken from the sorted table (note. Here, the rownum in the subquery needs to be aliased as the query condition)

-- 正确sql:第一种方式:三层嵌套查询
select * from 
(select rownum r,t.* from (select * from users order by age desc) t where rownum<=10) 
where r>5

insert image description here

-- 正确sql:第二种方式:使用分析函数ROW_NUMBER,用 row_number()分析函数实现的分页查询相对三层嵌套子查询要简单,只有两层查询
select * from 
(select row_number() over(order by age desc) rownumber, t.* from users t) 
where rownumber>5 and rownumber<=10

insert image description here


6. DCL (Data Control Language)

Because oracle users are created based on tablespaces, we need to specify tablespaces during user operations. Mysql does not have such a concept. If you want to see the sql comparison, please move to "MySQL uses sql Encyclopedia"

6.1. Create user

create user wateruser
identified by abc
default tablespace waterboss

wateruser is the created username

identified by is used to set the user's password

default tablesapce is used to specify the default tablespace name


6.2. Modify user

alter user wateruser
identified by ABC
default tablespace waterboss

wateruser is the created username

identified by is used to set the user's password

default tablesapce is used to specify the default tablespace name


6.3. Delete user

drop user wateruser

wateruser is the username to delete


6.4. User authorization

Oracle provides three standard roles (role): connect, resourceand dba.

  • connect role

Temporary users, especially users who do not need to create tables, are usually only given the connect role
connect is to use oracle simple permissions, which only have access to other users' tables, including select/insert/update and delete.
Users with a connect role can also create tables, views, sequences, clusters, synonyms, sessions, and other data links.

  • resource role

More reliable and official database users can be granted resource role.
resource provides additional permissions to users to create their own tables, sequences, procedures (procedures), triggers (triggers), indexes (index) and clusters (clusters)

  • dba role (database administrator role)

The dba role has all system privileges
, including unlimited space quotas and the ability to grant various privileges to other users.

  • System permission classification
permissions illustrate
DBA With all privileges, it is the highest authority of the system, and only the DBA can create the database structure.
RESOURCE Users with Resource permissions can only create entities, not database structures.
CONNECT Users with Connect privileges can only log in to Oracle, but cannot create entities or database structures.
  • use

For ordinary users: grant connect, resource permissions.

For DBA management users: grant connect, resource, dba permissions.

  • Example of use
grant connect, resource to wateruser;
grant dba to fireuser

Grant connect and resource privileges to user wateruser; grant DBA privileges to user fireuser


6.5. User withdrawal

revoke connect, resource from wateruser;
revoke dba from fireuser

Revoke the connect and resource privileges granted to the user fireuser; revoke the DBA privileges granted to the user fireuser


6.6. Query users

query all users

select * from all_users;

7. One-line functions

  • usefulness

1) View various information of the current user

2) Used to call system functions

7.1. Pseudo-table dual

Also called a virtual table, it is used to form the grammatical rules of select. Oracle guarantees that there is always only one record in dual.
To put it simply, the dual table is a table automatically created by oracle and the data dictionary. This table is a table with a single row and a single column. This table has only one column: DUMMY, and the data type is VERCHAR2(1). There is only one data in the dual table X, Oracle has internal logic to ensure that there is always only one piece of data in the dual table. The dual table is mainly used to select system variables or find the value of an expression.

select d.rowid, d.* from dual d;

insert image description here

  • Use dual query (example)

1) Get the current system time

select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') from dual;

2) Get the hostname

select SYS_CONTEXT('USERENV','TERMINAL') from dual;

3) Get the current locale

elect SYS_CONTEXT('USERENV','language') from dual;

4) Get a random number

select dbms_random.random from dual;

5) Sequence operation, we used it when setting auto-increment

select your_sequence.nextval from dual; -- 获得序列 your_sequence的下一个值
select your_sequence.currval from dual; -- 获得序列your_sequence的当前值

6) Can be used for calculator operations

select 7*9 from dual;

7.2. Character functions

  • effect

Character functions can be used to modify the sql query result value and then return the final result that needs business.

Of course, MySQL also has similar functions. Here we only talk about Oracle. For convenience, the dual virtual table is used as a demonstration. In fact, you can query the real table and perform operations on the returned results.

function illustrate
ASCII Returns the decimal value of the corresponding character
CHR gives the decimal return character
CONCAT Concatenates two strings, same as ||
INITCAT Make the first letter of a string uppercase
INSTR find the position of a string
INSTRB Find the position and number of bytes in a string
LENGTH gives the length of the string in characters
LENGTHB gives the length of the string in bytes
LOWER Convert a string to lowercase
LPAD Pads to the left of the character with the specified character
LTRIM crop the specified characters on the left
RPAD Pads to the right of the character with the specified character
RTRIM crops the specified characters on the right
REPLACE Perform string search and replace
SUBSTR take a substring of a string
SUBSTRB Take a substring of a string (in bytes)
SOUNDEX returns a homonym string
TRANSLATE Perform string search and replace
TRIM Cut off the preceding or following string
UPPER convert a string to uppercase
  • Examples of common character functions

(1) Find the string length LENGTH

select length('ABCD') from dual;
-- 结果:4

(2) Find the substring SUBSTR of the string

select substr('ABCD',2,2) from dual;
-- 结果:BC

(3) String concatenation CONCAT

select concat('ABC','D') from dual;
-- 结果:ABCD
-- 也可以用 || 对字符串进行拼
select 'ABC'||'D' from dual;
-- 结果:ABCD

(4) Find out the string position INSTR:

select INSTR('abcdbc', 'b', 1, 1) from dual; -- 原字符串;要查找的字符串;查找初始位置;查找第几个。返回子字符串索引
-- 结果:2

7.3. Numeric functions

function illustrate
ABS(value) 绝对值
CEIL(value) 大于或等于 value 的最小整数
COS(value) 余弦
COSH(value) 反余弦
EXP(value) e 的 value 次幂
FLOOR(value) 小于或等于 value 的最大整数
LN(value) value 的自然对数
LOG(value) value 的以 10 为底的对数
MOD(value,divisor) 求模
POWER(value,exponent) value 的 exponent 次幂
ROUND(value,precision) 按 precision 精度 4 舍 5 入
SIGN(value) value 为正返回 1;为负返回-1;为 0 返回 0.
SIN(value) 余弦
SINH(value) 反余弦
SQRT(value) value 的平方根
TAN(value) 正切
TANH(value) 反正切
TRUNC(value,按 precision) 按照 precision 截取 value
VSIZE(value) 返回 value 在 ORACLE 的存储空间大小
  • 常用字符函数举例

  • (1)四舍五入函数 ROUND

    select round(100.567) from dual;
    -- 结果:101
    select round(100.567, 2) from dual; -- 保留两位小数
    -- 结果:100.57
    
  • (2)截取函数 TRUNC

    select trunc(100.567) from dual; -- 去整
    -- 结果:100
    select trunc(100.567, 2) from dual; -- 保留两位小数
    -- 结果:100.56
    
  • (3)取模 MOD

    select mod(10, 3) from dual;
    -- 结果:1
    

7.4. 日期函数

函数 说明
ADD_MONTHS 在日期 date 上增加 count 个月
GREATEST(date1,date2,. . .) 从日期列表中选出最晚的日期
LAST_DAY( date ) 返回日期 date 所在月的最后一天
LEAST( date1, date2, . . .) 从日期列表中选出最早的日期
MONTHS_BETWEEN(date2, date1) 给出 Date2 - date1 的月数(可以是小数)
NEXT_DAY( date,’day’) 给出日期 date 之后下一天的日期,这里的 day 为星期,如: MONDAY,Tuesday 等。
NEW_TIME(date,’this’, ’other’) 给出在 this 时区=Other 时区的日期和时间
ROUND(date,’format’) 未指定 format 时,如果日期中的时间在中午之前,则将日期中的时间截断为 12 A.M.(午夜,一天的开始),否则进到第二天。时间截断为 12 A.M.(午夜,一天的开始),否则进到第二天。
TRUNC(date,’format’) 未指定 format 时,将日期截为 12 A.M.( 午夜,一天的开始).

我们用 sysdate 这个系统变量来获取当前日期和时间,语句如下:

select sysdate from dual;
-- 结果:2022/11/12 1:24:14
  • 常用字符函数举例

(1)加月函数 ADD_MONTHS :在当前日期基础上加指定的月

select add_months(sysdate, 2) from dual;
-- 结果:2023/1/12 1:26:35

(2)求所在月最后一天 LAST_DAY

select last_day(sysdate) from dual;
-- 结果:2022/11/30 1:27:51

(3)日期截取 TRUNC

select TRUNC(sysdate) from dual;
-- 结果:2022/11/12

select TRUNC(sysdate,'yyyy') from dual;
-- 结果:2022/1/1

select TRUNC(sysdate,'mm') from dual;
-- 结果:2022/11/1

7.5. 转换函数

函数 描述
CHARTOROWID 将 字符转换到 rowid 类型
CONVERT 转换一个字符节到另外一个字符节
HEXTORAW 转换十六进制到 raw 类型
RAWTOHEX 转换 raw 到十六进制
ROWIDTOCHAR 转换 ROWID 到字符
TO_CHAR 转换日期格式到字符串
TO_DATE 按照指定的格式将字符串转换到日期型
TO_MULTIBYTE 把单字节字符转换到多字节
TO_NUMBER 将数字字串转换到数字
TO_SINGLE_BYTE 转换多字节到单字节
  • 常用字符函数举例

(1)数字转字符串 TO_CHAR

select TO_CHAR(1024) from dual;
-- 结果:1024

(2)日期转字符串 TO_CHAR

select TO_CHAR(sysdate,'yyyy-mm-dd') from dual;
-- 结果:2022-11-12

(3)字符串转日期 TO_DATE

select TO_DATE('2022-09-13','yyyy-mm-dd') from dual;
-- 结果:2022/9/13

(4)字符串转数字 TO_NUMBER

select to_number('100') from dual;
-- 结果:100

7.6. 分析函数

函数 描述
RANK 相同的值排名相同,排名跳跃。
DENSE_RANK 相同的值排名相同,排名连续
ROW_NUMBER 返回连续的排名,无论值是否相等。
  • 函数使用举例

(1)相同的值排名相同,排名跳跃

select t.*, rank() over(order by age desc) 年龄排名 from users t;

insert image description here

(2)相同的值排名相同,排名连续

select t.*, dense_rank() over(order by age desc) 年龄排名 from users t;

insert image description here

(3)返回连续的排名,无论值是否相等

select t.*, row_number() over(order by age desc) 年龄排名 from users t;

insert image description here


7.7. 其它函数

函数 描述
NVL NVL(检测的值,如果为null的值);
NVL2 NVL2(检测的值,如果不为 null 的值,如果为 null 的值);
DECODE decode(条件, 值 1, 翻译值 1, 值 2, 翻译值 2, …值 n, 翻译值 n, 缺省值); 说明:根据条件返回相应值
  • 函数使用举例

(1)空值处理函数 NVL

select NVL(NULL, 0) from dual;
-- 结果:0

(2) Null value processing function NVL2

select NVL2(NULL, '有值', '空') from dual;
-- 结果:空

(3) Conditional value decode

select decode(3, 1, '晴天', 2, '阴天', 3, '雨天', 666) from dual;
-- 结果:雨天

essay

insert image description here

Guess you like

Origin blog.csdn.net/m0_48489737/article/details/127823273
Recommended