oracle基本查询用法入门示例

2020-02-20 12:00:23于海丽

本文实例讲述了oracle基本查询用法。,具体如下:

一、基本select语句

SELECT *|{[DISTINCT] column|expression [alias], ...}
FROM table;

例如:

--查询所有数据
select * from emp;

--查询指定列数据
select empno,ename,sal from emp;

--算数运算符(+ - * /)
select ename,sal,sal+30 from emp;

--使用括号
select ename,sal,12*(sal+30) from emp;

--定义空值
--(空值是无效的,未指定,未知的或不可预知的值,空值不是空格或是0)
select ename,job,sal,comm from emp;

--空值的数学运算
--包含空值的数学表达式的值都为空值
select ename,12*sal+comm from emp;

--列的别名
--别名使用双引号,AS可以省略
select deptno as "no",ename as "name" from emp;

--连接符,把列与列,列与字符连接在一起
select deptno || '--' || ename from emp;

--字符串
--日期和字符只能在单引号中出现
select 'hello ' || ename from emp;

--删除重复行
select distinct deptno from emp;

--显示表结构
desc[ribe] tablename;

二、过滤和排序

SELECT *|{[DISTINCT] column|expression [alias], ...}
FROM table
[WHERE condition(s)];

例如:

--查询指定条件数据
select deptno,ename from emp where deptno=10;

--字符串和日期包含在单引号中
--字符串大小写敏感,日期格式敏感
select ename,job,deptno from emp where ename='King';

--比较运算符(= > < <= >= <> !=)
select ename,sal from emp where sal<1500;

--其他比较运算符
--BETWEEN ... AND ... 在两个值之间包含边界
--IN(set) 等于值列表中的一个
--LIKE 模糊查询

--IS NULL 空值
select ename,sal,deptno from emp where deptno in(10,30);
select ename,sal,comm from emp where comm is null;

--逻辑运算(AND OR NOT)
select ename,sal from emp where deptno=10 and sal>1500;

排序

ORDER BY 字段 [DESC|ASC]

例如:

select ename,sal from emp order by sal desc;
--多列排序
--先按第一列排序,如果相同,则按第二列排序,以此类推
select * from emp order by sal desc,hiredate desc;

三、单行函数

1、字符函数

--LOWER 转换小写
--UPPER 转换大写
--INITCAP 首字母大写
select lower(ename) from emp;
--CONCAT 接接字符串
--SUBSTR 截取字符串
--LENGTH 字符串长度
--INSTR 查找字符串
--LPAD 左边填充字符
--RPAD 右边填充字符
--TRIM([leading|trailing|both] 字符串1 from 字符串2) 
--TRIM可以删除两边空格,也可删除其他字符
--REPLACE 替换字符串
select concat('aa','bb') from emp;
select substr('abcdefg', 2, 3) from emp;
select length('test...') from emp;
select instr('hello world', 'w') from emp;
select lpad(sal, '10', '0') from emp;
select rpad(sal, '10', '*') from emp;
select trim(' test ') from emp;
--从尾部删除字符串*号
select trim(trailing '*' from '**1212121**') from emp;
--把字符串中的22替换成88
select replace('11223344', '22', '88') from emp;