在Oracle数据库的开发过程中,SQL(结构化查询语言)是不可或缺的。无论是进行数据查询、数据插入、更新还是删除,都需要使用到SQL语句。以下是一些在Oracle开发中常用的SQL语句示例。
1. 数据查询(SELECT)
基本查询
SELECT column1, column2, ...
FROM table_name
WHERE condition;
排序查询
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 ASC, column2 DESC;
分组查询
SELECT column_name(s), aggregate_function(column_name)
FROM table_name
WHERE condition
GROUP BY column_name(s);
连接查询(JOIN)
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
--或者使用 LEFT JOIN, RIGHT JOIN 等
2. 数据插入(INSERT)
插入完整行
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
插入部分行
INSERT INTO table_name (column1, column3, ...)
VALUES (value1, value3, ...);
插入子查询结果
INSERT INTO table_name (column1, column2)
SELECT column_a, column_b
FROM another_table
WHERE condition;
3. 数据更新(UPDATE)
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
4. 数据删除(DELETE)
DELETE FROM table_name
WHERE condition;
5. 创建表(CREATE TABLE)
CREATE TABLE table_name ( column1 datatype [constraint], column2 datatype [constraint], ...
);
6. 修改表结构(ALTER TABLE)
添加列
ALTER TABLE table_name
ADD column_name datatype [constraint];
删除列
ALTER TABLE table_name
DROP COLUMN column_name;
修改列的数据类型
ALTER TABLE table_name
MODIFY (column_name new_datatype);
7. 创建索引(CREATE INDEX)
CREATE INDEX index_name
ON table_name (column1, column2, ...);
8. 聚合函数
计数
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
求和
SELECT SUM(column_name)
FROM table_name
WHERE condition;
平均值
SELECT AVG(column_name)
FROM table_name
WHERE condition;
最大值和最小值
SELECT MAX(column_name), MIN(column_name)
FROM table_name
WHERE condition;
9. 事务控制(事务处理在PL/SQL中更常见,但SQL本身也支持)
提交事务
COMMIT;
回滚事务
ROLLBACK;
10. 视图(CREATE VIEW)
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
11、触发器
CREATE OR REPLACE TRIGGER trg_after_employees_insert
AFTER INSERT ON employees
BEGIN -- 更新employee_count表中的员工数量 UPDATE employee_count SET total_employees = total_employees + 1 WHERE count_id = 1; -- 假设只有一个记录,并且count_id为1
END;