500 likes | 721 Views
SQL 結構化查詢語言. SQL 語言種類. 資料處理型語言( DML Data Manipulation Language) SELECT,INSERT,UPDATE,DELETE 交易控制型語言( Transaction Control) COMMIT,ROLLBACK,SAVEPOINT. SQL 語言種類(續). 資料定義型語言( DDL Data Definition Language) CREATE,ALTER,DROP 資料控制型語言( DCL Data Control Language) GRANT,REVOKE,SET ROLE.
E N D
SQL語言種類 • 資料處理型語言(DML Data Manipulation Language) • SELECT,INSERT,UPDATE,DELETE • 交易控制型語言(Transaction Control) • COMMIT,ROLLBACK,SAVEPOINT
SQL語言種類(續) • 資料定義型語言(DDL Data Definition Language) • CREATE,ALTER,DROP • 資料控制型語言(DCL Data Control Language) • GRANT,REVOKE,SET ROLE
一、資料處理型語言(DML) • SELECT Syntax(語法): SELECT [DISTINCT] {* , column [alias]..} FROM table ; * : selects all column column: select the name of column alias : give a select
Example : 1. SELECT * FROM emp ; 2. SELECT emp_no , emp_name FROM emp ;
Arithmetic Expressions 先乘除後加減,可以用括號改變次序
Example : SELECT emp_no , emp_name , emp_salary * 5 FROM emp ;
Column Aliases Example : SELECT emp_no AS 序號 , emp_name “姓名” FROM emp ;
Concatenation Operator Example : SELECT emp_no || emp_name AS “序號 姓名” FROM emp ;
Example : SELECT emp_no,emp_name,emp_dept FROM emp ; Example : SELECT emp_no,emp_name,NVL(emp_dept,’NO_WRITE) FROM emp ;
Duplicate Rows Example : SELECT emp_no,emp_name FROM emp ; Example : SELECT DISTINCT emp_no,emp_name FROM emp ;
Limit Condition and Order Syntax : SELECT expr FROM table WHERE condition ORDER BY expr ;
Comparison and Logical Operators • Logical comparison operators = > >= < <= • SQL comparison operators • BETWEEN ... AND... • IN(list) • LIKE • IS NULL • Logical operators • AND • OR • NOT
Negating Expressions • Logical Operators != <> ^= • SQL Operators • NOT BETWEEN • NOT IN • NOT LIKE • IS NOT NULL
BETWEEN and IN SQL Operators SQL> SELECT * 2 FROM emp 3 WHERE emp_no BETWEEN ‘1001' 4 AND ‘1025'; SQL> SELECT * 2 FROM emp 3 WHERE emp_dept IN (‘D01’,’D02’);
LIKE SQL Operator • You can use the LIKE operator to perform wildcard searches of valid search string values. • Search conditions can contain either literal characters or numbers. • "%" denotes none or many characters. • "_" denotes one character. SQL> SELECT * 2 FROM emp 3 WHERE emp_name LIKE ‘USER%5';
LIKE SQL Operator SQL> SELECT emp_name, emp_dept 2 FROM emp 3 WHERE emp_salary LIKE '%9%'; SQL> SELECT emp_name, emp_dept 2 FROM emp 3 WHERE emp_salary LIKE '%9_';
IS NULL SQL Operator • Test for null values with the = NULL operator. • Use the = operator. SQL> SELECT emp_name, emp_dept 2 FROM emp 3 WHERE emp_salary = NULL;
Multiple Conditions • Use complex criteria. • Combine conditions with AND or OR operators. • AND requires both conditions to be TRUE. • OR requires either condition to be TRUE.
Multiple Conditions SQL> SELECT * 2 FROM emp 3 WHERE emp_dept = ‘D01’ 4 AND emp_salary between 3000 AND 5000; SQL> SELECT * 2 FROM emp 3 WHERE emp_dept = ‘D01’ 4 OR emp_salary between 3000 AND 5000;
What Is a Join? • A join is used to query data from more than one table. • Rows are joined using common values, typically primary and foreign key values. • Join methods • Equijoin • Non-equijoin • Outer join • Self join • Set operators
Relations Between Tables S_EMP Table ID LAST_NAME DEPT_ID -- --------------- ------- 1 Velasquez 50 2 Ngao 41 3 Nagayama 31 4 Quick-To-See 10 5 Ropeburn 50 6 Urguhart 41 7 Menchu 42 8 Biri 43 9 Catchpole 44 10 Havel 45 11 Magee 31 12 Giljum 32 13 Sedeghi 33 14 Nguyen 34 15 Dumas 35 16 Maduro 41 S_DEPT Table ID NAME REGION_ID -- --------------- --------- 30 Finance 1 31 Sales 1 32 Sales 2 43 Operations 3 50 Administration 1 S_REGION Table ID NAME -- --------------------- 1 North America 2 South America 3 Africa / Middle East 4 Asia 5 Europe
Simple Join Query: Syntax • Write the join condition in the WHERE clause. • Precede each column name with the table name for clarity. • Column names must be prefixed with the table name when the same column name appears in more than one table. SELECT table.column, table.column FROM table1, table2 WHERE table1.column1 = table2.column2;
Server Equijoin: Example EMP DEPT LAST_NAME DEPT_ID ID NAME--------- ------- -- ---------------Velasquez 50 50 AdministrationNgao 41 41 OperationsNagayama 31 31 SalesRopeburn 50 50 AdministrationUrguhart 41 41 OperationsMenchu 42 42 OperationsBiri 43 43 OperationsHavel 45 45 Operations... ...
Server Additional Search Conditions Using the AND Operator: Example EMP DEPT LAST_NAME DEPT_ID ID NAME--------- ------- -- ---------------Velasquez 50 50 AdministrationNgao 41 41 OperationsNagayama 31 31 SalesRopeburn 50 50 AdministrationUrguhart 41 41 OperationsMenchu 42 42 OperationsBiri 43 43 OperationsHavel 45 45 Operations... ...
Non-Equijoins: Example • Non-equijoins result when no column in one table corresponds directly to a column in the second table. • The join condition contains an operator other than equal (=). SQL> SELECT e.ename, e.job, e.sal, s.grade 2 FROM emp e, salgrade s 3 WHERE e.sal BETWEEN s.losal AND s.hisal;
Outer Joins: Syntax • Use an outer join to see rows that do not normally meet the join condition. • Outer join operator is the plus sign (+). • Place the operator on the side of the join where there is no value to join to. SELECT table.column, table.column FROM table1, table2 WHERE table1.column(+) = table2.column;
Server Outer Joins CUSTOMER EMP SALES_LAST_NAME ID REP_ID NAME--------- -- ------ --------------Magee 11 11 WomansportMagee 11 11 Beisbol Si!Magee 11 11 Ojibway RetailGiljum 12 12 UnisportsGiljum 12 12 Futbol SonoraSedeghi 13 13 Hamada SportDumas 15 15 Sportique Sweet Rock Sports No Sales RepAssigned toSweet RockSports
Outer Joins: Example • Display the sales representative name and the customer name for all customers even if the customer has no sales representative. SQL> SELECT e.last_name, e.id, c.name 2 FROM s_emp e, s_customer c 3 WHERE e.id (+) = c.sales_rep_id 4 ORDER BY e.id;
Server Self Joins S_EMP (MANAGER) S_EMP (WORKER) LAST_NAME MANAGER_ID ID LAST_NAME--------- ---------- -- ----------Ngao 1 1 VelasquezNagayama 1 1 Velasquez Ropeburn 1 1 Velasquez Urguhart 2 2 NgaoMenchu 2 2 Ngao Biri 2 2 Ngao Magee 3 3 NagaymaGiljum 3 3 Nagayma ... ...
Self Joins: Example • Join rows in a table to rows in the same table by using a self join. • Simulate two tables in the FROM clause by creating two aliases for the table. SQL> SELECT worker.last_name||' works for '|| 2 manager.last_name 3 FROM s_emp worker, s_emp manager 4 WHERE worker.manager_id = manager.id;
What Is a Subquery? A subsequery is a SELECT statement embedded in a clause of another SQL statement. SELECT Syntax Main Query SELECT... FROM... WHERE... Subquery SELECT Syntax (SELECT... FROM... WHERE...);
Server Subqueries: Example S_EMP S_EMP LAST_NAME TITLE TITLE LAST_NAME--------- ----------- ----------- ---------Maduro Stock Clerk Stock Clerk SmithSmith Stock Clerk Nozaki Stock Clerk Patel Stock Clerk Newman Stock Clerk Chang Stock Clerk Patel Stock Clerk Dancs Stock Clerk Schwartz Stock Clerk
Subqueries: Syntax • The subquery executes once before the main query. • The result of the subquery is used by the main outer query. SELECT select_list FROM table WHERE expr operator (SELECT select_list FROM table);
How Are Nested Subqueries Processed? 1. Nested SELECT statement is executed first. 2. Result is passed into condition of main query. Nested Query Main Query SELECT dept_id FROM s_emp WHERE last_name='Biri'; SELECT last_name, title FROM s_emp WHERE dept_id = 43
Single Row Subqueries Write the SQLstatement todisplay thelast name and title of an employee. SELECT last_name, titleFROM s_empWHERE title = SELECT titleFROM s_empWHERE last_name = ’Smith’ Write the SQLstatement tofind out Smith’s title. SQL> SELECT last_name, title 2 FROM s_emp 3 WHERE title = 4 (SELECT title 5 FROM s_emp 6 WHERE last_name = ’Smith’); Put bothstatements together and let SQL determinethe title for Smith.
Multiple Row Subqueries: Example • A multiple row subquery returns many rows. • You must use a multiple row operator in the WHERE clause, for example the IN operator. SQL> SELECT last_name, first_name, title 2 FROM s_emp 3 WHERE dept_in IN 4 (SELECT ID 5 FROM s_dept 6 WHERE name = 'Finance' 7 OR region_id = 2);
Creating Tables: Syntax CREATE TABLE [schema.]table (column datatype [DEFAULT expr] [column_constraint], ... [table_constraint]); You must have specific privileges: • CREATE TABLE • A storage area
Datatypes Datatype VARCHAR(size) CHAR(size) int float DATE DATETIME Decimal(M,D) Description Variable length character values Fixed length character values Integer 單精浮點數 Date Date and time values M為全部數字位數(包括小數位)D為小數位數
Create Table: Example SQL> CREATE TABLE s_dept -> (id NUMBER(7), -> name VARCHAR (25), -> region_id NUMBER(7));
Data Manipulation and Transaction Control Commands Command INSERT UPDATE DELETE COMMIT Description Adds a new row to the table. Modifies existing rows in the table. Removes existing rows from the table. Makes all pending changes permanent.
Inserting New Rows into a Table: Syntax • Add new rows to a table by using the INSERT command. • Only one row is inserted at a time with this syntax. INSERT INTO table [(column [, column...])] VALUES (value [, value...]);
Inserting New Rows: Example • Insert a new row containing values for each column. • Optionally list the columns in the INSERT clause. • List values in the default order of the columns in the table. • Enclose character and date values within single quotation marks. SQL> INSERT INTO s_dept 2 VALUES (11, 'Finance', 2); 1 row created.
Updating Rows in a Table: Syntax • Modify existing rows with the UPDATE command. UPDATE table SET column = value [, column = value] [WHERE condition];
Updating Rows: Examples • Transfer employee number 2 to department 10. SQL> UPDATE s_emp 2 SET dept_id = 10 3 WHERE id = 2; 1 row updated. • Transfer employee number 1 to department 32 and change the salary to 2550. SQL> UPDATE s_emp 2 SET dept_id = 32, salary = 2550 3 WHERE id = 1; 1 row updated.
Updating All Rows in the Table • All rows in the table will be updated if you do not add the WHERE clause. SQL> UPDATE s_emp 2 SET commission_pct = 10; 25 rows updated.
Deleting Rows from a Table: Syntax • Remove existing rows by using the DELETE command. DELETE [FROM] table [WHERE condition]; • Remove all information about employees who started after January 1, 1996. SQL> DELETE FROM s_emp 2 WHERE start_date > 3 TO_DATE('01.01.1996', 'DD.MM.YYYY'); 1 row deleted.
Deleting Rows: Example • Delete all the rows in the table by excluding the WHERE clause. SQL> DELETE FROM test; 25,000 rows deleted. • Confirm the deletions. SQL> SELECT * 2 FROM test; no rows selected