create table toys (
toy_name varchar2(100),
colour varchar2(10),
price number(10, 2)
);
insert into toys values ( 'Sir Stripypants', 'red', 0.01 );
insert into toys values ( 'Miss Smelly_bottom', 'blue', 6.00 );
insert into toys values ( 'Cuteasaurus', 'blue', 17.22 );
insert into toys values ( 'Mr Bunnykins', 'red', 14.22 );
insert into toys values ( 'Baby Turtle', 'green', null );
commit;
选择行
放置星号会返回表中的所有可见列
select * from toys;
select toy_name, price from toys;
过滤数据
获取在列 toy_name 中存储“Sir Stripypants”的行
select * from toys
where toy_name = 'Sir Stripypants';
select * from toys
where colour = 'red';
组合标准
您可以使用 AND & OR 组合许多过滤器
AND:这将返回两个条件都为真的行。
toy_name 为 Sir Stripypants 的行。而且颜色是绿色的。Stripypants 爵士是红色的,所以这个查询什么都不返回
一个条件不成立
select * from toys
where toy_name = 'Sir Stripypants'
and colour = 'green';
OR 获取其中一个条件为真的所有行。小海龟的颜色是绿色。
select * from toys
where toy_name = 'Sir Stripypants' or
colour = 'green';
优先顺序
AND 的优先级高于 OR。因此,如果将两者都包含在 where 子句中,则放置它们的顺序会影响结果。
例如,以下两个查询从每一列中搜索相同的值。但它们返回不同的行
select * from toys
where toy_name = 'Mr Bunnykins' or toy_name = 'Baby Turtle'
and colour = 'green';
select * from toys
where colour = 'green'
and toy_name = 'Mr Bunnykins' or toy_name = 'Baby Turtle';
为避免将 AND 与 OR 组合的查询混淆,请使用括号。数据库首先处理括号内的条件。因此,以下两个查询都搜索以下行:
玩具名称是“兔宝宝先生”或“小海龟”
而且颜色是绿色的
select * from toys
where ( toy_name = 'Mr Bunnykins' or toy_name = 'Baby Turtle' )
and colour = 'green';
select * from toys
where colour = 'green'
and ( toy_name = 'Mr Bunnykins' or toy_name = 'Baby Turtle' );
值列表
select * from toys
where colour = 'red' or
colour = 'green';
查找所有颜色为红色或绿色的行
select * from toys
where colour in ( 'red' , 'green' );
值范围
要查找所有价格低于 10 的玩具
select * from toys
where price < 10;
价格大于或等于 6
select * from toys
where price >= 6;
使用条件之间,这将返回值从下限到上限的行。获取价格等于 6、20 或这两者之间的任何值的所有数据
select * from toys
where price between 6 and 20;
select * from toys
where price >= 6
and price <= 20;
select * from toys
where price > 6
and price <= 20;
通配符
下划线 (_) 正好匹配一个字符
匹配零个或多个字符的百分比 (%)
查找所有颜色以 b 开头的行
select * from toys
where colour like 'b%';
颜色以 n 结尾的行
select * from toys
where colour like '%n';
下划线正好匹配一个字符。因此,以下查找所有具有 toy_names 11 个字符长的行:
select * from toys
where toy_name like '___________';
e 的任一侧都只有一个字符
select * from toys
where colour like '_e_';
在字符串的任何位置包含 e 的任何颜色
select * from toys
where colour like '%e%';
空值
Where 子句仅返回测试为真的行。因此,如果您搜索价格等于 null 的行,您将不会得到任何数据:
select * from toys
where price = null;
要查找存储空值的行,您必须使用“is null”条件
select * from toys
where price is null;
否定
您可以通过在它之前放置 NOT 来返回大多数条件的相反结果。例如,要查找所有不是绿色的玩具
select *
from toys
where not colour = 'green';
不相等的条件,!= 或 <> 来获得相同的结果
select *
from toys
where colour <> 'green';
对此的一个例外是 null。搜索不等于 null 的行仍然不返回任何内容(错误的)
要获取具有非空值的所有行,您必须使用 is not null 条件:
select *
from toys
where colour is not null;