SQL Fundamentals: Basic SELECT statement基本的select语句

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL Fundamentals: Basic SELECT statement基本的select语句相关的知识,希望对你有一定的参考价值。

      • Basic SELECT statement基本的select语句

The basic syntax for a SELECT statement is presented below.

SELECT语句的基本语法如下。

      • |:多选一
      • []:可选择的内容
      • {}:多选一
      • 没有被{}括起来的是必选

SELECT [DISTINCT | ALL] {* | select_list}
FROM {table_name [alias] | view_name}
    [{table_name [alias] | view_name}]... 
[WHERE condition]
[GROUP BY condition_list]
[HAVING condition]
[ORDER BY {column_name | column_# [ ASC | DESC ] } ...

 

In its simplest form, a SELECT statement must include the following:

SELECT

      • The SELECT clause is mandatory and carries out the relational project operation.

选择子句是强制性的,并执行关系项目操作。

      • SELECT identifies the columns to be displayed.
      • A SELECT clause, which specifies the columns to be displayed.

SELECT标识要显示的

FROM

      • The FROM clause is also mandatory. It identifies one or more tables and/or views from which to retrieve the column data displayed in a result table.
      • FROM identifies the table containing those columns.
      • A FROM clause, which identifies the table containing the columns that are listed in the SELECT clause.

它标识包含SELECT子句中列出的列的表。

 

In the syntax:

SELECT

Is a list of one or more columns

*

Selects all columns

DISTINCT

Suppresses(阻止) duplicates(重复)

Column | expression

Selects the named column or the expression列名或表达式

alias

Gives the selected columns different heading(标题)

FROM table

Specifies the table containing the columns

Note: Throughout this course, the words keyword, clause, and statement are used as follows:

      • A keyword(关键字) refers to an individual(独特的) SQL element(有特殊含义的SQL元素)

——for example,SELECT and FROM are keywords.

      • A clause(子句) is a part of a SQL statementSelect语句的一个组成部分)

——for example, SELECT emplovee_id, last_name , and so on

      • A statement(语句) is a combination(组合) of two or more clausesSelect语句是两个或者多个子句的组合)

——for example, SELECT * FROM employeesSELECT *叫一个子句,FROM employees叫一个子句)

注意:习惯将关键字写成大写

WHERE

The WHERE clause is optional and carries out the relational select operation. It specifies which rows are to be selected.

 GROUP BY

The GROUP BY clause is optional. It organizes data into groups by one or more column names listed in the SELECT clause.

HAVING

The optional HAVING clause sets conditions regarding which groups to include in a result table. The groups are specified by the GROUP BY clause.

ORDER BY

The ORDER BY clause is optional. It sorts query results by one or more columns in ascending or descending order.

 

Selecting All Columns:

SELECT *

FROM departments

 

从departments表中选择所有的行rows.

每个行要显示所有列column.

 

Selecting Specific Columns:

SELECT department_id, location_id

FROM departments

从departments表中选择指定行.

 

Write SQL Statements

SQL statements are not case sensitive.

SQL语句不区分大小写

SQL statements can be entered on one or more lines.

可以在一行或多行上输入sql语句

Keywords cannot be abbreviated(缩写) or split across lines.

关键字不能缩写或跨越多行

Clauses are usually placed on separate lines.

子句通常放在单独的行上

Indents(缩进) are used to enhance redability.

缩进是用来增强可读性

In SQL Developer, SQL statements can be optionally terminated by semicolon(;).Semicolons are required when you execute multiple SQL statements.

In SQL Developer,SQL语句可以随意终止的分号(;)

当你执行多条SQL语句分号是必需的。

In SQL*Plus, you are required to end each SQL statement with a semicolon(;).

In SQL*Plus,,你需要用分号(;)结束每个SQL语句。

Chose the statements which correctly specify a rule to write a SQL statement

  1. SQL statements are case sensitive
  2. Keywords can be abbreviated to build a standard
  3. SQL statements are case in-sensitive
  4. clauses must be placed together

Answer: C.SQL statements are not case sensitive.

 

Column Heading Defaults:

默认的列标题(表的第一行):

SQL Developer

-Default heading alignment: Left-aligned(左对齐)

-Default heading display: Uppercase(大写)

SQL *Plus

-Character and Data column headings are left-aligned

-Number column headings are right-aligned

-Default heading display : Uppercase

 

 

Arithmetic expressions and NULL values in the SELECT statement

SELECT语句中的算术表达式空值

 

首先介绍显示表结构的命令

