All technological notes.
SELECT FROM-- Select all records
SELECT *
FROM table_name;
-- Select single field
SELECT col_name
FROM table_name;
-- Select multiple fields
SELECT col_name, col_name, ...
FROM table_name;
Argument
*) is used to indicate that all columns available are to be displayed.星号表示返回所有Good practice
It is best to enter your SQL command over several lines, beginning each line with a keyword making it clear and readable, and easier to debug 输入命令,建议分行,每一行由一个关键字起头,让代码清晰, 可读, 易于调试
Do your best to query only the needed columns.
AS-- return column with the name of alias name
SELECT column_name AS alias_name
FROM table_name;
AS operator gets executed at the very end of a query: that is, alias cannot be used inside a WHERE or HAVING clause.
SELECT customer_id
, SUM(amount) AS total_spent
FROM payment
GROUP BY customer_id
HAVING total_spent <100 --"total_spent" 不存在
-- return column with the name of alias name
SELECT column_name alias_name
FROM table_name;
||: Concatenation operatorConcatenation: Combining columns
Concatenation operator连接运算符(Oracle): two vertical bars beside one another || 双竖杠
-- combining two columns
SELECT field_name || field_name
FROM table_name
-- concatenate two columns with a space character
SELECT field_name || ' ' || field_name
FROM table_name
a string literal was inserted into the output to put a blank space between the two fields
All string literals are enclosed in single quotation marks, the single quotes have a space inside so I end up with a space in my result 单引号
SQL 只能进行简单计算, 更复杂的计算应该使用 Python 等编程语言处理;
Arithmetic operators 运算符号
| Operator | Operation |
|---|---|
+ |
Add |
- |
Subtract |
* |
Multiply |
/ |
Divide |
Arithmetic operations follow the standard order of operations (BEDMAS, or PEMDAS if you learned either of these acronyms) 运算顺序,按照一般四则运算.
Exponents are not supported, use multiplication 不支持指数计算,应该使用惩罚
Arithmetic operators can be used in any clause of a SQL statement except the FROM clause
Order of Operations 运算顺序: 四则运算
While Carry out calculation from left to right in an expression, any required multiplication and division operations are solved first;先乘除
While Carry out calculation from left to right in an expression, Addition and subtraction operations are solved after multiplication and division, again moving form left to right in the equation 后加减
To override this order of operations, parentheses are used to enclose a portion that should be calculated first 括号优先
SELECT DISTINCT: Return unique dataSELECT DISTINCT
DISTINCT keyword can be used to return only the unique values in a column.SELECT DISTINCT col_name FROM tb_name;
# use parethesis to clarify the column to which the DISTINCT is being applied.
SELECT DISTINCT(col_name) FROM tb_name;
-- Remove duplicate items by using DISTINCT
SELECT DISTINCT field_name, field_name
FROM table_name;
Application
The DISTINCT keyword is applied to all columns listed in the SELECT statement. Select 语句提及字段都会使用,而不是最近的字段才会适用;
The DISTINCT keyword in a SELECT statement with multiple columns returns the records that are unique for all columns will be returned.多字段时,相当于比较数组。
SELECT WHERE: Filter returned rowsWHERE statement
SELECT statement.WHERE语句后才执行.SELECT column_name
,column_name
,column_name
FROM table_name
WHERE column_name operator value;
Column name
WHERE语句中的列名不能是 alias. 注意该特性与在高级 select 中使用 alias 相比较, 因为 alias 是最后输出时才执行的.Rule for value
value is case sensitive.大小写敏感
注意: Oracle 不是大小写敏感,但 value 是大小写敏感;
e.g.: WHERE lname = 'SMITH'和WHERE lname = 'smith'返回的结果是不同的;
Character Strings 字符串: Using singel quotation mark. The use of double quotation mark will raise an error of invalid idetifier.
Date 日期: must be enclosed in single quotation marks.
e.g.: WHERE data = '2-Mar-22'
日期格式与 Date formate 设置有关.
Number 数字: single quotation marks are not required
The value in a numeric column is not required to be enclosed in single quotes.
e.g.: WHERE age = 10
实践:为避免引号引起的错误,建议搜索前使用DESC table_name查询表定义.
| Operator | Description |
|---|---|
= |
Equality, equal to |
<>,!=, ^= |
Not equal to |
> |
Greater than |
>= |
Greater than or equal to |
< |
Less than |
<= |
Less than or equal to |
A comparision operator indicates how the data should relate to a given search value (benchmark).
String: Seldom
-- return a set of data where state name start later than given string "GA"
-- if it is <, it means the state name start alphabetically earlier than the given string
SELECT firstname
,lastname
,state
FROM customers
WHERE state > 'GA';
<>.
SELECT firstname
,lastname
,state
FROM customers
WHERE state <> 'GA';
-- 注意:
-- 1. WHERE语句中的column_name列名可以是表达式;
-- 2. column_name不能用alias,下例中只能键入表达式,不能用别名profit
-- 3. value也可以是表达式。
SELECT title
,retail-cost AS profit
FROM books
WHERE retail-cost < cost*.2;
Order of the logical operator:
WHERE (category = 'FAMILY LIFE')
OR (pubid = 4
AND cost > 15)
AND
| Clause | Both/Either | Result |
|---|---|---|
condition_A AND condition_B |
Both True | TRUE |
condition_A AND condition_B |
Either or Both False | FALSE |
若干指定列的 AND<>判断,相当于 NOT IN
集合上,相当于 condition_A 和 condition_B 的交集the intersection of sets a and b
OR
| Clause | Both/Either | Result |
|---|---|---|
condition_A OR condition_B |
Either or Both True | TRUE |
condition_A OR condition_B |
Both False | FALSE |
若干指定列的 OR=判断,相当于 IN
集合上,相当于 condition_A 和 condition_B 的并集the union of sets a and b
NOT
BETWEEN AND OperatorBETWEEN AND Operator
Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN low_boudary AND high_boudary;
Practice
value >= low AND value <= highBegin and end points are inclusive.包含起始值
Can combine BETWEEN with the NOT
NOT BETWEEN low AND highvalue < low AND value > highCan work with date:
BETWEEN YYYY-MM-DD AND YYYY-MM-DD0:00-- 返回开头为A-D
SELECT title
,pubid
FROM books
WHERE title BETWEEN 'A' AND 'D';
IN OperatorIN Operator
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
Practice
The list of given benchmark must be enclosed in parentheses and separated by commas. 使用括号包围;多个给定值时用逗号分隔;
给定的 value 必须完全匹配,包括字符串,数字,和日期.
Inclusive: IN
OR=语句
-- Equivalent
SELECT title
,pubid
FROM books
WHERE pubid IN (1,3,5);
SELECT title
,pubid
FROM books
WHERE pubid =1 OR pubid = 3 OR pubid = 5;
exclusive:NOT IN 取反
AND<>语句SELECT column_name(s)
FROM table_name
WHERE column_name NOT IN (v1,v2,...);
SELECT column_name(s)
FROM table_name
WHERE column_name <> v1
AND column_name <> v2 ;
LIKE and ILIKE OpeartorLIKE Opeartor:
wildcard characters.Wildcard characters
| Wildcard | Description | Note |
|---|---|---|
_ |
underscore 下划线, is used to represent exactly one character; | can’t represent nothing |
% |
percent 百分号, is used to represent any number of characters; | can represent nothing |
LIKE: case-sensitiveILIKE: case-insensitive
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;
SELECT * FROM customer
WHERE first_name LIKE 'J%';
SELECT * FROM customer
WHERE first_name LIKE '_her%';
SELECT * FROM customer
WHERE first_name NOT LIKE '_her%';
%a -- End with 'a'
a% --Start with 'a'
%a% --Contain 'a'
_a_ --The string is composed of 3 characters with 'a' in the middle
_a --The string is composed of 2 characters and ends with 'a'.
a_ --The string is composed of 2 characters and starts with 'a'.
Escape 转义
ESCAPE_%;只有转义标识符其后的通配符才会被转义 taken as literal %/_ symbal,其他通配符不会被转义.
-- B here is escape indicator, the first character followed escape indicator escapes
-- 该处B被声明为转义的标识
SELECT *
FROM testing
WHERE tvalue LIKE 'B%__A%T' ESCAPE 'B'
-- Return rows started with % and followed by any characters.
SELECT *
FROM testing
WHERE tvalue LIKE '\%%' ESCAPE '\'
IS NULLNULL values, representing that no value has been stored in particular field , can return unexpected results.
IS NULL is used to search NULL values, while equal sign = can’t be used
field_name = NULL,不会报错; 但不会返回任何行.Not returns no rows.字段中存在NULL值时,返回的数据使用(null)标识。
取反: IS NOT NULL. 不能使用<>。
ORDER BY: Sort RowsORDER BY
Syntax
-- Ascending order
SELECT col_1, col_2 FROM tb_name ORDER BY col_1 ASC;
-- Descending order
SELECT col_1, col_2 FROM tb_name ORDER BY col_1 DESC;
-- Multiple order, Same order
SELECT col_1, col_2 FROM tb_name ORDER BY col_1, col_2;
-- Multiple order, Different order
SELECT col_1, col_2
FROM tb_name
ORDER BY col_1 ASC, col_2 DESC;
ORDER BY clause is listed at the end of the SELECT statement.
Column alias, if applied, can be used in ORDER BY clause. 可以使用别名
Sort by column ordinals
Order:
ASC: Default, Ascending order
DESC: Descending orderNULL value:
NULLS FIRST: Null values are listed first.NULLS LAST: Null values are listed last.技术上, 可以在 order by 中对某列排序, 但该列不在 select 中返回. 但现实中很少出现.
LIMIT: Limits number of returned rowsLIMIT
LIMIT is the last command to be executed. 最后才执行的语句.
SELECT col_1, col_2
FROM tb
WHERE condition
ORDER BY col_1
LIMIT num
Sub query
SELECT *
FROM tb
WHERE (sub query)
EXISTS functiontest the existence of rows in a subquery.
Syntax
SELECT col
FROM tb
WHERE EXISTS(
SELECT col
FROM tb
WHERE condition
)
UNIONUNION
SELECT clause.Syntax
SELECT col FROM tb_1
UNION
SELECT col FROM tb_2;