SQL的數據查詢
第二章:SQL的數據查詢
2.1 SELECT基本語法
單表操作:projection投影列,selection選擇行,join連接
SELECT {* | [DISTINCT] column列 |expression [alias],...}
FROM table;
• SELECT identifies the columns to be displayed.選擇特定的列顯示
• FROM identifies the table containing those columns.
Selecting All Columns :SELECT * FROM departments;
Selecting Specific ColumnsSELECT department_id, location_id FROM departments;
Writing SQL Statements:語法結構
• SQL statements are not case sensitive.語句大小寫不敏感
• SQL statements can be entered on one or more lines.書寫一行或多行
• Keywords cannot be abbreviated or split across lines.關鍵字不可分行
• Clauses are usually placed on separate lines.
• Indents are used to enhance readability.
• In SQL Developer, SQL statements can be optionally terminated by a semicolon (😉. Semicolons are required when you execute multiple SQL statements.
• In SQL*Plus, you are required to end each SQL statement with a semicolon (😉.
Column Heading Defaults
Arithmetic expressions and NULL values in the SELECT statement
算術表達和空值
Defining a Null Value空值是特殊數據類型,函數轉換運算
• Null is a value that is unavailable, unassigned, unknown, or inapplicable.
• Null is not the same as zero or a blank space.不是零也不是空格
Defining a Column Alias別名
A column alias:
• Renames a column heading
• Is useful with calculations
• Immediately follows the column name (There can also be the optional AS keyword between the column name and the alias.)
• Requires double quotation“” marks if it contains spaces or special characters, or if it is case-sensitive
SELECT last_name AS name, commission_pct as comm FROM employees;
SELECT last_name "Name" /*顯示結果大小寫不變*/, salary*12 "Annual Salary" FROM employees;
Concatenation Operator聯合運算符:兩個字段放在一個字段輸出
• Links columns or character strings to other columns
• Is represented by two vertical bars (||)
• Creates a resultant column that is a character expression
SELECT last_name||job_id AS "Employees" FROM employees;
Literal Character Strings文本字符串
• A literal is a character字符串, a number數字, or a date日期 (需要單引號)that is included in the SELECT statement.
• Date and character literal values must be enclosed within single quotation marks.
• Each character string is output once for each row returned.
**SELECT last_name ||' is a '||job_id AS "Employee Details"//單引號
FROM employees;**
Alternative Quote (q) Operator
• Specify your own quotation mark delimiter.
• Select any delimiter.
• Increase readability and usability.
SELECT department_name || q'[ Department's]' || manager_id關鍵字q :保持括號內原意
AS "Department and Manager"
FROM departments;
Duplicate Rows
The default display of queries is all rows, including duplicate rows
SELECT DISTINCT重複值只顯示一次 department_id FROM employees;
2.2 行限定與排序(where字句與order by字句)
2.2.1 行限定(where字句)
Limiting the Rows That Are Selected
• Restrict the rows that are returned by using the WHERE clause:
SELECT *|{[DISTINCT] column|expression [alias],...}
FROM table
[WHERE logical expression(s)];
SELECT employee_id, last_name, job_id, department_id
FROM employees
WHERE department_id = 90;(數字)
Character Strings and Dates
• Character strings and date values are enclosed with single quotation marks.
• Character values are case-sensitive and date values are format-sensitive.
• The default date display format is DD-MON-RR.日期格式RR-相對年份;YY-絕對年份
SELECT last_name, job_id, department_id
FROM employees
WHERE last_name ='Whalen';//(where操作中大小寫敏感,可以通過函數轉換)
SELECT last_name
FROM employees
WHERE hire_date ='17-OCT-03';
Comparison Operators
SELECT last_name, salary
FROM employees
WHERE salary <= 3000;
Use the BETWEEN operator to display rows based on a range of values:
SELECT last_name, salary
FROM employees
WHERE salary BETWEEN 2500 AND 3500;
Use the IN operator to test for values in a list:
SELECT employee_id, last_name, salary, manager_id
FROM employees
WHERE manager_id IN (100, 101, 201);在這幾個值中即可
Pattern Matching Using the LIKE Operator
• Use the LIKE operator to perform wildcard searches of valid search string values.
• Search conditions can contain either literal characters or numbers:通配符
– % denotes zero or more characters.通配0到多個字符串
– _ denotes one character.通配一個字符串
SELECT first_name
FROM employees
WHERE first_name LIKE 'S%';以大寫S開頭字符串
Combining Wildcard Characters
• You can combine the two wildcard characters (%, _) with literal characters for pattern matching:
SELECT last_name
FROM employees
WHERE last_name LIKE '_o%' ;
• You can use the ESCAPE identifier to search for the actual % and _ symbols.還原通配符原意
The % and _ symbols can be used in any combination with literal characters. The example in the slide displays the names of all employees whose last names have the letter “o” as the second character.
ESCAPE Identifier:
When you need to have an exact match for the actual % and _ characters, use the ESCAPE identifier. This option specifies what the escape character is. If you want to search for strings that contain SA_, you can use the following SQL statement:
SELECT employee_id, last_name, job_id
FROM employees
WHERE job_id LIKE '%SA\_%' ESCAPE '\'; \後輸出_,還原字符是\
The ESCAPE identifier identifies the backslash () as the escape character. In the SQL statement, the escape character precedes the underscore (_). This causes the Oracle server to interpret the underscore literally.
Using the NULL Conditions
Test for nulls with the IS NULL operator.
SELECT last_name, manager_id
FROM employees
WHERE manager_id IS NULL ;
Defining Conditions Using the Logical Operators邏輯運算符
Using the AND Operator
AND requires both the component conditions to be true:
**SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE salary>= 10000 AND job_id LIKE '%MAN%' ;
**
Using the OR Operator
OR requires either component condition to be true:
SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE salary>= 10000 OR job_id LIKE '%MAN%';滿足其一即可
Using the NOT Operator
SELECT last_name, job_id
FROM employees
WHERE job_id NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP'); 不在in列表中
Rules of precedence for operators in an expression
Rules of Precedence優先級
You can use parentheses to override rules of precedence.
SELECT last_name, job_id, salary
FROM employees
WHERE job_id = 'SA_REP' OR job_id = 'AD_PRES' AND salary > 15000;
2.2.2 排序 - order by子句
Using the ORDER BY Clause排序
• Sort the retrieved rows with the ORDER BY clause:
– ASC: Ascending order, default默認升序
– DESC: Descending order降序
• The ORDER BY clause comes last in the SELECT statement:
SELECT last_name, job_id, department_id, hire_date
FROM employees
ORDER BY hire_date;舊日期在前
• Sorting in descending order:
SELECT last_name, job_id, department_id, hire_date
FROM employees
ORDER BY hire_date DESC ;
• Sorting by column alias
SELECT employee_id, last_name, salary*12 annsal
FROM employees
ORDER BY annsal ;按照別名排序
• Sorting by using the column’s numeric position:物理順序,按照查詢第三個字段排序
SQL Row limiting clause in a query
SQL Row Limiting Claus
• The row_limiting_clause allows you to limit the rows that are returned by the query.
• Queries that order data and then limit row output are widely used and are often referred to as Top-N queries.
• You can specify the number of rows or percentage of rows to return with the FETCH_FIRST keywords.
• You can use the OFFSET keyword to specify that the returned rows begin with a row after the first row of the full result set.
• The WITH TIES keyword includes additional rows with the same ordering keys as the last row of the row-limited result set (you must specify ORDER BY in the query).
Using SQL Row Limiting Clause in a Query
You can specify the row_limiting_clause in the SQL SELECT statement by placing it after the ORDER BY clause. Syntax:
SQL Row Limiting Clause Example
SELECT employee_id, first_name
FROM employees
ORDER BY employee_id FETCH FIRST 5 ROWS ONLY; 只選取前五條
SELECT employee_id, first_name
FROM employees
ORDER BY employee_id
OFFSET 5 ROWS FETCH NEXT 5 ROWS ONLY;忽略前五條,從第六條記錄選取五條
2.2.3 Substitution Variables替換變量
• Use substitution variables to:單/雙替換符
– Temporarily store values with single-ampersand (&) and double-ampersand (&&) substitution
• Use substitution variables to supplement the following:
– WHERE conditions
– ORDER BY clauses
– Column expressions
– Table names
– Entire SELECT statements
Use a variable prefixed with an ampersand (&) to prompt the user for a value:
SELECT employee_id, last_name, salary, department_id
FROM employees
WHERE employee_id =&employee_num;無需聲明,直接使用
Character and Date Values with
Substitution Variables
Use single quotation marks for date and character values:
SELECT last_name, department_id, salary*12
FROM employees
WHERE job_id ='&job_title';字符串
Specifying Column Names, Expressions, and Text
SELECT employee_id, last_name, job_id,&column_name
FROM employees
WHERE &condition
ORDER BY &ordercolumn ;
Using the Double-Ampersand Substitution Variable雙替換符&&:可存儲舊值
Use double ampersand (&&) if you want to reuse the variable value without prompting the user each time
Undefine 雙替換符變量名;清除舊值
DEFINE and VERIFY commands
Using the DEFINE Command
• Use the DEFINE command to create and assign a value to a variable.
• Use the UNDEFINE command to remove a variable.
DEFINE employee_num=200 提前定義
SELECT employee_id, last_name, salary, department_id
FROM employees
WHERE employee_id = &employee_num;
UNDEFINE employee_num清除賦值
Using the VERIFY Command:Use the VERIFY command to toggle the display of the substitution variable, both before and after SQL Developer replaces substitution variables with values:
SET VERIFY ON顯示替換變量舊值,默認打開
SELECT employee_id, last_name, salary
FROM employees
WHERE employee_id = &employee_num;