DESCRIBE command

描述命令:显示表结构

The structural metadata of a table may be obtained by querying the database for the list of columns that comprise it using the DESCRIBE command. It will list the used column names, their null property and data type.

Syntax:

DESC[RIBE] [SCHEMA].object name

For example,

SQL> desc emp;

 Name                                      Null?    Type

 ----------------------------------------- -------- ----------------------------

 EMPNO                                     NOT NULL NUMBER(4)

 ENAME                                              VARCHAR2(10)

 JOB                                                VARCHAR2(9)

 MGR                                                NUMBER(4)

 HIREDATE                                           DATE

 SAL                                                NUMBER(7,2)

 COMM                                               NUMBER(7,2)

 DEPTNO                                             NUMBER(2)

 

will display the EMPLOYEE table structure i.e. columns, their data types, precision and nullable property.

 

 

An arithmetic expression can be creaeted using the column names, operators and constant values to embed an expression in a SELECT statement.

算术表达式可以使用列名称、运算符常量值嵌入一个SELECT语句中的表达创建

The operator applicable to a column depends on column‘s data type.

适用于的运算符依赖于数据类型

For example, arithmetic operators will not fit for character literal values.

例如,算术运算符不适合字符面值。

 

 For example,

SELECT employee_id, sal * 12 ANNUAL_SAL
FROM employees;

The above query contains the arithmetic expression (sal * 12) to calculate annual salary of each employee.

上面的查询包含算术表达式(sal* 12来计算每个雇员的年薪。

 

Arithmetic Expressions

算术表达式

      • You may need to modify the way in which data is displayed, or you may want to perform calculations, or look at what-if scenarios. All these are possible using arithmetic expressions.

你可能需要修改数据的显示方式,或想执行计算,通过使用算术表达式可以实现.

      • An arithmetic expression can contain column names, constant numeric values, and the arithmetic operators.

一个算术表达式可以包含列名、常量数字值算术操作符.

      • Create expressions with number and date data by using arithmetic operators.

 

Arithmetic operators

算术运算符

The slide lists the arithmetic operators that are available in SQL.

You can use arithmetic operators in any clause of a SQL statement(except the FROM clause)

除了FROM子句,可在SELECT的任何其他子句中使用算术操作符.

Note: With the DATE and TIMESTAMP data types, you can use the addition and subtraction.

DATATIMESTAMP数据类型,只能使用+ -操作符.

 

Operators act upon the columns (known as operands) to result into a different result. In case of multiple operators in an expression, the order of evaulation is decided by the operator precedence. Here are the elementary rules of precedence -

      • Multiplication and division occur before Addition and Subtraction.
      • Operators on the same priority are evaluated from left to right.
      • Use paretheses to override the default behavior of the operators.

Below table shows the precedence of the operators, in such cases. Precedence Level Operator Symbol Operation

Description 

 Operator        

Precedence        

Addition

+

Lowest

Subtraction

-        

Lowest        

Multiplication

*        

Medium        

Division

/        

Medium

Brackets

( )        

Highest

        

Examine the below queries (a), (b), and (c)

SQL> SELECT 2*3 FROM DUAL;

       2*3

----------

SQL> SELECT ename,sal,sal+200 FROM emp;

ENAME             SAL    SAL+200

---------- ---------- ----------

SMITH             800       1000

WARD             1250       1450

 

SQL> SELECT ename,sal,sal+(comm*sal) FROM emp;

ENAME             SAL SAL+(COMM*SAL)

---------- ---------- --------------

SMITH             800

WARD             1250         626250

Query (a) multiplies two numbers, while (b) shows addition of $1500 to salaries of all employees.

Query (c) shows the addition of commission component to employee‘s salary.

As per the precedence, first commission would be calculated on the salary, and then added to the salary.

 

注意,如上sal+200这个列是运算列,并不是真正存在的列,这里可以对这个列设定一个列别名.

 

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(区分大小写).

如果别名列中有空格,或特殊字符,或区分大小写,这个时候这个列标题要用双引号引起来.

 

An alias is used to rename a column or an expression during display. The alias to a column or an expression appears as the heading in the output of a query. It is useful in providing a meaningful heading to long expressions in the SELECT query. By default, the alias appears in uppercase in the query output without spaces. To override this behavior, alias must be enclosed within double quotes to preserve the case and spaces in the alias name.

SELECT price * 2 as DOUBLE_PRICE, price * 10 "Double Price"
FROM products;

DOUBLE_PRICE        Double Price
------------        ------------
39.9                        39.9
60                        60
51.98                        51.98

 

Concatenation operators

串联操作符||

A 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.

 

字符串连接起来,创建一个组合列.

 

Concatenation operator can be used to join two string values or expressions in a SELECT query. The double vertical bar symbol is used as string concatenation operator. It is applicable only for character and string column values resulting into a new character expression. Example

SQL> SELECT ename,job,ename||job as "Employees" FROM emp;

 

ENAME      JOB       Employees

---------- --------- -------------------

SMITH      CLERK     SMITHCLERK

The above query shows concatenation of two character literals values.

 

Literals

字面量/常量

      • A literal is a character, a number, or a date that is included in the SELECT statement.

常量可以是字符串,数字,日期.

      • Data and character literal values must be enclosed within single quotation (单引号)marks.

日期字符串常量必须用单引号引起来.

      • Each character string is output once for each row returned.

为返回的每一行打印一次.

 

单引号引起来的是字面量.

单引号为定界符.

 

Any hard coded value, which is not stored in database, in the SELECT clause, is known s Literal. It can be number, character, or date value. Character and date values must be enclosed within quotes. Consider the below SQL queries.examples of using literals of different data types in SQL queries.

The query below uses two character literals to join them together.

SQL>

 SELECT ‘ORACLE‘||‘ CERTIFICATION‘ FROM DUAL

The query below uses character literals to pretty print the employee‘s salary.

SQL>

SELECT first_name ||‘earns‘|| salary||‘ as of ‘|||sysdate
FROM employees

SQL> SELECT ename,job,ename||‘job is‘||job as "Employees" FROM emp;

 

ENAME      JOB       Employees

---------- --------- -------------------------

SMITH      CLERK     SMITHjob isCLERK

 

Quote Operator

引用运算符

      • Specify your own quotation mark (引号)delimiter.
      • Select any delimiter(定界符).
      • Increase readability and usability(适用性).
      • Q运算符适用于字符串本身包含单引号的情况.
      • 使用Q操作符可以选择自己的引号定界符.
      • 你可以选择任何方便的定界符,[],{},(),<>.

The quote operator is used to specify the quotation mark delimiter of your own. You can chose a convenient delimiter, depedning on the data.

如下例子中,使用q操作符,中括号[]被作为字符串的定界符,里面的单引号就是普通的字符.

SELECT         department_name|| ‘ Department‘ ||q‘[‘s Manager Id: ]‘|| manager_id
FROM departments;

SQL> SELECT ename,job,ename||q‘[‘s job is]‘||job as "Employees" FROM emp;

 

ENAME      JOB       Employees

---------- --------- ----------------------------

SMITH      CLERK     SMITH‘s job isCLERK

 

NULL空值

      • Null is a value that is unavailable, unassigned(未赋值), unknown, or inapplicable(不适用的).
      • Null is not the same as zero(数值类型的0 or a blank space(字符类型的空格).
      • 包含NULL值的算术表达式,其结果还是NULL.

 

 

If a column doesn‘t has a definite value, it is considered as NULL. NULL value denotes unknown or unavailable. It is not zero for numeric values, not blank space for character values.

Columns with NULL value can be selected in a SELECT query and can be the part of an arithmetic expression. Any arithmetic expression using NULL values results into NULL. For this reason, columns with NULL value must be handled differently by specifying their alternate values using Oracle supplied functions like NVL or NULLIF.

SQL> SELECT NULL + 1000 NUM
FROM DUAL;

NUM
--------

 

技术分享

 

 

 

Duplicate Rows

The default display of queries is all rows, including duplicate rows.

DISTINCT Keyword:Suppresses(阻止) duplicates(重复)

这里可以选择多个列,但是他会取多个列的组合的重复,如列1的前三行为122;列2的前三行为134,会取出第一行,显示第二行和第三行.

If the data is expected to have duplicate results, use DISTINCT keyword to eliminate duplicates and diplay only the unique results in the query output. Only the selected columns are validated for duplication and the rows will be logically eliminated from the query output. To be noted, the DISTINCT keyword must appear just after the SELECT clause.

The simple query below demonstrates the use of DISTINCT to display unique department ids from EMPLOYEES table.

DISTINCT后可以跟多个列,去掉多个列的组合完全一样的重复行.

SQL> SELECT DISTINCT deptno FROM EMP;

 

    DEPTNO

----------

        30

        20

        10

Question:Which of the following clause is used to suppress duplicates in a SELECT statement?

  1. INTERSECT
  2. DUPLICATE
  3. DISTINCT
  4. UNIQUE

Answer: C, D. Duplicate data can be restricted with the use of DISTINCT or UNIQUE in the SELECT statement.

 

 

1. Identify the capabilities of SELECT statement.

  1. Projection
  2. Selection
  3. Data Control
  4. Transaction

Answer: A, B. The SELECT statement can be used for selection, projection and joining.

2. Determine the capability of the SELECT statement demonstrated in the given query.

SELECT e.ename, d.dname
FROM   emp e, dept d
WHERE e.deptno = d.deptno
AND    e.sal > 1000;

  1. Selection
  1. Filtering
  1. Joining
  2. Projection

Answer: A, C, D. Projection is including only the required columns in query, while Selection is selecting only the required data. Joining means combining two tables together through a connecting column.

3. Which of the following clause is used to suppress duplicates in a SELECT statement?

  1. INTERSECT
  2. DUPLICATE
  3. DISTINCT
  4. UNIQUE

Answer: C, D. Duplicate data can be restricted with the use of DISTINCT or UNIQUE in the SELECT statement.

4. Chose the statements which correctly specify a rule to write a SQL statement

  1. SQL statements are case sensitive
  2. Keywords can be abbreviated to build a standard
  3. SQL statements are case in-sensitive
  4. clauses must be placed together

Answer: C.SQL statements are not case sensitive.

5. Determine the output of the below query -

SELECT ‘5+7‘
FROM dual;

  1. 12
  2. 5+7
  3. 5
  4. 7

Answer: B.Oracle treats the values within double quotes as string expressions.

6. Write a query to display employee details (Name, Department, Salary and Job) from EMP table.

  1. SELECT ename, deptno, sal, job FROM emp;
  2. SELECT * FROM emp;
  3. SELECT DISTINCT ename, deptno, sal, job FROM emp;
  4. SELECT ename, deptno, sal FROM emp;

Answer A.Select the required from the tables each separated by a comma.

7. Which of the below queries displays employees‘ name and new salary after the increment of 1000?

  1. SELECT ename, sal FROM emp;
  2. SELECT ename, sal=sal+1000 FROM emp;
  3. SELECT ename, sal+1000 FROM emp;
  4. SELECT ename, 1000 FROM emp;

Answer: C. Basic arithmetic calculations can be done using the columns in SELECT statements.

8. Determine the output of the below query

SELECT 36/2-5*10 FROM dual;

  1. 130
  2. -32
  3. -120
  4. 175

Answer: B. Multiplication and Division occur before addition and subtraction.

9. Determine the output of the below query

SELECT (100-25)/15*(20-3) FROM dual;

  1. 0.294
  2. -85
  3. 63.67
  4. 85

Answer: D. Expression within the brackets are executed before the divisions and multiplications in the expression.

10. Chose the statements which correctly define a NULL value.

  1. NULL is a special value with zero bytes
  2. NULL is no value or unknown value
  3. NULL is represented by a blank space
  4. NULL is not same as zero

Answer: B, D.NULL is NO VALUE but neither same as zero nor as blank or space character.

11. Determine the output of the below query

SELECT sal + NULL
FROM emp
WHERE empno = 7369;

  1. sal + NULL
  1. NULL
  1. 0
  2. 1250

Answer: B. Any arithmetic operation with NULL results in NULL.

12. Which of the below statements define column alias correctly?

  1. A column alias renames a column heading
  2. A column alias is an alternate column in a table
  3. A column alias can be specified during table definition
  4. A column alias immediately follows the column or expression in the SELECT statement

Answer: A, D. Column Alias can be used to name an expression in the SELECT statement.

13. Specify the column alias NEWSAL for the expression containing salary in the below SQL query

SELECT ename, job, sal + 100 FROM emp;

  1. (sal + 100) AS NEWSAL
  2. (sal + 100) NEWSAL
  3. (sal + 100) IS NEWSAL
  4. sal + 100 IS NEWSAL

Answer: A, B.Use ‘AS‘ to signify new alias to a column expression.

14. Specify the column alias "New Salary" for the expression containing salary in the below SQL query

SELECT ename, job, sal + 100 FROM emp;

  1. (sal + 100) AS New Salary
  2. (sal + 100) "New Salary"
  3. (sal + 100) IS New Salary
  4. sal + 100 as "New Salary"

Answer: B, D. Column alias with space and special characters must be enquoted within double quotes.

15. Which command is used to display the structure of a table?

  1. LIST
  2. SHOW
  3. DESCRIBE
  4. STRUCTURE

Answer: C.DESCRIBE is used to show the table structure.

16. Predict the output when below statement is executed in SQL* Plus?

DESC emp

  1. Raises error "SP2-0042: unknown command "desc emp" - rest of line ignored."
  2. Lists the columns of EMP table
  3. Lists the EMP table columns, their data type and nullity
  4. Lists the columns of EMP table along with their data types

Answer: C. DESCRIBE is used to show the table structure along with table columns, their data type and nullity

17. Which of the below statements are true about the DESCRIBE command?

  1. It can be used in SQL*Plus only
  2. It can be used in both SQL*Plus as well as SQL Developer
  3. It doesn‘t works for object tables
  4. It doesn‘t works for SYS owned tables

Answer: B.

18. Which of the below alphanumeric characters are used to signify concatenation operator in SQL?

  1. +
  2. ||
  3. -
  4. ::

Answer: B.In SQL, concatenation operator is represented by two vertical bars (||).

19. Which of the below statements are correct about the usage of concatenation operator in SQL?

  1. It creates a virtual column in the table
  2. It generates a character expression as the result of concatenation of one or more strings
  3. It creates a link between two character columns
  4. It can be used to concatenate date expressions with other columns

Answer: B, D. Concatenation operator joins two values as an expression.

20. Predict the output of the below query

SELECT ename || NULL
FROM emp
WHERE empno = 7369

  1. SMITH
  2. SMITH NULL
  3. SMITHNULL
  4. ORA-00904: "NULL": invalid identifier

Answer: A. Concatenation with NULL results into same value.

21. Predict the output of the below query

SELECT 50 || 0001
FROM dual

  1. 500001
  2. 51
  3. 501
  4. 5001

Answer: C. The leading zeroes in the right operand of expression are ignored by Oracle.

22. You execute the below query

SELECT e.ename||‘ departments‘s name is:‘|| d.dname
FROM emp e, dept d
where e.deptno=d.deptno;

And get the exception - ORA-01756: quoted string not properly terminated. Which of the following solutions can permanently resolve the problem?

  1. Use double quote marks for the literal character string
  2. Use [q] operator to enquote the literal character string and selecting the delimiter of choice
  3. Remove the single quote mark (apostrophe) from the literal character string
  4. Use another delimiter to bypass the single quote apostrophe in the literal string

Answer: B. The [q] operator is used to enquote character literals with a quote.

23. Which of the below SELECT statement shows the correct usage of [q] operator?

  1. SELECT e.ename || q‘[department‘s name is]‘|| d.dname
       FROM emp e, dept d
       WHERE e.deptno = d.deptno;
  2. SELECT e.ename || q[‘department‘s name is‘]|| d.dname
       FROM emp e, dept d
       WHERE e.deptno = d.deptno;
  3. SELECT e.ename || q[department‘s name is]|| d.dname
       FROM emp e, dept d
       WHERE e.deptno = d.deptno;
  4. SELECT e.ename || q‘(department‘s name is)‘|| d.dname
       FROM emp e, dept d
       WHERE e.deptno = d.deptno;

Answer: A

24. Which of the below SELECT statement is used to select all columns of EMP table?

  1. SELECT ALL FROM emp
  2. SELECT # FROM emp
  3. SELECT * FROM emp
  4. SELECT empno,ename,deptno,sal,job,mgr,hiredate FROM emp

Answer: C. The character ‘*‘ is used to select all the columns of the table.

25. Which of the below SQL query will display employee names, department, and annual salary?

  1. SELECT ename, deptno, sal FROM emp;
  2. SELECT ename, deptno, sal + comm FROM emp;
  3. SELECT ename, deptno, (sal * 12) Annual_Sal FROM emp;
  4. Annual salary cannot be queried since the column doesn‘t exists in the table

Answer: C. Use numeric expressions in SELECT statement to perform basic arithmetic calculations.

 

 

以上是关于SQL Fundamentals: Basic SELECT statement基本的select语句的主要内容,如果未能解决你的问题,请参考以下文章

SQL Fundamentals:Substitution Variables(替代变量)

SQL Fundamentals: 子查询 || 分析函数

SQL Fundamentals || DCL(Data Control Language) || 角色ROLES

SQL Fundamentals:Restricting and Sorting Data限制和排序数据

SQL Fundamentals || DCL(Data Control Language) || 用户管理&Profile概要文件

SQL Fundamentals || Single-Row Functions || 转换函数 Conversion function