ORACLE 如何建立表外键
例:学生表student (id, name , sex )
成绩表score (id ,math )
如何创建表,要求 有主键,有约束 解:
CREATE TABLE STUDENT(ID CHAR(10), NAME VARCHAR(8),SEX CHAR(1));
ALTER TABLE STUDENT ADD CONSTRAINT PK_STUDENT PRIMARY KEY(ID);
CREATE TABLE SCORE( ID CHAR(10),MATH NUMBER(5,2));
ALTER TABLE SCORE ADD CONSTRAINT FK_SCROE FOREIGN KEY(ID) REFERENCES STUDENT(ID);
* 主键与外键:
键是表中的列(可以是一列,也可以是几列),主键用于唯一的标识表中的数据项;外键用于连接父表和子表。而所谓的父表和子表是根据3NF
范式的要求,为了消除传递依赖,将原表拆成2个相互关联的表,而这个关联就是外键。
ALTER TABLE zxt RENAME COLUMN mcc TO mc;
Q2.
CONSTRAINT name FOREIGN KEY (column_name) REFERENCES table_name (column_name);
Q3.
SQL> select hiredate+'10' from emp; 增加10天
HIREDATE+
---------
27-DEC-80
02-MAR-81
04-MAR-81
SQL> select hiredate from emp
2 ;
HIREDATE
---------
17-DEC-80
20-FEB-81
Q4.
MAX()和MIN()函数不仅可以作用于数值型数据,也可以作用于字符串或是日期时间数据类型的数据。
实例MAX()函数用于字符型数据
可见,对于字符串也可以求其最大值。
说明
对字符型数据的最大值,是按照首字母由A~Z的顺序排列,越往后,其值越大。当然,对于汉字则是按照其全拼拼音排列的,若首字符相同,则比较下一个字符,以此类推。
当然,对与日期时间类型的数据也可以求其最大/最小值,其大小排列就是日期时间的早晚,越早认为其值越小,如下面的实例。
Q5.'
sub queries
A. Multiple columns or expressions can be compared between the main query and sub query
B. Main query and sub query can get data from different tables
C. Sub queries can contain GROUP BY and ORDER BY clauses
Q6.
IN比较符的多行子查询
在多行子查询中必须使用多行比较运算符 , IN比较符返回子查询的中的每一个值,一旦有与该值相等的数据行则输出这些满足条件的数据行。
例子10-21查询那些是所在岗位中工资最低的员工信息。
SQL> select ename,job,sal,hiredate
2 from emp
3 where sal in (select min(sal)
4 from emp
5 group by job);
Q7.
the two statement produce identical results as ORDER BY 2 will take the second column as sorting column.
Q8.
SUBQUERIES can be used in the SELECT list and in the FROM, WHERE, and HAVING clauses of a query.
A subquery can have any of the usual clauses for selection and projection. The following are required clauses:
A SELECT list
A FROM clause
The following are optional clauses:
WHERE
GROUP BY
HAVING
The subquery (or subqueries) within a statement must be executed before the parent query that calls it, in order that the results of the subquery can be passed to the
parent
SQL> SELECT package_id, SUM (package_line_id)
2 FROM (SELECT package_id, package_line_id, 1 dummy
3 FROM kdlv_package_lines
4 WHERE package_id BETWEEN 30006 AND 30028)
5 GROUP BY (SELECT 'package_id'
6 FROM DUAL)
7 /
GROUP BY (SELECT 'package_id'
*
ERROR at line 5:
ORA-22818: subquery expressions not allowed here
Q9.
Which three SQL statements would display the value 1890.55 as $1,890.55? (Choose three.)
A. SELECT TO_CHAR(1890.55,'$99G999D00')
FROM DUAL;
B. SELECT TO_CHAR(1890.55,'$9,999V99')
FROM DUAL;
C. SELECT TO_CHAR(1890.55,'$0G000D00')
FROM DUAL;
D. SELECT TO_CHAR(1890.55,'$99G999D99')
FROM DUAL;
E. SELECT TO_CHAR(1890.55,'$9,999D99')
FROM DUAL;
Answer: A,C,D
Q10
It produces an error because the ORDER BY clause should appear only at the end of a compound query-that is, with the last SELECT statement
Using the ORDER BY Clause in Set Operations
The ORDER BY clause can appear only once at the end of the compound query. Component queries cannot have individual ORDER BY clauses. The ORDER BY
clause recognizes only the columns of the first SELECT query.
By default, the first column of the first SELECT query is used to sort the output in an ascending order
Q12
SQL have character, numeric, date, conversion function.
Incorrect answer:
ASQL have character, numeric, date, conversion function. CSQL have character, numeric, date, conversion function. DSQL have character, numeric, date, conversion
function. FSQL have character, numeric, date, conversion function.
Q15.AC
Q16 D
You need to create a report of the 10 students who achieved the highest ranking in the course INT SQL and who completed the course in the year 1999.
D. SELECT student_id, marks, ROWNUM "Rank"
FROM (SELECT student_id, marks
FROM students
WHERE (finish_date BETWEEN '01-JAN-99 AND '31-DEC-99' AND course_id = `INT_SQL'
ORDER BY marks DESC)
WHERE ROWNUM <= 10 ;
如果你要是用 rownum查询只能使用
SQL> select rownum ,empno ,ename,job,mgr,hiredate from emp where rownum < 5; 查询前四条的记录!
ROWNUM EMPNO ENAME JOB MGR HIREDATE
---------- ---------- ---------- --------- ---------- ------------------
1 7369 SMITH CLERK 7902 17-DEC-80
2 7499 ALLEN SALESMAN 7698 20-FEB-81
3 7521 WARD SALESMAN 7698 22-FEB-81
4 7566 JONES MANAGER 7839 02-APR-81
Q17
B
SYSDATE cannot be used with the CHECK constraint
CHECK Constraint
The CHECK constraint defines a condition that each row must satisfy. The condition can use the same constructs as the query conditions, with the following exceptions:
References to the CURRVAL, NEXTVAL, LEVEL, and ROWNUM pseudocolumns(伪列) Calls to SYSDATE, UID, USER, and USERENV functions
Queries that refer to other values in other rows
A single column can have multiple CHECK constraints that refer to the column in its definition. There is no limit to the number of CHECK constraints that you can define
on a column. CHECK constraints can be defined at the column level or table level.
CREATE TABLE employees
(...
salary NUMBER(8,2) CONSTRAINT emp_salary_min
CHECK (salary > 0),
Q19
Oracle INSERT WITH CHECK OPTION的用法
insert into (
WITH CHECK OPTION) values (...)
例如:
SQL> insert into (select object_id,object_name,object_type from xxx where object_id<1000 WITH CHECK OPTION)
2 values(999,'testbyhao','testtype');
这样的语法看起来很特殊,其实是insert进subquery里的这张表里,只不过如果不满足subquery里的where条件的话,就不允许插入。
如果插入的列有不在subquery作为检查的where条件里,那么也会不允许插入。
如果不加WITH CHECK OPTION则在插入时不会检查。
这里注意,subquery其实是不会实际执行的。
Q21
Gaps in the Sequence
Although sequence generators issue sequential numbers without gaps, this action occurs independent of a commit or rollback. Therefore, if you roll back a statement
containing a sequence, the number is lost.
Another event that can cause gaps in the sequence is a system crash. If the sequence caches values in memory, those values are lost if the system crashes. Because
sequences are not tied directly to tables, the same sequence can be used for multiple tables.
However, if you do so, each table can contain gaps in the sequential numbers.
Modifying a Sequence
If you reach the MAXVALUE limit for your sequence, no additional values from the sequence are allocated and you will receive an error indicating that the sequence
exceeds the MAXVALUE. To continue to use the sequence, you can modify it by using the ALTER SEQUENCE statement To remove a sequence, use the DROP
statement:
DROP SEQUENCE dept_deptid_seq;
Q22.
Creating a Synonym for an Object
To refer to a table that is owned by another user, you need to prefix the table name with the name of the user who created it, followed by a period. Creating a synonym
eliminates the need to qualify the object name with the schema and provides you with an alternative name for a table, view, sequence, procedure, or other objects.
This method can be especially useful with lengthy object names, such as views.
In the syntax:
PUBLIC Creates a synonym that is accessible to all users synonym Is the name of the synonym to
be created object Identifies the object for which the synonym is created Guidelines
The object cannot be contained in a package.
Q24
Q25
1、关于trunc 和round函数比较
整体概括:
round函数 四舍五入
trunc函数 直接截取
对于时间:
Round函数对日期进行“四舍五入”,Trunc函数对日期进行截取。如果我们不指定格式的话,Round会返回一个最接近date参数的日期,而Trunc函数只会简单的截取时分秒部分,返回年月日部分
对于数字:
Round函数对数字同样进行“四舍五入”,Trunc函数截取时不进行四舍五入,可以指明保留小数点后面的位数。
2、Round、Trunc用法
[sql] view plain copy 在CODE上查看代码片派生到我的代码片
/**************************For date****************************/
--Trunc函数
SELECT TRUNC(SYSDATE), -- 今天的日期为 2014-05-08
TRUNC(SYSDATE, 'YYYY'), --返回当年第一天 2014-01-01 yyyy/yy/year 年
TRUNC(SYSDATE, 'MM'), --返回当月第一天 2014-05-01 mm/month 月
TRUNC(SYSDATE, 'DD'), --返回当前年月日 2014-05-08 d/day 周
TRUNC(SYSDATE, 'D'), --(星期天)返回当前星期的第一天 2014-05-04
TRUNC(SYSDATE, 'HH'), --返回当前时间精确小时 2014-05-08 11:00:00
TRUNC(SYSDATE, 'MI') -- 返回当前时间精确分钟 2014-05-08 11:06:00 TRUNC()函数没有秒的精确
FROM DUAL;
--Round函数
select Round(sysdate, 'Q') Rnd_Q, --2014-04-01
Round(sysdate, 'Month') Rnd_Month, --2014-05-01
Round(sysdate, 'WW') Rnd_Week, --2014-05-07
Round(sysdate, 'W') Rnd_Week_again, --2014-05-08
Round(sysdate, 'DDD') Rnd_day, --2014-05-08
Round(sysdate, 'DD') Rnd_day_again, --2014-05-08
Round(sysdate, 'DAY') Rnd_day_of_week, --2014-05-11
Round(sysdate, 'D') Rnd_day_of_week_again, --2014-05-11
Round(sysdate, 'HH12') Rnd_hour_12, --2014-05-08 12:00:00
Round(sysdate, 'HH24') Rnd_hour_24, --2014-05-08 12:00:00
Round(sysdate, 'MI') Rnd_minute --2014-05-08 11:52:00
from dual;
/****************************For number************************/
/**
--TRUNC(number,num_digits)
Number 需要截尾取整的数字。
Num_digits 指明需保留小数点后面的位数。可选项,忽略他则截去任何的小数部分,Num_digits 的默认值为 0,
--此参数够为负数,表示为小数点左边指定位数后面的部分截去,即均以0记。
TRUNC()函数截取时不进行四舍五入**/
--TRUNC函数
select TRUNC(123.458), --123
TRUNC(123.458, 0), --123
TRUNC(123.458, 1), --123.4
TRUNC(123.458, 2), --123.45
TRUNC(123.458, 3), --123.458
TRUNC(123.458, 4), --123.458
TRUNC(123.458, -1), --120
TRUNC(123.458, -2), --100
TRUNC(123.458, -3), --0
TRUNC(123.458, -4), --0
TRUNC(123), --123
TRUNC(123, 1), --123
TRUNC(123, 2), --123
TRUNC(123, 3), --123
TRUNC(123, 4) --123
from dual;
--Round函数
select Round(123.458), --123
Round(123.458, 0), --123
Round(123.458, 1), --123.5
Round(123.458, 2), --123.46
Round(123.458, 3), --123.458
Round(123.458, 4), --123.458
Round(123.458, -1), --120
Round(123.458, -2), --100
Round(123.458, -3), --0
Round(123.458, -4), --0
Round(123), --123
Round(123, 1), --123
Round(123, 2), --123
Round(123, 3), --123
Round(123, 4) --123
from dual;
Q26
A function is a program written to optionally accept input parameters, perform an operation, or return a single value. A function returns only one value per execution.
Three important components form the basis of defining a function. The first is the input parameter list. It specifies zero or more arguments that may be passed to a
function as input for processing. These arguments or parameters may be of differing data types, and some are mandatory while others may be optional. The second
component is the data type of its resultant value. Upon execution, only one value is returned by the function. The third encapsulates the details of the processing
performed by the function and contains the program code that optionally manipulates the input parameters, performs calculations and operations, and generates a return
value.
Q27
The SQL UNION query allows you to combine the result sets of two or more SQL SELECT statements. It removes duplicate rows between the various SELECT
statements. Each SQL SELECT statement within the UNION query must have the same number of fields in the result sets with similar data types.
Q28
The Oracle Database stores dates in an internal numeric format, representing the century, year, month, day, hours, minutes, and seconds.
The default display and input format for any date is DD-MON-RR.
RR Date Format
The RR date format is similar to the YY element, but you can use it to specify different centuries. Use the RR date format element instead of YY so that the century of the
return value varies according to the specified two digit year and the last two digits of the current year. The table in the slide summarizes the behavior of the RR element.
Note the values shown in the last two rows of the above table. As we approach the middle of the century, then the RR behavior is probably not what you want.
This data is stored internally as follows:
CENTURY YEAR MONTH DAY HOUR MINUTE SECOND 19 87 06 17 17 10 43
Q29.
. The VALUES clause cannot be used in an INSERT with a subquery
Q32.
Q34.
Using the COUNT Function
The COUNT function has three formats:
COUNT(*)
COUNT(expr)
COUNT(DISTINCT expr)
COUNT(*) returns the number of rows in a table that satisfy the criteria of the SELECT statement, including duplicate rows and rows containing null values in any of the
columns. If a WHERE clause is included in the SELECT statement, COUNT(*) returns the number of rows that satisfy the condition in the WHERE clause.
In contrast,
COUNT(expr) returns the number of non-null values that are in the column identified by expr.
COUNT(DISTINCT expr) returns the number of unique, non-null values that are in the column identified by expr.
Q35.
1、LONG 数据类型中存储的是可变长字符串,最大长度限制是2GB。
2、对于超出一定长度的文本,基本只能用LONG类型来存储,数据字典中很多对象的定义就是用LONG来存储的。
1、LONG 数据类型中存储的是可变长字符串,最大长度限制是2GB。
2、对于超出一定长度的文本,基本只能用LONG类型来存储,数据字典中很多对象的定义就是用LONG来存储的。
3、LONG类型主要用于不需要作字符串搜索的长串数据,如果要进行字符搜索就要用varchar2类型。
4、很多工具,包括SQL*Plus,处理LONG 数据类型都是很困难的。
5、LONG 数据类型的使用中,要受限于磁盘的大小。
能够操作 LONG 的 SQL 语句:
1、Select语句
2、Update语句中的SET语句
3、Insert语句中的VALUES语句
限制:
1、一个表中只能包含一个 LONG 类型的列。
2、不能索引LONG类型列。
3、不能将含有LONG类型列的表作聚簇。
4、不能在SQL*Plus中将LONG类型列的数值插入到另一个表格中,如insert into ...select。
5、不能在SQL*Plus中通过查询其他表的方式来创建LONG类型列,如create table as select。
6、不能对LONG类型列加约束条件(NULL、NOT NULL、DEFAULT除外),如:关键字列(PRIMARY KEY)不能是 LONG 数据类型。
7、LONG类型列不能用在Select的以下子句中:where、group by、order by,以及带有distinct的select语句中。
8、LONG类型列不能用于分布查询。
Q36.
PRIMARY KEY Constraint
A PRIMARY KEY constraint creates a primary key for the table. Only one primary key can be created for each table. The PRIMARY KEY constraint is a column or a set
of columns that uniquely identifies each row in a table. This constraint enforces the uniqueness of the column or column combination and ensures that no column that is
part of the primary key can contain a null value.
Note: Because uniqueness is part of the primary key constraint definition, the Oracle server enforces the uniqueness by implicitly creating a unique index on the primary
key column or columns
Q38.
NVL Function
Converts a null value to an actual value:
Data types that can be used are date, character, and number.
Data types must match:
- NVL(commission_pct,0)
- NVL(hire_date,'01-JAN-97')
- NVL(job_id,'No Job Yet')\
Q39.
(88)You need to calculate the number of days from 1st January 2007 till date. Dates are stored in the default format of dd-mon-rr.
Which SQL statements would give the required output? (Choose two .)
A. SELECT SYSDATE - '01-JAN-2007' FROM DUAL;
B. SELECT SYSDATE - TO_DATE('01/JANUARY/2007') FROM DUAL;
C. SELECT SYSDATE - TO_DATE('01-JANUARY-2007') FROM DUAL;
D. SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY') - '01-JAN-2007' FROM DUAL;
E. SELECT TO_DATE(SYSDATE, 'DD/MONTH/YYYY') - '01/JANUARY/2007' FROM DUAL;
答案:(B、C)
解析:
--A(X),会隐式将'11-MAR-14'转换为数字,而不是日期。
scott@TESTDB11>select sysdate - '11-MAR-14' from dual;
select sysdate - '11-MAR-14' from dual
*
ERROR at line 1:
ORA-01722: invalid number
-- B, 与默认的日期格式一致(即使指定4位的年也可以)
scott@TESTDB11>select sysdate - to_date('11-MAR-14') from dual;
SYSDATE-TO_DATE('11-MAR-14')
----------------------------
-.76417824
-- C, 与默认的日期格式的区别只在分隔符上,也可以正确执行
scott@TESTDB11>select sysdate - to_date('11/MAR/14') from dual;
SYSDATE-TO_DATE('11/MAR/14')
----------------------------
-.76405093
Q40.
Q41.
NVL Function
Converts a null value to an actual value:
Data types that can be used are date, character, and number.
Data types must match:
- NVL(commission_pct,0)
- NVL(hire_date,'01-JAN-97')
- NVL(job_id,'No Job Yet')
MONTHS_BETWEEN(date1, date2): Finds the number of months between date1 and date2 The result can be positive or negative. If date1 is later than date2, the result
is positive; if date1 is earlier than date2, the result is negative. The noninteger part of the result represents a portion of the month.
MONTHS_BETWEEN returns a numeric value. - answer C NVL has different datatypes - numeric and strings, which is not possible!
The data types of the original and if null parameters must always be compatible. They must either be of the same type, or it must be possible to implicitly convert if null
to the type of the original parameter. The NVL function returns a value with the same data type as the original parameter.
Q44.
Creating Joins with the USING Clause
Natural joins use all columns with matching names and data types to join the tables. The USING clause can be used to specify only those columns that should be usedfor an equijoin.
The Natural JOIN USING Clause
The format of the syntax for the natural JOIN USING clause is as follows:
SELECT table1.column, table2.column
FROM table1
JOIN table2 USING (join_column1, join_column2...);
While the pure natural join contains the NATURAL keyword in its syntax, the JOIN...USING syntax does not.
An error is raised if the keywords NATURAL and USING occur in the same join clause. The JOIN...USING clause allows one or more equijoin columns to be explicitly
specified in brackets after the USING keyword. This avoids the shortcomings associated with the pure natural join. Many situations demand that tables be joined only on
certain columns, and this format caters to this requirement.
Q45.
Rules for Performing DML Operations on a View
You cannot add data through a view if the view includes:
Group functions
A GROUP BY clause
The DISTINCT keyword
The pseudocolumn ROWNUM keyword
Columns defined by expressions
NOT NULL columns in the base tables that are not selected by the view
Q46.
LONG Character data in the database character set, up to 2GB. All the functionality of LONG (and more) is provided by CLOB; LONGs should not be used in a modern
database, and if your database has any columns of this type they should be converted to CLOB. There can only be one LONG column in a table.
DVARCHAR2 Variable-length character data, from 1 byte to 4KB. The data is stored in the database character set. The VARCHAR2 data type must be qualified with a
number indicating the maximum length of the column.
If a value is inserted into the column that is less than this, it is not a problem: the value will only take up as much space as it needs. If the value is longer than this
maximum, the INSERT will fail with an error. VARCHAR2(size)
Variable-length character data (A maximum size must be specified: minimum size is 1; maximum size is 4,000.)
BLOB Like CLOB, but binary data that will not undergo character set conversion by Oracle Net. BFILE A locator pointing to a file stored on the operating system of the
database server. The size of the files is limited to 4GB.
TIMESTAMP This is length zero if the column is empty, or up to 11 bytes, depending on the precision specified.
Similar to DATE, but with precision of up to 9 decimal places for the seconds, 6 places by default.
Q47.
The MERGE Statement allows you to conditionally insert or update data in a table. If the rows are present in the target table which match the join condition, they are
updated if the rows are not present they are inserted into the target table
Q48.
Rules for Performing DML Operations on a View
You cannot add data through a view if the view includes:
Group functions
A GROUP BY clause
The DISTINCT keyword
The pseudocolumn ROWNUM keyword
Columns defined by expressions
NOT NULL columns in the base tables that are not selected by the views
Q50.
RIGHT OUTER JOIN
其实这三种都是表链接的方式,right 和left
join是外连接的两种方式。
select t1.col1, t2.col2 from t1
right(或者) left outer join
t2 on t1.id = t2.id。
这两个你用哪个都是无所谓的,关键是看你到底是要用那张表作为驱动表,
说的通俗一点就是如果是left,就要要把左边那张表(t1)里的列数据都查出来,不管跟第二张表有没有匹配.
如果匹配那么,结果集中就会出现col2,如果没有对应的col2,那么这一行记录就会
对应一个null
也就是这一行记录就成了col1, null
相反如果是right: null, col2
full join,就是把两种情况给综合起来.都放到结果集中.
也就是结果集中可能出现: col1, null
null, col2
col1, col2
Q52.
ORACLE集合操作函数:UNION、INTERSECT、MINUS
集合操作不适用于LOB,Varray和潜逃表列
Union、intersect、minus操作符不适用于long列
如果选择列表中包含有表达式或者函数,那么必须为表达式或函数定义列别名
1、Uinon:无重并集,并以第一列的结果进行升序排序
2、Uinon all:有重并集,不对结果集排序
3、Intersect:交集,以第一列的结果进行升序排列
4、Minus:差集,以第一列的结果进行升序排列
5、可使用order by,必须放在最后一条select之后,当列名相同时,可以直接用列名排序,如果不同可以用位置排序,也可以使用别名使其相同。
Q53.
Using the NVL2 Function
The NVL2 function examines the first expression. If the first expression is not null, the NVL2 function returns the second expression. If the first expression is null, the third
expression is returned.
Syntax
NVL2(expr1, expr2, expr3)
In the syntax:
expr1 is the source value or expression that may contain a null expr2 is the value that is returned if expr1 is not null expr3 is the value that is returned if expr1 is null
Q58.
日期-日期,返回的是天数,是一个数字,
由本地连接到远程,SYSDATE是一个 SQL 函数,它用于返回当前所连接的远程服务器上数据库的日期和时间。
59.
Note: The IN operator is internally evaluated by the Oracle server as a set of OR conditions, such as a=value1 or a=value2 or a=value3. Therefore, using the IN operator
has no performance benefits and is used only for logical simplicity.
Q60,
1、Uinon:无重并集,并以第一列的结果进行升序排序
2、Uinon all:有重并集,不对结果集排序
3、Intersect:交集,以第一列的结果进行升序排列
4、Minus:差集,以第一列的结果进行升序排列
Q62.
Object privilege on VIEW is DELETE, INSERT, REFERENCES, SELECT and UPDATE
Q63.
C. When a data definition language statement is executed
D. When a TRUNCATE statement is executed after the pending transaction
E. When a ROLLBACK command is execute
Q65.
INTERVAL DAY TO SECOND类型可以用来存储单位为天和秒的时间间隔。下面这条语句创建一个名为promotions的表,用来存储促销信息。promotions表包含了一个INTERVAL DAY TO SECOND类型的列duration,该列用来记录促销有效的时间间隔:
CREATE TABLE promotions (
promotion_id INTEGER CONSTRAINT promotions_pk PRIMARY KEY,
name VARCHAR2(30) NOT NULL,
duration INTERVAL DAY(3) TO SECOND (4)
);
注意此处指定了duration列中天的精度为3,秒的小数部分精度为4。这就是说可以为该列的天存储3位数字,而为该列的秒最多可以在小数点右边存储4位数字。
Q69.
CASE Expression
Facilitates conditional inquiries by doing the work of an IF-THEN-ELSE statement:
CASE expr WHEN comparison_expr1 THEN return_expr1
[WHEN comparison_expr2 THEN return_expr2
WHEN comparison_exprn THEN return_exprn
ELSE else_expr]
END
Q70.
--A(X), USING只能用于等值连接
--B(X), 可以指定多个pair of columns
select e.empno, e.ename, e.deptno, d.loc
from emp e join dept d
on(e.deptno = d.deptno and d.deptno = e.deptno)
where empno = 7788;
--D
--ON可以与WHERE一起使用
select e.empno, e.ename, e.deptno, d.deptno, d.loc
from emp e join dept d
on(e.deptno = d.deptno)
where e.empno = 7788;
EMPNO ENAME DEPTNO DEPTNO LOC
---------- ---------- ---------- ---------- -------------
7788 SCOTT 20 20 DALLAS
--USING可以和WHERE一起使用
select e.empno, e.ename, deptno, d.loc
from emp e join dept d
using(deptno)
where empno = 7788;
EMPNO ENAME DEPTNO LOC
---------- ---------- ---------- -------------
7788 SCOTT 20 DALLAS
Q75.
Creating a Table Using a Subquery
Create a table and insert rows by combining the CREATE TABLE statement and the AS subquery option.
CREATE TABLE table
[(column, column...)]
AS subquery;
Match the number of specified columns to the number of subquery columns. Define columns with column names and default values.
Guidelines
The table is created with the specified column names, and the rows retrieved by the SELECT statement are inserted into the table.
The column definition can contain only the column name and default value. If column specifications are given, the number of columns must equal the number of columns
in the subquery SELECT list.
If no column specifications are given, the column names of the table are the same as the column names in the subquery.
The column data type definitions and the NOT NULL constraint are passed to the new table. Note that only the explicit NOT NULL constraint will be inherited. The
PRIMARY KEY column will not pass the NOT NULL feature to the new column. Any other constraint rules are not passed to the new table. However, you can add
constraints in the column definition.
Q77.
Using the TO_CHAR Function with Dates
TO_CHAR converts a datetime data type to a value of VARCHAR2 data type in the format specified by the format_model. A format model is a character literal that
describes the format of datetime stored in a character string. For example, the datetime format model for the string '11- Nov-1999' is 'DD-Mon-YYYY'. You can use the
TO_CHAR function to convert a date from its default format to the one that you specify.
Guidelines
· The format model must be enclosed with single quotation marks and is case-sensitive. · The format model can include any valid date format element. But be sure to
separate the date value from the format model with a comma.
· The names of days and months in the output are automatically padded with blanks. · To remove padded blanks or to suppress leading zeros, use the fill mode fm
element.
Elements of the Date Format Model
--------------------------------------------------------------------- DY Three-letter abbreviation of the day of the week
DAY Full name of the day of the week
DD Numeric day of the month
MM Two-digit value for the month
MON Three-letter abbreviation of the month
MONTH Full name of the month
YYYY Full year in numbers
YEAR Year spelled out (in English)
Q78.
INTERSECT Returns only the rows that occur in both queries' result sets, sorting them and removing duplicates.
The columns in the queries that make up a compound query can have different names, but the output result set will use the names of the columns in the first query.
Q83.
You cannot use column alias in the WHERE clause.
Q86.
The NVL2 Function
The NVL2 function provides an enhancement to NVL but serves a very similar purpose. It evaluates whether a column or expression of any data type is null or not.
5-6 The NVL function\
If the first term is not null, the second parameter is returned, else the third parameter is returned. Recall that the NVL function is different since it returns the original term
if it is not null. The NVL2 function takes three mandatory parameters. Its syntax is NVL2(original, ifnotnull, ifnull), where original represents the term being tested. Ifnotnull
is returned if original is not null, and ifnull is returned if original is null. The data types of the ifnotnull and ifnull parameters must be compatible, and they cannot be of type
LONG.
They must either be of the same type, or it must be possible to convert ifnull to the type of the ifnotnull parameter. The data type returned by the NVL2 function is the
same as that of the ifnotnull parameter.
Q87.
Updating Two Columns with a Subquery
You can update multiple columns in the SET clause of an UPDATE statement by writing multiple subqueries. The syntax is as follows:
UPDATE table
SET column =
(SELECT column
FROM table
WHERE condition)
[ ,
column =
(SELECT column
FROM table
WHERE condition)]
[WHERE condition ] ;
Q88.
A SELECT statement can be used to perform these three functions:
selection, projection, join
Q91.
Table names and column names must begin with a letter and be 1-30 characters long. Characters A-Z,a-z, 0-9, _, $ and # (legal characters but their use is discouraged).
Incorrect answer:
BNon alphanumeric character such as "*" is discourage in Oracle table name.
DTable name must begin with a letter.
Q92.
view
A. It allows you to update job IDs of the existing sales staff to any other job ID in the EMPLOYEES table
B. It allows you to delete details of the existing sales staff from the EMPLOYEES table
C. It allows you to insert rows into the EMPLOYEES table
D. It allows you to insert IDs, last names, and job IDs of the sales staff from the view if it is used in multitable INSERT statements
Answer: B,D
Q97.
DECODE
he DECODE Function
Although its name sounds mysterious, this function is straightforward. The DECODE function implements ifthen-else conditional logic by testing its first two terms for
equality and returns the third if they are equal and optionally returns another term if they are not. The DECODE function takes at least three mandatory parameters, but
can take many more. The syntax of the function is DECODE(expr1,comp1, iftrue1, [comp2,iftrue2...[ compN,iftrueN]], [iffalse]).
Q98.
SQL> alter session set nls_date_language='american' ;
会话已更改。
SQL> SELECT TO_CHAR(TO_DATE('19-mar-2001', 'DD-Mon-YYYY'), 'Ddspth "of" Month YY
YY fmHH:MI:SS AM') NEW_DATE FROM dual;
NEW_DATE
----------------------------------------------------------------------------
Nineteenth of March 2001 12:0:0 AM
SQL> SELECT TO_CHAR(TO_DATE('19-mar-2001', 'DD-Mon-YYYY'), 'fmDdspth "of" Month
YYYY fmHH:MI:SS AM') NEW_DATE FROM dual;
NEW_DATE
------------------------------------------------------------------------
Nineteenth of March 2001 12:00:00 AM
Q99.
Which tasks can be performed using SQL functions built into Oracle Database ? (Choose three.)
A. displaying a date in a nondefault format
B. finding the number of characters in an expression
C. substituting a character string in a text expression with a specified string
D. combining more than two columns or expressions into a single column in the output
Answer: ABC
答案解析:
题意问:内置到Oracle数据库使用SQL函数可以执行哪些任务? (选择三项)。
A.显示一个非默认格式的日期,例如:to_char()转换日期输出
B.在一个表达式中查找字符的数量,使用REGEXP_COUNT 函数。REGEXP_COUNT 返回在源串中出现的模式的次数。
C.使用指定的字符串来替换文本表达式中的字符串,replace函数。
D.联合超过两个列或表达式输出为一个列,contact只能连接两列。||可以连接多个,但它不是SQL函数。
Q100.
TO_DATE
Q101.
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.
Q102.
oracle 中的INTERVAL 函数详解 <转载> (2012-10-10 07:23:23)转载▼
标签: it
分类: 学习笔记
oracle 中的INTERVAL 函数详解
分类: oracle 2010-04-30 11:32 661人阅读 评论(0) 收藏 举报
INTERVAL YEAR TO MONTH数据类型
Oracle语法:
INTERVAL 'integer [- integer]' {YEAR | MONTH} [(precision)][TO {YEAR | MONTH}]
该数据类型常用来表示一段时间差, 注意时间差只精确到年和月. precision为年或月的精确域, 有效范围是0到9, 默认值为2.
eg:
INTERVAL '123-2' YEAR(3) TO MONTH
表示: 123年2个月, "YEAR(3)" 表示年的精度为3, 可见"123"刚好为3为有效数值, 如果该处YEAR(n), n<3就会出错, 注意默认是2.
INTERVAL '123' YEAR(3)
表示: 123年0个月
INTERVAL '300' MONTH(3)
表示: 300个月, 注意该处MONTH的精度是3啊.
INTERVAL '4' YEAR
表示: 4年, 同 INTERVAL '4-0' YEAR TO MONTH 是一样的
INTERVAL '50' MONTH
表示: 50个月, 同 INTERVAL '4-2' YEAR TO MONTH 是一样
INTERVAL '123' YEAR
表示: 该处表示有错误, 123精度是3了, 但系统默认是2, 所以该处应该写成 INTERVAL '123' YEAR(3) 或"3"改成大于3小于等于9的数值都可以的
INTERVAL '5-3' YEAR TO MONTH + INTERVAL '20' MONTH =
INTERVAL '6-11' YEAR TO MONTH
表示: 5年3个月 + 20个月 = 6年11个月
与该类型相关的函数:
NUMTODSINTERVAL(n, 'interval_unit')
将n转换成interval_unit所指定的值, interval_unit可以为: DAY, HOUR, MINUTE, SECOND
注意该函数不可以转换成YEAR和MONTH的.
NUMTOYMINTERVAL(n, 'interval_unit')
interval_unit可以为: YEAR, MONTH
eg: (Oracle Version 9204, RedHat Linux 9.0)
SQL> select numtodsinterval(100,'DAY') from dual;
NUMTODSINTERVAL(100,'DAY')
---------------------------------------------------------------------------
+000000100 00:00:00.000000000
SQL> c/DAY/SECOND
1* select numtodsinterval(100,'SECOND') from dual
SQL> /
NUMTODSINTERVAL(100,'SECOND')
---------------------------------------------------------------------------
+000000000 00:01:40.000000000
SQL> c/SECOND/MINUTE
1* select numtodsinterval(100,'MINUTE') from dual
SQL> /
NUMTODSINTERVAL(100,'MINUTE')
---------------------------------------------------------------------------
+000000000 01:40:00.000000000
SQL> c/MINUTE/HOUR
1* select numtodsinterval(100,'HOUR') from dual
SQL> /
NUMTODSINTERVAL(100,'HOUR')
---------------------------------------------------------------------------
+000000004 04:00:00.000000000
SQL> c/HOUR/YEAR
1* select numtodsinterval(100,'YEAR') from dual
SQL> /
select numtodsinterval(100,'YEAR') from dual
*
ERROR at line 1:
ORA-01760: illegal argument for function
SQL> select numtoyminterval(100,'year') from dual;
NUMTOYMINTERVAL(100,'YEAR')
---------------------------------------------------------------------------
+000000100-00
SQL> c/year/month
1* select numtoyminterval(100,'month') from dual
SQL> /
NUMTOYMINTERVAL(100,'MONTH')
---------------------------------------------------------------------------
+000000008-04
时间的计算:
SQL> select to_date('1999-12-12','yyyy-mm-dd') - to_date('1999-12-01','yyyy-mm-dd') from dual;
TO_DATE('1999-12-12','YYYY-MM-DD')-TO_DATE('1999-12-01','YYYY-MM-DD')
---------------------------------------------------------------------
11
-- 可以相减的结果为天.
SQL> c/1999-12-12/1999-01-12
1* select to_date('1999-01-12','yyyy-mm-dd') - to_date('1999-12-01','yyyy-mm-dd') from dual
SQL> /
TO_DATE('1999-01-12','YYYY-MM-DD')-TO_DATE('1999-12-01','YYYY-MM-DD')
---------------------------------------------------------------------
-323
-- 也可以为负数的
SQL> c/1999-01-12/2999-10-12
1* select to_date('2999-10-12','yyyy-mm-dd') - to_date('1999-12-01','yyyy-mm-dd') from dual
SQL> /
TO_DATE('2999-10-12','YYYY-MM-DD')-TO_DATE('1999-12-01','YYYY-MM-DD')
---------------------------------------------------------------------
365193
下面看看INTERVAL YEAR TO MONTH怎么用.
SQL> create table bb(a date, b date, c interval year(9) to month);
Table created.
SQL> desc bb;
Name Null? Type
----------------------------------------- -------- ----------------------------
A DATE
B DATE
C INTERVAL YEAR(9) TO MONTH
SQL> insert into bb values(to_date('1985-12-12', 'yyyy-mm-dd'), to_date('1984-12-01','yyyy-mm-dd'), null)
1 row created.
SQL> select * from bb;
A B
--------- ---------
C
---------------------------------------------------------------------------
12-DEC-85 01-DEC-84
SQL> update bb set c = numtoyminterval(a-b, 'year');
1 row updated.
SQL> select * from bb;
A B
--------- ---------
C
---------------------------------------------------------------------------
12-DEC-85 01-DEC-84
+000000376-00
-- 直接将相减的天变成年了, 因为我指定变成年的
SQL> select a-b, c from bb;
A-B
----------
C
---------------------------------------------------------------------------
376
+000000376-00
SQL> insert into bb values(null,null,numtoyminterval(376,'month'));
1 row created.
SQL> select * from bb;
A B C
--------- --------- --------------------------------------------
12-DEC-85 01-DEC-84 +000000376-00
+000000031-04
SQL> insert into bb values ( null,null, numtoyminterval(999999999,'year'));
1 row created.
SQL> select * from bb;
A B C
--------- --------- ---------------------------------------------------------------------
12-DEC-85 01-DEC-84 +000000376-00
+000000031-04
+999999999-00
========================
今天来添加点新的东西![2008-07-26] 这部分东东来源:http://www.oraclefans.cn/forum/showblog.jsp?rootid=139
INTERVAL YEAR TO MONTH类型2个TIMESTAMP类型的时间差别。内部类型是182,长度是5。其中4个字节存储年份差异,存储的时候在差异上加了一个0X80000000的偏移量。一个字节存储月份的差异,这个差异加了60的偏移量。
SQL> ALTER TABLE TestTimeStamp ADD E INTERVAL YEAR TO MONTH;
SQL> update testTimeStamp set e=(select interval '5' year + interval '10' month year from dual);
已更新3行。
SQL> commit;
提交完成。
SQL> select dump(e,16) from testTimeStamp;
DUMP(E,16)
---------------------------------------------
Typ=182 Len=5: 80,0,0,5,46
Typ=182 Len=5: 80,0,0,5,46
Typ=182 Len=5: 80,0,0,5,46
年:0X80000005-0X80000000=5
月:0x46-60=10
INTERVAL DAY TO SECOND数据类型
Oracle语法:
INTERVAL '{ integer | integer time_expr | time_expr }'
{ { DAY | HOUR | MINUTE } [ ( leading_precision ) ]
| SECOND [ ( leading_precision [, fractional_seconds_precision ] ) ] }
[ TO { DAY | HOUR | MINUTE | SECOND [ (fractional_seconds_precision) ] } ]
leading_precision值的范围是0到9, 默认是2. time_expr的格式为:HH[:MI[:SS[.n]]] or MI[:SS[.n]] or SS[.n], n表示微秒.
该类型与INTERVAL YEAR TO MONTH有很多相似的地方,建议先看INTERVAL YEAR TO MONTH再看该文.
范围值:
HOUR: 0 to 23
MINUTE: 0 to 59
SECOND: 0 to 59.999999999
eg:
INTERVAL '4 5:12:10.222' DAY TO SECOND(3)
表示: 4天5小时12分10.222秒
INTERVAL '4 5:12' DAY TO MINUTE
表示: 4天5小时12分
INTERVAL '400 5' DAY(3) TO HOUR
表示: 400天5小时, 400为3为精度,所以"DAY(3)", 注意默认值为2.
INTERVAL '400' DAY(3)
表示: 400天
INTERVAL '11:12:10.2222222' HOUR TO SECOND(7)
表示: 11小时12分10.2222222秒
INTERVAL '11:20' HOUR TO MINUTE
表示: 11小时20分
INTERVAL '10' HOUR
表示: 10小时
INTERVAL '10:22' MINUTE TO SECOND
表示: 10分22秒
INTERVAL '10' MINUTE
表示: 10分
INTERVAL '4' DAY
表示: 4天
INTERVAL '25' HOUR
表示: 25小时
INTERVAL '40' MINUTE
表示: 40分
INTERVAL '120' HOUR(3)
表示: 120小时
INTERVAL '30.12345' SECOND(2,4)
表示: 30.1235秒, 因为该地方秒的后面精度设置为4, 要进行四舍五入.
INTERVAL '20' DAY - INTERVAL '240' HOUR = INTERVAL '10-0' DAY TO SECOND
表示: 20天 - 240小时 = 10天0秒
==================
该部分来源:http://www.oraclefans.cn/forum/showblog.jsp?rootid=140
INTERVAL DAY TO SECOND类型存储两个TIMESTAMP之间的时间差异,用日期、小时、分钟、秒钟形式表示。该数据类型的内部代码是183,长度位11字节:
l 4个字节表示天数(增加0X80000000偏移量)
l 小时、分钟、秒钟各用一个字节表示(增加60偏移量)
l 4个字节表示秒钟的小时差异(增加0X80000000偏移量)
以下是一个例子:
SQL> alter table testTimeStamp add f interval day to second ;
表已更改。
SQL> update testTimeStamp set f=(select interval '5' day + interval '10' second from dual);
已更新3行。
SQL> commit;
提交完成。
SQL> select dump(f,16) from testTimeStamp;
DUMP(F,16)
--------------------------------------------------------------------------------
Typ=183 Len=11: 80,0,0,5,3c,3c,46,80,0,0,0
Typ=183 Len=11: 80,0,0,5,3c,3c,46,80,0,0,0
Typ=183 Len=11: 80,0,0,5,3c,3c,46,80,0,0,0
日期:0X80000005-0X80000000=5
小时:60-60=0
分钟:60-60=0
秒钟:70-60=10
秒钟小数部分:0X80000000-0X80000000=0
Q102.
SQL> SELECT INTERVAL '300' MONTH,
2 INTERVAL '54-2' YEAR TO MONTH,
3 INTERVAL '11:12:10.1234567' HOUR TO SECOND
4 FROM DUAL;
INTERVAL'300'MONTH
---------------------------------------------------------------------------
INTERVAL'54-2'YEARTOMONTH
---------------------------------------------------------------------------
INTERVAL'11:12:10.1234567'HOURTOSECOND
---------------------------------------------------------------------------
+25-00
+54-02
+00 11:12:10.123457
Evaluate the following query:
SELECT INTERVAL '300' MONTH, INTERVAL '54-2' YEAR TO MONTH,
INTERVAL '11:12:10.1234567' HOUR TO SECOND
FROM dual;
What is the correct output of the above query?
A. +25-00 , +54-02, +00 11:12:10.123457
B. +00-300, +54-02, +00 11:12:10.123457
C. +25-00 , +00-650, +00 11:12:10.123457
D. +00-300 , +00-650, +00 11:12:10.123457
SQL Language Reference->Literal
Datetime Data Types
You can use several datetime data types:
INTERVAL YEAR TO MONTH
Stored as an interval of years and months
INTERVAL DAY TO SECOND
Stored as an interval of days, hours, minutes,and seconds
给点例子:
时间间隔字面量
说明
INTERVAL '3' DAY
时间间隔为3天
INTERVAL '2' HOUR
时间间隔为2小时
INTERVAL '25' MINUTE
时间间隔为25分钟
INTERVAL '45' SECOND
时间间隔为45秒
INTERVAL '3 2' DAY TO HOUR
时间间隔为3天零2小时
INTERVAL '3 2:25' DAY TO MINUTE
时间间隔为3天零2小时25分
INTERVAL '3 2:25:45' DAY TO SECOND
时间间隔为3天零2小时25分45秒
INTERVAL '123 2:25:45.12' DAY(3)
TO SECOND(2)
时间间隔为123天零2小时25分45.12秒; 天的精度是3位数字,秒的小数部分的精度是2位数字
INTERVAL '3 2:00:45' DAY TO SECOND
时间间隔为3天2小时0分45秒
INTERVAL '-3 2:25:45' DAY TO SECOND
时间间隔为负数,值为3天零2小时25分45秒
INTERVAL '1234 2:25:45' DAY(3)
TO SECOND
时间间隔无效,因为天的位数超过了指定的精度3
INTERVAL '123 2:25:45.123' DAY
TO SECOND(2)
时间间隔无效,因为秒的小数部分的位数超过了指定的精度2
Q103
SEQUENCE 序列默认开始1 步进1
Q104
B: A unique constraint can contain null values because null values cannot be compared to anything.
D: The NOT NULL constraint ensure that null value are not permitted for the column
Q105
SEQUENCE 序列
the EMP_ID_SEQ sequence is not affected by modification to the EMPLOYEES table. Any other column of NUMBER data type in your schema can use the
EMP_ID_SEQ sequence.
Q106.
172. The SQL statements executed in a user session are as follows:
SQL> CREATE TABLE product
(pcode NUMBER(2),
pname VARCHAR2(10));
SQL> INSERT INTO product VALUES (1, 'pen');
SQL> INSERT INTO product VALUES (2,'pencil');
SQL> SAVEPOINT a;
SQL> UPDATE product SET pcode = 10 WHERE pcode = 1;
SQL> SAVEPOINT b;
SQL> DELETE FROM product WHERE pcode = 2;
SQL> COMMIT;
SQL> DELETE FROM product WHERE pcode=10;
Which two statements describe the consequences of issuing the ROLLBACK TO SAVE POINT a
command in the session? (Choose two.)
A. The rollback generates an error.
B. No SQL statements are rolled back.
C. Only the DELETE statements are rolled back.
D. Only the second DELETE statement is rolled back.
E. Both the DELETE statements and the UPDATE statement are rolled back.
Answer: AB
答案解析:
参考:http://blog.csdn.net/rlhua/article/details/12885143
由于COMMIT命令提交后之前建立的保存点都变成无效的了。
ROLLBACK TO SAVEPOINT a;命令报错后,只会影响本身这条语句,不会影响其它语句,所以第二个DELETE语句不会回滚。
实验验证:
sh@TEST0910> create table product
2 (pcode number(2),
3 pname varchar2(10));
Table created.
sh@TEST0910> INSERT INTO product VALUES (1, 'pen');
1 row created.
sh@TEST0910> INSERT INTO product VALUES (2,'pencil');
1 row created.
sh@TEST0910> SAVEPOINT a;
Savepoint created.
sh@TEST0910> UPDATE product SET pcode = 10 WHERE pcode = 1;
1 row updated.
sh@TEST0910> SAVEPOINT b;
Savepoint created.
sh@TEST0910> DELETE FROM product WHERE pcode = 2;
1 row deleted.
sh@TEST0910> COMMIT;
Commit complete.
sh@TEST0910> select * from product;
PCODE PNAME
---------- ----------
10 pen
sh@TEST0910> DELETE FROM product WHERE pcode=10;
1 row deleted.
sh@TEST0910> ROLLBACK TO SAVE POINT a
2 ;
ROLLBACK TO SAVE POINT a
*
ERROR at line 1:
ORA-00933: SQL command not properly ended
Q107.
NVL2(original,ifnotnull,ifnull)
NULLIF(ifunequal,comparison_term)
NVL(original,ifnull)
P370
Q108
Q109.
The general syntax to create a synonym is:
CREATE [PUBLIC] SYNONYM synonym FOR object
Q110.
A. SELECT cust_city, cust_income_level, cust_last_name
FROM customers
ORDER BY cust_city desc, cust_income_level DESC;
Q111.
题目要求:
showing the promo namealong with the customer name for all products
that were sold duringtheir promo campaign and before 30th October 2007
不应该在连接表的时候就加上条件,应该在把条件最后面
Q113.
The SUBSTR(string, start position, number of characters) function accepts three parameters and returns a string consisting of the number of characters extracted from
the source string, beginning at the specified start position:
substr('http://www.domain.com',12,6) = domain
The position at which the first character of the returned string begins.
When position is 0 (zero), then it is treated as 1.
When position is positive, then the function counts from the beginning of string to find the first character.
When position is negative, then the function counts backward from the end of string.
substring_length
The length of the returned string. SUBSTR calculates lengths using characters as defined by the input character set. SUBSTRB uses bytes instead of characters.
SUBSTRC uses Unicode complete characters.
SUBSTR2 uses UCS2 code points. SUBSTR4 uses UCS4 code points. When you do not specify a value for this argument, then the function
The INSTR(source string, search item, [start position],[nth occurrence of search item]) function returns a number that represents the position in the source string,
beginning from the given start position, where the nth occurrence of the search item begins:
Oracle的instr函数使用实例
INSTR方法的格式为
INSTR(src, subStr,startIndex, count)
src: 源字符串
subStr : 要查找的子串
startIndex : 从第几个字符开始。负数表示从右往左查找。
count: 要找到第几个匹配的序号
返回值: 子串在字符串中的位置,第1个为1;不存在为0. (特别注意:如果src为空字符串,返回值为null)。
用法举例:
最简单的一种,查找l字符,首个l位于第3个位置。
SQL> select instr('hello,java world', 'l') from dual;
INSTR('HELLO,JAVAWORLD','L')
----------------------------
3
查找l字符,从第4个位置开始。
SQL> select instr('hello,java world', 'l', 4) from dual;
INSTR('HELLO,JAVAWORLD','L',4)
------------------------------
4
查找l字符,从第1个位置开始的第3个
SQL> select instr('hello,java world', 'l', 1, 3) from dual;
INSTR('HELLO,JAVAWORLD','L',1,
------------------------------
15
查找l字符,从右边第1个位置开始,从右往左查找第3个(也即是从左到右的第1个)
SQL> select instr('hello,java world', 'l', -1, 3) from dual;
INSTR('HELLO,JAVAWORLD','L',-1
------------------------------
3
找不到返回0
SQL> select instr('hello,java world', 'MM') from dual;
INSTR('HELLO,JAVAWORLD','MM')
-----------------------------
0
Q115.
Duplicate Rows
Unless you indicate otherwise, SQL displays the results of a query without eliminating the duplicate rows.
To eliminate duplicate rows in the result, include the DISTINCT keyword in the SELECT clause immediately after the SELECT keyword.
You can specify multiple columns after the DISTINCT qualifier. The DISTINCT qualifier affects all the selected columns, and the result is every distinct combination of the
columns.
Q116.
一、原题
View the Exhibit and examine the structure of the PROMOTIONS table.
Which SQL statements are valid? (Choose all that apply.)
A. SELECT promo_id, DECODE(NVL(promo_cost,0), promo_cost,promo_cost * 0.25, 100) "Discount"
FROM promotions;
B. SELECT promo_id, DECODE(promo_cost, 10000,DECODE(promo_category, 'G1', promo_cost *.25, NULL),NULL) "Catcost"
FROM promotions;
C. SELECT promo_id, DECODE(NULLIF(promo_cost, 10000),NULL, promo_cost*.25, 'N/A') "Catcost"
FROM promotions;
D. SELECT promo_id, DECODE(promo_cost, >10000, 'High',<10000, 'Low') "Range"
FROM promotions;
答案:AB
二、题目翻译
查看 PROMOTIONS 表的结构
选择所有有效的SQL语句(选择所有正确的选项)。
三、题目解析
C选项不正确,前面几个参数都是number类型,最后一个是字符类型,隐式转换数值时不成功。
D选项语法不正确。
Q118.
So, how are words that contain single quotation marks dealt with? There are essentially two mechanisms available. The most popular of these is to add an additional
single quotation mark next to each naturally occurring single quotation mark in the character string Oracle offers a neat way to deal with this type of character literal in the
form of the alternative quote (q) operator. Notice that the problem is that Oracle chose the single quote characters as the special pair of symbols that enclose or wrap any
other character literal. These character-enclosing symbols could have been anything other than single quotation marks. Bearing this in mind, consider the alternative
quote (q) operator. The q operator enables you to choose from a set of possible pairs of wrapping symbols for character literals as alternatives to the single quote
symbols. The options are any single-byte or multibyte character or the four brackets:
(round brackets), {curly braces},
[squarebrackets], or . Using the q operator, the character delimiter can effectively be changed from a single quotation mark to any other character The
syntax of the alternative quote operator is as follows:
q'delimiter'character literal which may include the single quotes delimiter' where delimiter can be any character or bracket.
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: ]' || manager_id
AS "Department and Manager"
FROM departments;
Alternative Quote (q) Operator
Many SQL statements use character literals in expressions or conditions. If the literal itself contains a single quotation mark, you can use the quote (q) operator and
select your own quotation mark delimiter.
You can choose any convenient delimiter, single-byte or multibyte, or any of the following character pairs: [ ], { }, ( ), or < >.
In the example shown, the string contains a single quotation mark, which is normally interpreted as a delimiter of a character string. By using the q operator, however,
brackets [] are used as the quotation mark delimiters. The string between the brackets delimiters is interpreted as a literal character string.
求助,关于输出"’"的问题.
需要输出的语句为Envoy Ambassador's category is Hardware;
有4个选项,
A. SELECT prod_name || q'''s category is ' || prod_category CATEGORIES
FROM products;
B. SELECT prod_name || q'['s ]'category is ' || prod_category CATEGORIES
FROM products;
C. SELECT prod_name || q'\'s\' || ' category is ' || prod_category CATEGORIES
FROM products;
D. SELECT prod_name || q'<'s >' || 'category is ' || prod_category CATEGORIES
FROM products;
D选项测试过了,是对的,C选项对不对?为什么我测试的是不对的呢,但是答案是CD.
求高手指教,谢谢
------解决方案--------------------
SQL code
SQL> SELECT q'<'s >' from dual;
Q'<
---
's
SQL> SELECT q'\'s \' from dual;
Q'\
---
's
SQL> SELECT q'['s ]' from dual;
Q'[
---
's
就是一个转义字符一样的了
------解决方案--------------------
oracle里面转义的方法有很多 不过一般要显示单引号 可以这么用 不用转义
SQL code
select 'Ambassador'||chr(39)||'s' c1
from dual
Q119.
Combining Wildcard Characters
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 '\';
Q121.
Using the ANY Operator in Multiple-Row Subqueries
The ANY operator (and its synonym, the SOME operator) compares a value to each value returned by a subquery.
>ANY means more than the minimum.
=ANY is equivalent to IN
Using the ALL Operator in Multiple-Row Subqueries
The ALL operator compares a value to every value returned by a subquery.
>ALL means more than the maximum and
The NOT operator can be used with IN, ANY, and ALL operators.
Q124.
Using the ORDER BY Clause in Set Operations
- The ORDER BY clause can appear only once at the end of the compound query.
- Component queries cannot have individual ORDER BY clauses.
- The ORDER BY clause recognizes only the columns of the first SELECT query.
- By default, the first column of the first SELECT query is used to sort the output in an ascending order
Q125.
Schema Object Naming Rules
因为专业、所以必过
QQ: 6693 0855 微信: anypass
Every database object has a name. In a SQL statement, you represent the name of an object with a quoted identifier or a nonquoted identifier.
A quoted identifier begins and ends with double quotation marks ("). If you name a schema object using a quoted identifier, then you must use the double quotation marks
whenever you refer to that object.
A nonquoted identifier is not surrounded by any punctuation. The following list of rules applies to both quoted and nonquoted identifiers unless otherwise
indicated:
Names must be from 1 to 30 bytes long with these exceptions:
Names of databases are limited to 8 bytes.
Names of database links can be as long as 128 bytes. If an identifier includes multiple parts separated by periods, then each attribute can be up to 30 bytes long.
Each period separator, as well as any surrounding double quotation marks, counts as one byte. For example, suppose you identify a column like this:
"schema"."table"."column"
Nonquoted identifiers cannot be Oracle Database reserved words (ANSWER D). Quoted identifiers can be reserved words, although this is not recommended.
Depending on the Oracle product you plan to use to access a database object, names might be further restricted by other product-specific reserved words. The Oracle
SQL language contains other words that have special meanings. These words include datatypes, schema names, function names, the dummy system table DUAL, and
keywords (the uppercase words in SQL statements, such as DIMENSION, SEGMENT, ALLOCATE, DISABLE, and so forth). These words are not reserved. However,
Oracle uses them internally in specific ways. Therefore, if you use these words as names for objects and object parts, then your SQL statements may be more difficult to
read and may lead to unpredictable results. In particular, do not use words beginning with SYS_ as schema object names, and do not use the names of SQL built-in
functions for the names of schema objects or user-defined functions. You should use ASCII characters in database names, global database names, and database link
names, because ASCII characters provide optimal compatibility across different platforms and operating systems.
Nonquoted identifiers must begin with an alphabetic character (ANSWER B - begins with 9) from your database character set. Quoted identifiers can begin with any
character. Nonquoted identifiers can contain only alphanumeric characters from your database character set and the underscore (_), dollar sign ($), and pound sign (#).
Database links can also contain periods (.) and "at" signs (@). Oracle strongly discourages you from using $ and # in nonquoted identifiers.
Quoted identifiers can contain any characters and punctuations marks as well as spaces. However, neither quoted nor nonquoted identifiers can contain double
quotation marks or the null character (\0).
Within a namespace, no two objects can have the same name. Nonquoted identifiers are not case sensitive. Oracle interprets them as uppercase. Quoted identifiers are
case sensitive. By enclosing names in double quotation marks, you can give the following names to different objects in the same namespace:
employees
"employees"
"Employees"
"EMPLOYEES"
Note that Oracle interprets the following names the same, so they cannot be used for different objects in the same namespace:
employees
EMPLOYEES
"EMPLOYEES"
Columns in the same table or view cannot have the same name. However, columns in different tables or views can have the same name.
Procedures or functions contained in the same package can have the same name, if their arguments are not of the same number and datatypes. Creating multiple
procedures or functions with the same name in the same package with different arguments is called overloading the procedure or functio
Q126.
Creating a View
You can create a view by embedding a subquery in the CREATE VIEW statement.
In the syntax:
CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view
[(alias[, alias]...)]
AS subquery
[WITH CHECK OPTION [CONSTRAINT constraint]]
[WITH READ ONLY [CONSTRAINT constraint]];
OR REPLACE Re-creates the view if it already exists
FORCE Creates the view regardless of whether or not the base tables exist NOFORCE Creates the view only if the base tables exist (This is the default.) View Is the
name of the view alias Specifies names for the expressions selected by the view's query (The number of aliases must match the number of expressions selected by the
view.) subquery Is a complete SELECT statement (You can use aliases for the columns in the SELECT list.)
WITH CHECK OPTION Specifies that only those rows that are accessible to the view can be inserted or updated ANSWER D constraint Is the name assigned to the
CHECK OPTION constraint
WITH READ ONLY Ensures that no DML operations can be performed on this view Rules for Performing DML Operations on a View
You cannot add data through a view if the view includes:
Group functions
A GROUP BY clause
The DISTINCT keyword
The pseudocolumn ROWNUM keyword
Columns defined by expressions
NOT NULL columns in the base tables that are not selected by the view - ANSWER C
Q128.
The inner query returns a value to the outer query. If the inner query does not return a value, the outer query does not return a result
Q130.
The LPAD(string, length after padding, padding string) and RPAD(string, length after padding, padding string) functions add a padding string of characters to the left or
right of a string until it reaches the specified length after padding.
rpad函数从右边对字符串使用指定的字符进行填充
rpad(string,padded_length,[pad_string])
string 表示:被填充的字符串
padded_length 表示:字符的长度,是返回的字符串的数量,如果这个数量比原字符串的长度要短,rpad函数将会把字符串截取成从左到右的n个字符;
pad_string 是个可选参数,这个字符串是要粘贴到string的右边,如果这个参数未写,lpad函数将会在string的右边粘贴空格。
例如:
rpad('tech', 7); 将返回'tech '
rpad('tech', 2); 将返回'te'
rpad('tech', 8, '0'); 将返回'tech0000'
rpad('tech on the net', 15, 'z'); 将返回 'tech on the net'
rpad('tech on the net', 16, 'z'); 将返回 'tech on the netz'
SQL> select rpad('aa',5)||decode('bbb',null,' ',rpad('bbb',8))||rpad('cccc',12) from dual;
RPAD('AA',5)||DECODE('BBB',NUL
------------------------------
aa bbb cccc
Q135.
SQL 通配符
在搜索数据库中的数据时,SQL 通配符可以替代一个或多个字符。
SQL 通配符必须与 LIKE 运算符一起使用。
在 SQL 中,可使用以下通配符:
通配符
描述
%
替代一个或多个字符
_
仅替代一个字符
[charlist]
字符列中的任何单一字符
[^charlist]
或者
[!charlist]
不在字符列中的任何单一字符
SELECT * FROM Person.Contact WHERE LastName LIKE '_u' --选取名字的第一个字符之后是 "u" 的人Xu
SELECT * FROM Person.Contact WHERE LastName LIKE 'Ad%' --Ad开头
SELECT * FROM Person.Contact WHERE LastName LIKE '%[fk]%' --包含f或者k
SELECT * FROM Person.Contact WHERE LastName LIKE '[m-o]%' --以m,n,o开头
SELECT * FROM Person.Contact WHERE LastName LIKE 'a[^d]%' --以a开头,第二个字母不为d
例子 2
接下来,我们希望从 "Persons" 表中选取的这条记录的姓氏以 "C" 开头,然后是一个任意字符,然后是 "r",然后是任意字符,然后是 "er":
我们可以使用下面的 SELECT 语句:
SELECT * FROM Persons WHERE LastName LIKE 'C_r_er'
例子 3
现在,我们希望从上面的 "Persons" 表中选取居住的城市不以 "A" 或 "O" 或 "F" 开头的人:
我们可以使用下面的 SELECT 语句:
SELECT * FROM Persons
WHERE City LIKE '[!AOF]%'
Q136.
(88)You need to calculate the number of days from 1st January 2007 till date. Dates are stored in the default format of dd-mon-rr.
Which SQL statements would give the required output? (Choose two .)
A. SELECT SYSDATE - '01-JAN-2007' FROM DUAL;
B. SELECT SYSDATE - TO_DATE('01/JANUARY/2007') FROM DUAL;
C. SELECT SYSDATE - TO_DATE('01-JANUARY-2007') FROM DUAL;
D. SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY') - '01-JAN-2007' FROM DUAL;
E. SELECT TO_DATE(SYSDATE, 'DD/MONTH/YYYY') - '01/JANUARY/2007' FROM DUAL;
答案:(B、C)
解析:
--A(X),会隐式将'11-MAR-14'转换为数字,而不是日期。
scott@TESTDB11>select sysdate - '11-MAR-14' from dual;
select sysdate - '11-MAR-14' from dual
*
ERROR at line 1:
ORA-01722: invalid number
-- B, 与默认的日期格式一致(即使指定4位的年也可以)
scott@TESTDB11>select sysdate - to_date('11-MAR-14') from dual;
SYSDATE-TO_DATE('11-MAR-14')
----------------------------
-.76417824
-- C, 与默认的日期格式的区别只在分隔符上,也可以正确执行
scott@TESTDB11>select sysdate - to_date('11/MAR/14') from dual;
SYSDATE-TO_DATE('11/MAR/14')
----------------------------
-.76405093
Q137.
If the ORDER BY clause is not used, the sort order is undefined, and the Oracle server may not fetch rows in the same order for the same query twice. Use the ORDER
BY clause to display the rows in a specific order.
Note: Use the keywords NULLS FIRST or NULLS LAST to specify whether returned rows containing null values should appear first or last in the ordering sequence.
ANSWER C Sorting
The default sort order is ascending:
· Numeric values are displayed with the lowest values first (for example, 1 to 999). · Date values are displayed with the earliest value first (for example, 01-JAN-92 before
01-JAN-
95).
· Character values are displayed in the alphabetical order (for example, "A" first and "Z" last). · Null values are displayed last for ascending sequences and first for
descending sequences.
- ANSWER B
· You can also sort by a column that is not in the SELECT list.
Q138.
90. Examine thestructure and data in the PRICE_LIST table:
name Null Type
PROD_ID NOT NULLNUMBER(3)
PROD_PRICE VARCHAR2(10)
PROD_ID PROD_PRICE
100 $234.55
101 $6,509.75
102 $1,234
You plan to give adiscount of 25% on the product price and need to display the discount amount inthe
same format as thePROD_PRICE.
Which SQL statementwould give the required result?
A. SELECTTO_CHAR(prod_price* .25,'$99,999.99')
FROM PRICE_LIST;
B. SELECTTO_CHAR(TO_NUMBER(prod_price)* .25,'$99,999.00')
FROM PRICE_LIST;
C. SELECTTO_CHAR(TO_NUMBER(prod_price,'$99,999.99')* .25,'$99,999.00')
FROM PRICE_LIST;
D. SELECTTO_NUMBER(TO_NUMBER(prod_price,'$99,999.99')* .25,'$99,999.00')
FROM PRICE_LIST;
Answer:C
解析:
需要先将价格转换为数字再进行运算
TO_NUMBER(prod_price,'$99,999.99')* .25 将符合特定格式的字符串转换为数值
当然运算完成,再转换为价格的格式
TO_CHAR(TO_NUMBER(prod_price,'$99,999.99')*.25,'$99,999.00')
更多格式说明:
http://blog.csdn.net/zbdba/article/details/17042195
Q140.
The COALESCE Function
The COALESCE function returns the first nonnull value from its parameter list. If all its parameters are null, then null is returned.
The COALESCE function takes two mandatory parameters and any number of optional parameters. The syntax is COALESCE(expr1, expr2,...,exprn), where expr1 is
returned if it is not null, else expr2 if it is not null, and so on. COALESCE is a general form of the NVL function, as the following two equations illustrate:
COALESCE(expr1,expr2) = NVL(expr1,expr2)
COALESCE(expr1,expr2,expr3) = NVL(expr1,NVL(expr2,expr3)) The data type COALESCE returns if a not null value is found is the same as that of the first not null
parameter.
To avoid an "ORA-00932: inconsistent data types" error, all not null parameters must have data types compatible with the first not null parameter.
Oracle COALESCE函数
Oracle COALESCE函数语法为COALESCE(表达式1,表达式2,...,表达式n),n>=2,此表达式的功能为返回第一个不为空的表达式,如果都为空则返回空值。
注意:所有表达式必须为同一类型或者能转换成同一类型。 www.2cto.com
示例一:在emp表中给comm列为空的人员设为200
[sql] www.2cto.com
SQL> select a.empno,a.ename,comm,coalesce(comm,200)new_comm from emp a;
EMPNO ENAME COMM NEW_COMM
---------- -------------------- ---------- ----------
7369 SMITH 200
7499 ALLEN 300 300
7521 WARD 500 500
7566 JONES 200
7654 MARTIN 1400 1400
7698 BLAKE 200
7782 CLARK 200
7788 SCOTT 200
7839 KING 200
7844 TURNER 0 0
7876 ADAMS 200
EMPNO ENAME COMM NEW_COMM
---------- -------------------- ---------- ----------
7900 JAMES 200
7902 FORD 200
7934 MILLER 200
8888 xiangyc 888.88 888.88
已选择15行。
示例2:模拟返回第一个不为空的值
[sql]
SQL> select coalesce(null,3+5,4+6) value from dual;
VALUE
----------
8
示例3:模拟数据类型不一致的情况
[sql]
SQL> select COALESCE (null,333,444,'555') from dual;
select COALESCE (null,333,444,'555') from dual
*
第 1 行出现错误:
ORA-00932: 数据类型不一致: 应为 NUMBER, 但却获得 CHAR
Q141.
How Are Indexes Created?
You can create two types of indexes.
Unique index: The Oracle server automatically creates this index when you define a column in a table to have a PRIMARY KEY or a UNIQUE constraint. The name of the
index is the name that is given to the constraint.
Nonunique index: This is an index that a user can create. For example, you can create the FOREIGN KEY column index for a join in a query to improve the speed of
retrieval. Note: You can manually create a unique index, but it is recommended that you create a unique constraint, which implicitly creates a unique index.
Q143.
一、原题
You need to display the date 11-oct-2007 in words as 'Eleventh of October, Two Thousand Seven'.
Which SQL statement would give the required result?
A. SELECT TO_CHAR('11-oct-2007', 'fmDdspth "of" Month, Year')
FROM DUAL;
B. SELECT TO_CHAR(TO_DATE('11-oct-2007'), 'fmDdspth of month, year')
FROM DUAL;
C. SELECT TO_CHAR(TO_DATE('11-oct-2007'), 'fmDdthsp "of" Month, Year')
FROM DUAL;
D. SELECT TO_DATE(TO_CHAR('11-oct-2007','fmDdspth ''of'' Month, Year'))
FROM DUAL;
答案:C
二、题目翻译
需要把11-oct-2007显示为Eleventh of October, Two Thousand Seven
下面哪个SQL能得出所需的结果?
三、题目解析
A选项不正确,'11-oct-2007'本来就是个字符串,还用to_char转换就不对了。
B选项不正确,日期格式不对,如果不属于转换日期格式标识符需要使用双引号,如"of"
C选项正确。
D选项不正确,语法不对,和A类似,本来就是字符串,还转。
日期格式的详细用法,详见:
http://blog.csdn.net/holly2008/article/details/25213993
Q144.
What would be the outcome if all the parentheses(括号) areremoved from the above statement?如果所有的括号从上面的语句中删除,会有什么的结果?
B The result remains unchanged.
Q146.
注意:从Oralce 10g开始,可以使用q’<>/[]/{}’,引号中用特殊字符括起来即可。
So, how are words that contain single quotation marks dealt with? There are essentially two mechanisms available. The most popular of these is to add an additional
single quotation mark next to each naturally occurring single quotation mark in the character string Oracle offers a neat way to deal with this type of character literal in the
form of the alternative quote (q) operator. Notice that the problem is that Oracle chose the single quote characters as the special pair of symbols that enclose or wrap any
other character literal. These character-enclosing symbols could have been anything other than single quotation marks. Bearing this in mind, consider the alternative
quote (q) operator. The q operator enables you to choose from a set of possible pairs of wrapping symbols for character literals as alternatives to the single quote
symbols. The options are any single-byte or multibyte character or the four brackets:
(round brackets), {curly braces}, [squarebrackets], or . Using the q operator, the character delimiter can effectively be changed from a single quotation
mark to any other character
The syntax of the alternative quote operator is as follows:
q'delimiter'character literal which may include the single quotes delimiter' where delimiter can be any character or bracket.
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: ]'
|| manager_id
AS "Department and Manager"
FROM departments;
Alternative Quote (q) Operator
Many SQL statements use character literals in expressions or conditions. If the literal itself contains a single quotation mark, you can use the quote (q) operator and
select your own quotation mark delimiter.
You can choose any convenient delimiter, single-byte or multibyte, or any of the following character pairs: [ ], { }, ( ), or < >.
In the example shown, the string contains a single quotation mark, which is normally interpreted as a delimiter of a character string. By using the q operator, however,
brackets [] are used as the quotation mark delimiters. The string between the brackets delimiters is interpreted as a literal character string.
Q148.
CHECK Constraint
The CHECK constraint defines a condition that each row must satisfy. The condition can use the same constructs as the query conditions, with the following exceptions:
References to the CURRVAL, NEXTVAL, LEVEL, and ROWNUM pseudocolumns Calls to SYSDATE, UID, USER, and USERENV functions
Queries that refer to other values in other rows
A single column can have multiple CHECK constraints that refer to the column in its definition. There is no limit to the number of CHECK constraints that you can define
on a column. CHECK constraints can be defined at the column level or table level.
CREATE TABLE employees
(...
salary NUMBER(8,2) CONSTRAINT emp_salary_min
CHECK (salary > 0),
Q151.
C. It produces an error because COUNT(*) should be only in the HAVING clause and not in the WHERE clause.
Restricting Group Results with the HAVING Clause
You use the HAVING clause to specify the groups that are to be displayed, thus further restricting the groups on the basis of aggregate information.
In the syntax, group_condition restricts the groups of rows returned to those groups for which the specified condition is true.
The Oracle server performs the following steps when you use the HAVING clause:
1. Rows are grouped.
2. The group function is applied to the group.
3. The groups that match the criteria in the HAVING clause are displayed. The HAVING clause can precede the GROUP BY clause, but it is recommended that you place
the GROUP BY clause first because it is more logical. Groups are formed and group functions are calculated before the HAVING clause is applied to the groups in the
SELECT list. Note: The WHERE clause restricts rows, whereas the HAVING clause restricts groups.
Q152.
A,CLOB不能指定精度
B,表名得以字母开头
C,emp_status列默认值应该为’ACTIVE’,不应该用双引号
Q153.
A naturally occurring underscore character may be escaped (or treated as a regular nonspecial symbol) using the ESCAPE identifier in conjunction with an ESCAPE
character. The second example in Figure 3-12 shows the SQL statement that retrieves the JOBS table records with JOB_ID values equal to SA_MAN and SA_REP and
which conforms to the original requirement:
select job_id from jobs
where job_id like 'SA\_%' escape '\';
发布时间:2012-09-19 00:00:00 来源:比特网 作者:悠虎
关键字:Oracle
定义:escape关键字经常用于使某些特殊字符,如通配符:'%','_'转义为它们原来的字符的意义,被定义的转义字符通常使用'\',但是也可以使用其他的符号。
实例:
SQL> select * from t11 where name like '%_%';
NAME
---------
aa_a
aaa
SQL> select * from t11 where name like '%\_%' escape '\';
NAME
----------
aa_a
注意:如果是 '/' 作为检索字符, 必须 用 '/' 作为转义符, 正斜扛也一样。
select * from wan_test where psid like '%//%' escape '/'
1.使用 ESCAPE 关键字定义转义符。在模式中,当转义符置于通配符之前时,该通配符就解释为普通字符。
2.ESCAPE 'escape_character' 允许在字符串中搜索通配符而不是将其作为通配符使用。escape_character 是放在通配符前表示此特殊用途的字符。
select * from a WHERE name LIKE '%/%ab' ESCAPE '/'
结果为:
name
----------
11%ab
12%ab
==================================================================================
SQL> select * from test;
TEST
--------------------
sdd_kk
d'd
dfsfsa
dffa%asfs
12345
1%2345
1%54321
2%54321
%%54321
A&B
已选择9行。
其中包含特殊的字符分别为%,_,&,有可能包含这些字符的数据含有错误,或者需要查找包含这些字符的数据。
SQL> select * from test where test like 'sdd _%' escape ' ';
TEST
--------------------
sdd_kk
转义字符为' '(空格);
SQL> select * from test where test like 'sdd\_%' escape '\';
TEST
--------------------
sdd_kk
转义字符为'\';
SQL> select * from test where test like 'sdd=_%' escape '=';
TEST
--------------------
sdd_kk
转义字符为'=';
SQL> select * from test where test like 'sdd/_%' escape '/';
TEST
--------------------
sdd_kk 转义字符为'/';
SQL> select * from test where test like 'sddd_%' escape 'd';
未选定行
转义字符为d,没有实现转义功能;
SQL> select * from test where test like '%\_%' escape '\';
TEST
--------------------
sdd_kk
查找包含所有'_'的字段。
同理:通过这种方法查找含有'%'的所有字段:
SQL> select * from test where test like '%\%%' escape '\';
TEST
--------------------
dffa%asfs
1%2345
1%54321
2%54321
%%54321
但是'&'不能通过转义字符查找:
SQL> select * from test where test like '%\&%' escape'\';
select * from test where test like '%\&%' escape'\'
*
第 1 行出现错误:
ORA-01424: 转义符之后字符缺失或非法
可以通过另外的方式进行转义:
SQL> select ascii('&') from dual;
ASCII('&')
----------
38
SQL> select * from test where test like '%'||chr(38)||'%';
TEST
--------------------
A&B
'''的转义:
SQL> select * from test where test like '%''%';
TEST
--------------------
d'd
特殊符号的数据的插入
SQL> insert into test values('test&test');
输入 test 的值: test
原值 1: insert into test values('test&test')
新值 1: insert into test values('testtest') -虽然插入,但是数据不对。
已创建 1 行。
SQL> show define
define "&" (hex 26)
SQL> set define off
SQL> show define
define OFF
SQL> insert into test values('test&test');
已创建 1 行。
SQL> show escape
escape OFF
SQL> set escape on
SQL> show escape
escape "\" (hex 5c)
SQL> insert into test values('test\&test');
已创建 1 行。
SQL> select * from test;
TEST
--------------------
sdd_kk
d'd
dfsfsa
dffa%asfs
12345
1%2345
1%54321
2%54321
%%54321
A&B
testtest
test&test
test&test
已选择13行。
SQL> commit;
提交完成。
SQL> select * from test;
TEST
--------------------
sdd_kk
d'd
dfsfsa
dffa%asfs
12345
1%2345
1%54321
2%54321
%%54321
A&B
testtest
test&test
test&test
已选择13行。
SQL> insert into test values('test\%test');
已创建 1 行。
SQL> insert into test values('test\_test');
已创建 1 行。
SQL> insert into test values('test\'test);
insert into test values('test'test)
*
第 1 行出现错误:
ORA-00917: 缺失逗号
SQL> insert into test values('test''test');
已创建 1 行。
SQL> select * from test;
TEST
--------------------
sdd_kk
d'd
dfsfsa
dffa%asfs
12345
1%2345
1%54321
2%54321
%%54321
A&B
testtest
test&test
test&test
test%test
test_test
test'test
已选择16行。
连接符‘||’导致了新一轮的转义:连接符号‘||’左右的单引号没有任何的关系,除非‘||’是作为字符串的一部分(这在动态SQL中很常见)。
SQL> SELECT 'ORACLE'||'''' FROM DUAL;
'ORACLE'||''
----------
ORACLE'
个人理解,'ORACLE'||'''' 后面的“''''”应该认为是一个字符串(即前后单引号,中间是“''”串,而中间又是密集单引号,因此第一个为转义功能)
SQL> SELECT 'ORACLE''''' FROM DUAL;
'ORACLE'''''
------------
ORACLE''
对于第一个,前两个单引号配对,后面四个单引号按照上面的第一条原则分配,既:SELECT 'ORACLE'||'''' FROM DUAL;
对于第二个,由于第二个单引号后面存在单引号,所以就不与第一个配对,而是充当了转义的角色。既:SELECT 'ORACLE''''' FROM DUAL;
Q156.
NATURAL JOIN operation
A NATURAL JOIN is a JOIN operation that creates an implicit join clause for you based on the common columns in the two tables being joined. Common columns are
columns that have the same name in both tables.
If the SELECT statement in which the NATURAL JOIN operation appears has an asterisk (*) in the select list, the asterisk will be expanded to the following list of columns
(in this order):
All the common columns
Every column in the first (left) table that is not a common column Every column in the second (right) table that is not a common column An asterisk qualified by a table
name (for example, COUNTRIES.*) will be expanded to every column of that table that is not a common column.
If a common column is referenced without being qualified by a table name, the column reference points to the column in the first (left) table if the join is an INNER JOIN
or a LEFT OUTER JOIN. If it is a RIGHT OUTER JOIN, unqualified references to a common column point to the column in the second (right) table.
Syntax
TableExpression NATURAL [ { LEFT | RIGHT } [ OUTER ] | INNER ] JOIN { TableViewOrFunctionExpression |
( TableExpression ) }
Examples
If the tables COUNTRIES and CITIES have two common columns named COUNTRY and COUNTRY_ISO_CODE, the following two SELECT statements are
equivalent:
SELECT * FROM COUNTRIES NATURAL JOIN CITIES
SELECT * FROM COUNTRIES JOIN CITIES
USING (COUNTRY, COUNTRY_ISO_CODE)
Q157.
The NOT NULL constraint can be defined only at the column level. It enforces that a value must be defined for this column such that the column may not be NULL for any
row.
Incorrect Answers
A:The UNIQUE constraint enforces uniqueness on values in the constrained column. It can be defined not only at the column level.
C:The CHECK constraint enforces that values added to the constrained column must be present in a static list of values permitted for the column.
D:The PRIMARY KEY constraint stipulates that values in the constrained column(s) must be unique and not NULL. If the primary key applies to multiple columns, then
the combination of values in the columns must be unique and not NULL.
E:The FOREIGN KEY constraint enforces that only values in the primary key of a parent table may be included as values in the constrained column(s) of the child table
Q158.
The GRANT command with the WITH GRANT OPTION clause allows the grantee to grant object privileges to other users and roles.
Incorrect Answers
A:The WITH GRANT OPTION does not allow a grantee DBA privileges.
B:It is not required syntax for object privileges. It is optional clause of GRANT command.
C:GRANT command does not allows privileges on columns of tables.
D:It is not used to grant an object privilege on a foreign key column
Q159.
To reuse the variable without prompting the user each time you can use && substitution variable.
Incorrect Answers
A:This substitution variable will prompt the user each time.
B:ACCEPT is command, not substitution variable. It used to define more accurate or specific prompt or when you want more output to display as the values are defined.
C:PROMPT is part of the ACCEPT command, it is not a variable.
Q160.
A change to the DEFAULT value affects only subsequent(后来的) insertions to the table. Existing rows will not be affected.
Incorrect Answers
A:Column definitions can be altered to add DEFAULT values.
C:Column definitions can be altered to add DEFAULT values. It works for columns with a NUMBER data type also.
D:A change to the DEFAULT value affects only subsequent insertions to the table. Existing rows will not be affected
Q162.
D: GRANT is a DML operation which will cause an implicit commit
E: It is important to understand that an implicit COMMIT occurs on the database when a user exits SQL*Plus or issues a data-definition language (DDL) command such
as a CREATE TABLE statement, used to create a database object, or an ALTER TABLE statement, used to alter a database object.
Incorrect Answers
A:The DELETE command is data-manipulation language (DML) command and it does not complete a transaction.
B:The DESCRIBE command is internal SQL*Plus command and it has nothing to do with completion a transaction.
C: ROLLBACK is not used to commit or complete a transaction, it is used to undo a transaction
F:SELECT command is used to retrieve data. It does not complete a transaction.
Q163.
This answer provides correct list of columns for the output.
Incorrect Answers
A:This answer does not provide correct list of columns for the output. It is not required to show all columns of the table. Symbol "*" is used in the SELECT command to
substitute a list of all columns of the table.
B:This answer does not provide correct list of columns for the output. There are not NAME and ADDRESS columns in the CUSTOMERS table.
C:This answer does not provide correct list of columns for the output. There are not ID, NAME, ADDRESS or PHONE columns in the CUSTOMERS table.
E:This answer does not provide correct list of columns for the output. It is not required to show all columns of the table.
Q164.
The ROWID datatype stores information related to the disk location of table rows. They also uniquely identify the rows in your table. The ROWID datatype is stored as a
hexadecimal string.
Incorrect Answers
A:It is not a binary data. The ROWID datatype is a hexadecimal string.
B:It is not a character data. The ROWID datatype is a hexadecimal string.
C:It is not a raw binary data. The ROWID datatype is a hexadecimal string.
D:It is not binary data stored in an external file. The ROWID datatype is a hexadecimal string.
Q165.
You cannot roll back DROP TABLE statement. All pending transactions related on this table are committed. If the table is dropped, Oracle automatically drops any index,
trigger and constraint associated with the table as well. All data in the table is deleted, and the table structure is also deleted.
Incorrect Answers
C:All views based on the DEPT table become invalid, but they are not deleted.
F:All data in the table is deleted, and the table structure is also deleted. Command TRUNCATE deletes all data in the table, but does not delete the structure of the table.
G:All synonyms based on the DEPT table are not deleted after dropping the table.
Q166.
You can create a view in your own schema only if you are granted the CREATE VIEW privilege.
Incorrect Answers
A:You can create a view in your own schema only.
B:You can create a view in your own schema only, not in any schema.
D:There is no sequence view in Oracle.
E:You cannot create a view that is accessible by everyone. You will need specially grant SELECT privileges on this view for everyone.
F:You can create a view in your own schema, but not only for tables in your schema. You can use object from other users schemas if you have privileges to retrieve data
from them.
Q167.
Constraints can be created after the table is created. Use ALTER TABLE command for that. Constraints can be created at the same time the table is created (CREATE
TABLE command).
Incorrect Answers
A:There is no requirements in Oracle that constraint names must start with SYS_C. Oracle can use prefix "SYS" to build indexes for UNIQUE and NOT NULL constraints,
but it is not required for user to follow this naming rule.
B:Not all constraints must be defines at the column level. Only NOT NULL constraint must be.
E:There is no VIEW_CONSTRAINTS dictionary view in Oracle.
Q168.
B: WHERE clause cannot be use to restrict groups(约束组)
WHERE clause cannot be use when there is group functions.
D: A HAVING clause can only e used to restrict GROUPS.
Note: HAVING clause to specify which groups are to be displayed and thus further restrict the groups on the basis of aggregate information. The Oracle server performs the following steps when you use the Having clause
1. rows are grouped
2. the group function is applied to the group
3. the group that match the criteria(条件) in the Having clause are displayed.
Incorrect Answers :
A. Where clause cannot be use to restrict groups
C. A HAVING clause can only e used to restrict GROUPS.
E. WHERE clause cannot be use when there is group function, instead HAVING is to be use.
F. There is no constraint to use HAVING clause in a sub queries.
Q169.
'=' is use in the statement and sub query will return more than one row. Employees table has 2 row matching the employee name Smith.
The update statement will fail.
Incorrect Answers :
A. The Update statement will fail no update was done. B. The update statement will fail no update was done. C. The update statement will fail no update was done. E. The
update statement will fail but not due to job_it='IT_ADMIN' F. The update statement will fail but not due to department_id='Administration'
Q170.
In a WHERE clause, date and characters values must be enclosed within single quotation marks.
Sample of the correct syntax
SELECT EMPLOYEE_ID, &COLUMN_NAME
FROM EMPLOYEES
Incorrect Answers :
A. Incorrect use of " symbol
B. Incorrect use of ' symbol
D. No input for table name as EMP has been use in the statement
SQL> SELECT &1,&2 FROM &3 WHERE LAST_NAME='&4';
输入 1 的值: 1
输入 2 的值: 2
输入 3 的值: 3
输入 4 的值: 4
原值 1: SELECT &1,&2 FROM &3 WHERE LAST_NAME='&4'
新值 1: SELECT 1,2 FROM 3 WHERE LAST_NAME='4'
SELECT 1,2 FROM 3 WHERE LAST_NAME='4'
*
Q171.
ROUND (45.953,-1) will round value to 1 decimal places to the left.
TRUNC (45.936,2) will truncate value to 2 decimal
The answer will be 50 and 45.93
Incorrect Answers :
A. Does not meet round and truncate functions
B. Does not meet round functions
D. Does not meet truncate functions
E. Does not meet round functions
F. Does not meet round functions
Q172.
You need to determine how dispersed your customer base is.
You need to determine how dispersed your customer base is.
全部释义和例句>> 你需要确定如何分散你的客户群
E. COUNT(DISTINCT (UPPER(country_address)))
Q173.
The correct syntax for DELETE statement
DELETE [ FROM ] table
[ WHERE condition ];
Incorrect Answers :
A. '=' is use in the statement and sub query will return more than one row.
Error Ora-01427: single-row sub query returns more than one row.
B. Incorrect DELETE statement
D. Incorrect DELETE statemen
Q175.
You can remove existing rows from a table by using the DELETE statement.
DELETE [FROM] table
[WHEREcondition];
Incorrect answer:
AStatement will not cause error
BDelete statement will not delete the table structure DStatement will not cause error
Q176.
The correct statement for MERGE is
MERGE INTO table_name
Incorrect answer:
BWrong statement with the keyword EXISTS
CWrong statement with the keyword EXISTS
DWrong statement on the MERGE new_employee
通过这个merge你能够在一个SQL语句中对一个表同时执行inserts和updates操作. 当然是update还是insert是依据于你的指定的条件判断的,Merge into可以实现用B表来更新A表数据,如果A表中没有,则把B表的数据插入A表. MERGE命令从一个或多个数据源中选择行来updating或inserting到一个或多个表
语法如下
MERGE INTO [your table-name] [rename your table here]
USING ( [write your query here] )[rename your query-sql and using just like a table]
ON ([conditional expression here] AND [...]...)
WHEN MATHED THEN [here you can execute some update sql or something else ]
WHEN NOT MATHED THEN [execute something else here ! ]
Q177.
Oracle的substr函数简单用法
substr(字符串,截取开始位置,截取长度) //返回截取的字
substr('Hello World',0,1) //返回结果为 'H' *从字符串第一个字符开始截取长度为1的字符串
substr('Hello World',1,1) //返回结果为 'H' *0和1都是表示截取的开始位置为第一个字符
substr('Hello World',2,4) //返回结果为 'ello'
substr('Hello World',-3,3)//返回结果为 'rld' *负数(-i)表示截取的开始位置为字符串右端向左数第i个字符
测试:
select substr('Hello World',-3,3) value from dual;
Q178.
Oracle constraint type is Not Null, Check, Primary Key, Foreign Key and Unique
Q182.
The correct statement for Top-N Analysis
SELECT [coloumn_list], ROWNUM
FROM (SELECT [coloumn_list]
FROM table
ORDER BY Top-N_coloumn)
WHERE ROWNUM <= N;
Q183.
ALTER TABLE customers MODIFY customer_name CONSTRAINT cust_name_nn NOT NULL;
修改约束
Q85.
this is the correct solution for the answer.
GRANT role_name to users;
Q186.
ALTER TABLE table_name
ADD [CONSTRAINT constraint] type (coloumn)
Q189.
manipulate data items, act on each row returned, return one result per row, and accept arguments that can be a column or expression.
Incorrect answer:
Ais not single row attributes
Efunctions can accept more than one argument, e.g NVL2
Q191.
EMPLOYEE_ID is a primary key.
Incorrect answer:
AEMPLOYEE_ID cannot be null
BEMPLOYEE_ID cannot be null
Dmismatch of field_name with datatype
Q192.
use the REVOKE statement to revoke privileges granted to other users. Privilege granted to others through the WITH GRANT OPTION clause are also revoked.
Alice, Reena and Timber will be revoke.
Incorrect answer:
Athe correct answer should be Alice, Reena and Timber Bthe correct answer should be Alice, Reena and Timber
Q193.
A. SELECT employee_id, last_name, job_id FROM employees WHERE job_id LIKE '%SA\_' ESCAPE '\';
Q194.
SELECT 'Dear Customer ' || customer_name || ',' FROM customers;
Q195.
A. Once created, a sequence belongs to a specific schema.
Q196.
D. Object privilege on VIEW is DELETE, INSERT, REFERENCES, SELECT and UPDATE.
Q198.
A. Group functions on columns ignore NULL values.
Q199.
C. SELECT MAX(gpa) FROM student_grades WHERE gpa IS NOT NULL GROUP BY semester_end;
Q201.
use the double-ampersand if you want to reuse the variable value without prompting the user each time.
Q202.
DATE value subtract DATE value will return numeric value.
C. SELECT sysdate-hire_date
FROM EMP;
Q203.
Create a synonyms when the names of the tables are too long or the table names are difficult.
Q204.
A. You cannot update a view with group functions
Q205.
onenote截图
Q206.
B. WHERE lower(country_address) = 'france'
Q209.
. What does the FORCE option for creating a view do?
D. creates a view regardless of whether or not the base tables exist
Q211.
D. **17000.00
SELECT LPAD (salary,10,'*')
FROM EMP
WHERE EMP_ID = 1001
lpad用法
lpad(字段名,填充长度,填充的字符) 左侧加空格
Q213.
GRANT ROLE to ROLE/USER
Q214.
Which best describes an inline view
D. a sub query that is part of the FROM clause of another query
Q215.
Equijoins are also called simple joins or inner joins. Equijoin involve primary key and foreign key.
D. SELECT e.last_name, d.department_name, d.location_id FROM employees e, departments D
WHERE e.department_id =d.department_id;
Q217.
. In which two cases would you use an outer join? (Choose two.)
C. The columns being joined have NULL values.
E. The tables being joined have both matched and unmatched data.
Q218.
the NOT NULL constraint can be specified only at the column level, not at the table leve
Q220.
C. Only the first query executes successfully and gives the correct result.
Answer: C
The MONTHS_BETWEEN(date 1, date 2) function returns the number of months between two dates:
months_between('01-FEB-2008','01-JAN-2008') = 1
The DECODE Function
Although its name sounds mysterious, this function is straightforward. The DECODE function implements if then-else conditional logic by testing its first two terms for
equality and returns the third if they are equal and optionally returns another term if they are not. DECODE Function Facilitates conditional inquiries by doing the work of
a CASE expression or an IF-THENELSE statement:
DECODE(col|expression, search1, result1
[, search2, result2,...,]
[, default])
DECODE Function
The DECODE function decodes an expression in a way similar to the IF-THEN-ELSE logic that is used in various languages. The DECODE function decodes expression
after comparing it to each search value. If the expression is the same as search, result is returned. If the default value is omitted, a null value is returned where a search
value does not match any of the result values.
Q221.
A. listing of customers who do not have a credit limit and were born before 1980
B. finding the number of customers, in each city, whose marital status is 'married'
C. finding the average credit limit of male customers residing in 'Tokyo' or 'Sydney'
D. listing of those customers whose credit limit is the same as the credit limit of customers residing in the city 'Tokyo'
E. finding the number of customers, in each city, whose credit limit is more than the average credit limit of all the customers
Answer: D,E
Describe the Types of Problems That the Subqueries Can Solve There are many situations where you will need the result of one query as the input for another.
Use of a Subquery Result Set for Comparison Purposes Which employees have a salary that is less than the average salary? This could be answered by two statements,
or by a single statement with a subquery. The following example uses two statements:
select avg(salary) from employees;
select last_name from employees where salary < result_of_previous_query ; Alternatively, this example uses one statement with a subquery:
select last_name from employees where salary < (select avg(salary)from employees); In this example, the subquery is used to substitute a value into the WHERE clause
of the parent query: it is returning a single value, used for comparison with the rows retrieved by the parent query.
The subquery could return a set of rows. For example, you could use the following to find all departments that do actually have one or more employees assigned to them:
select department_name from departments where department_id in (select distinct(department_id) from employees);
Q223.
C. SELECT cust_last_name AS "Name", cust_credit_limit + 1000 AS "New Credit Limit" FROM customers;
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.(空格,特殊字符,区分大小写双引号)
Q224.
ROUND(column|expression, n) Rounds the column, expression, or value to n decimal places or, if n is omitted, no decimal places (If n is negative, numbers to the left of
decimal point are rounded.
Q226.
Datetime Data Types
You can use several datetime data types:
INTERVAL YEAR TO MONTH
Stored as an interval of years and months
INTERVAL DAY TO SECOND
Stored as an interval of days, hours, minutes, and seconds
由于MONTH 默认是2为有效位数,所以不能是300,就表示成YEAR TO MONTH 于是成了+25-00
第二个不够2位补0,第三个最后一位默认6位,收上来就是123457了 Oracle语法:
INTERVAL 'integer [- integer]' {YEAR | MONTH} [(precision)][TO {YEAR | MONTH}]
该数据类型常用来表示一段时间差, 注意时间差只精确到年和月. precision为年或月的精确域, 有效范围是0到9, 默认值为2
Q227.
VARCHAR2(size)Variable-length character data (A maximum size must be specified: minimum size is 1; maximum size is 4,000.)
CHAR [(size)] Fixed-length character data of length size bytes (Default and minimum size is 1; maximum size is 2,000.)
NUMBER [(p,s)] Number having precision p and scale s (Precision is the total number of decimal digits and scale is the number of digits to the right of the decimal point;
precision can range from 1 to 38, and scale can range from -84 to 127.)
DATE Date and time values to the nearest second between January 1, 4712 B.C., and December 31, 9999 A.D
B. The TRANS_VALIDITY column would give an error.
C. The CUST_STATUS column would store exactly one character
Q228.
: The NUMBER datatype stores fixed and floating-point numbers. Numbers of virtually any magnitude can be stored and are guaranteed portable among different
systems operating Oracle, up to 38 digits of precision.
The following numbers can be stored in a NUMBER column:
Positive numbers in the range 1 x 10-130 to 9.99...9 x 10125 with up to 38 significant digits Negative numbers from -1 x 10-130 to 9.99...99 x 10125 with up to 38
significant digits Zero
Positive and negative infinity (generated only by importing from an Oracle Version 5 database)
D: The VARCHAR2 datatype stores variable-length character strings. When you create a table with a VARCHAR2 column, you specify a maximum string length (in bytes
or characters) between 1 and 4000 bytes for the VARCHAR2 column.
An interval (间隔)literal(字符) specifies a period of time, and Oracle supports two types of interval literals:
YEAR_TO_MONTH and DAY TO SECOND. For DAY TO SECOND, you can specify these differences in terms in terms of days, hours, minutes, and seconds. DAY TO SECOND contains a leading field and may contain an optional trailing field. If trailing field is specified it must be less significant than the leading field. For example,
INTERVAL MINUTE TO DAY is not valid.
A DAY TO MINUTE interval considers an interval of days to the nearest minute
Q229.
Synonyms
Synonyms are database objects that enable you to call a table by another name. You can create synonyms to give an alternative name to a table.
Q230.
Including Constraints
· Constraints enforce rules at the table level.
· Constraints prevent the deletion of a table if there are dependencies.
· The following constraint types are valid:
- NOT NULL
- UNIQUE
- PRIMARY KEY
- FOREIGN KEY
- CHECK
Q233.
Defining Constraints
The slide gives the syntax for defining constraints when creating a table. You can create constraints at either the column level or table level. Constraints defined at the
column level are included when the column is defined. Table-level constraints are defined at the end of the table definition and must refer to the column or columns on which the constraint pertains(从属) in a set of parentheses(圆括号). It is mainly the syntax that differentiates the two; otherwise, functionally, a columnlevel constraint is the same as a table-level constraint. NOT NULL constraints must be defined at the column level. Constraints that apply to more than one column must be defined at the table level
Q236.
But why the answer is not "C" ?
Because you didn't specify the MINVALUE for the sequence. If you check the sequence definition that you created it will have the default value of 1, which it reverts to
when cycling. If you wanted to keep the minimum value you would need to specify it in the sequence creation.
sequence Is the name of the sequence generator
INCREMENT BY n Specifies the interval between sequence numbers, where n is an integer (If this clause is omitted, the sequence increments by 1.)
START WITH n Specifies the first sequence number to be generated (If this clause is omitted, the sequence starts with 1.)
MAXVALUE n Specifies the maximum value the sequence can generate NOMAXVALUE Specifies a maximum value of 10^27 for an ascending sequence and -1 for a
descending sequence (This is the default option.)
MINVALUE n Specifies the minimum sequence value
NOMINVALUE Specifies a minimum value of 1 for an ascending sequence and -(10^26) for a
descending sequence (This is the default option.)
CYCLE | NOCYCLE Specifies whether the sequence continues to generate values after reaching its maximum or minimum value
(NOCYCLE is the default option.)
CACHE n | NOCACHE Specifies how many values the Oracle server preallocates and keeps in memory (By default, the Oracle server caches 20 values.)
Q239.
A synonym is an alias for a table (or a view). Users can execute SQL statements against the
synonym, and the database will map them into statements against the object to which the synonym points.
Private synonyms are schema objects. Either they must be in your own schema, or they must be qualified with the schema name. Public synonyms exist independently
of a schema. A public synonym can be referred to by any user to whom permission has been granted to see it without the need to qualify it with a schema name.
Private synonyms must be a unique name within their schema. Public synonyms can have the same name as schema objects. When executing statements that address
objects without a schema qualifier, Oracle will first look for the object in the local schema, and only if it cannot be found will it look for a public synonym
Q242.
Using the ORDER BY Clause
The order of rows that are returned in a query result is undefined. The ORDER BY clause can be used to sort the rows. However, if you use the ORDER BY clause, it
must be the last clause of the SQL statement. Further, you can specify an expression, an alias, or a column position as the sort condition.
Syntax
SELECT expr
FROM table
[WHERE condition(s)]
[ORDER BY {column, expr, numeric_position} [ASC|DESC]]; In the syntax:
ORDER BY specifies the order in which the retrieved rows are displayed ASC orders the rows in ascending order (This is the default order.)
DESC orders the rows in descending order
If the ORDER BY clause is not used, the sort order is undefined, and the Oracle server may not fetch rows in the same order for the same query twice. Use the ORDER
BY clause to display the rows in a specific order.
Note: Use the keywords NULLS FIRST or NULLS LAST to specify whether returned rows containing null values should appear first or last in the ordering sequence.
Q243.
You cannot use column alias in the WHERE clause.
Q244.
A. finding the remainder of a division
C. comparing two expressions to check whether they are equal
D. checking whether a specified character exists in a given string
Q245.
ROUND: Rounds value to a specified decimal
TRUNC: Truncates value to a specified decimal
MOD: Returns remainder of division
SYSDATE is a date function that returns the current database server date and time.
Date-Manipulation Functions
Date functions operate on Oracle dates. All date functions return a value of the DATE data type except MONTHS_BETWEEN, which returns a numeric value.
MONTHS_BETWEEN(date1, date2): Finds the number of months between date1 and date2. The result can be positive or negative. If date1 is later than date2, the result
is positive; if date1 is earlier than date2, the result is negative. The noninteger part of the result represents a portion of the month.
ADD_MONTHS(date, n): Adds n number of calendar months to date. The value of n must be an integer and can be negative.
NEXT_DAY(date, 'char'): Finds the date of the next specified day of the week ('char') following date. The value of char may be a number representing a day or a
character string. LAST_DAY(date): Finds the date of the last day of the month that contains date The above list is a subset of the available date functions. ROUND and
TRUNC number functions can also be used to manipulate the date values as shown below:
ROUND(date[,'fmt']): Returns date rounded to the unit that is specified by the format model fmt. If the format model fmt is omitted, date is rounded to the nearest day.
TRUNC(date[, 'fmt']): Returns date with the time portion of the day truncated to the unit that is specified by the format model fmt. If the format model fmt is omitted, date
is truncated to the nearest day.
The CONCAT Function
The CONCAT function joins two character literals, columns, or expressions to yield one larger character expression. Numeric and date literals are implicitly cast as
characters when they occur as parameters to the CONCAT function. Numeric or date expressions are evaluated before being
converted to strings ready to be concatenated. The CONCAT function takes two parameters. Its syntax is CONCAT(s1, s2), where s1 and s2 represent string literals,
character column values, or expressions resulting in character values.
The INSTR(source string, search item, [start position],[nth occurrence of search item]) function returns a number that represents the position in the source string,
beginning from the given start position, where the nth occurrence of the search item begins:
instr('http://www.domain.com','.',1,2) = 18
The TRIM function literally trims off leading or trailing (or both) character strings from a given source string:
A选项,mod应该是返回余数,而不是商
B选项,引用文档中的一段话:
This function takes as an argument any numeric data type or any nonnumeric data
type that canbe implicitly converted to a numeric data type . If you omit n2, then the
function returns thesame data type as the numeric data type of the argument. If you
include n2, then thefunction returns NUMBER.
C选项,concat(char1,char2)用于连接字符串
D选项,sysdate放回系统当前时间
scott@ORCL>selectsysdate from dual;
SYSDATE
--------------
02-12月-13
E选项,instr(char1,char2,[m[,n]])
The INSTR functionssearch string for substring. The search operation is defined
as comparing thesubstring argument with substrings of string of the same length
for equality until amatch is found or there are no more substrings left. Each
consecutive comparedsubstring of string begins one character to the right (for
forward searches) or onecharacter to the left (for backward searches) from the first
character of theprevious compared substring. If a substring that is equal to
substring is found, thenthe function returns an integer indicating the position of
the first character ofthis substring. If no such substring is found, then the function
returns zero.
SELECT INSTR('CORPORATEFLOOR','OR', 3, 2) "Instring"
FROM DUAL;
Instring
----------
14
F选项,trim() 从字符串string的头,尾或两端截掉字符
Q246.
77. In the CUSTOMERStable, the CUST_CITY column contains the value 'Paris' for the
CUST_FIRST_NAME'ABIGAIL'.
Evaluate the followingquery:
SQL> SELECT INITCAP (cust_first_name || ' ' ||
UPPER(SUBSTR(cust_city,-LENGTH(cust_city),2)))
FROM customers
WHERE cust_first_name ='ABIGAIL';
What would be theoutcome?
A. Abigail PA
B. Abigail Pa
C. Abigail IS
D. an error message
Answer: B
解析:
Initcap 返回首字母大写
INITCAP (UPPER(SUBSTR(cust_city,-LENGTH(cust_city),2)))
INITCAP (UPPER(SUBSTR(cust_city,-5,2)))
INITCAP (UPPER(Pa))
INITCAP(PA)
Pa
Q247.
scott@ORCL>selecttrim('son' from 'anderson') from dual;
select trim('son' from'anderson') from dual
*
第 1 行出现错误:
ORA-30001: 截取集仅能有一个字符
Trim的用法:
trim([leading | trailing| both] trim_char from string) 从字符串String中删除指定的字符trim_char。
leading:从字符串的头开始删除。
trailing:从字符串的尾部开始删除。
borth:从字符串的两边删除。
Q248.
SUBSTR(c1,n1[,n2])
【功能】取子字符串
【说明】多字节符(汉字、全角符等),按1个字符计算
【参数】在字符表达式c1里,从n1开始取n2个字符;若不指定n2,则从第y个字符直到结束的字串.
【返回】字符型
【示例】
SQL> select substr('13088888888',3,8) test from dual;
test
--------
08888888
INSTR(C1,C2[,I[,J]])
【功能】在一个字符串中搜索指定的字符,返回发现指定的字符的位置;
【说明】多字节符(汉字、全角符等),按1个字符计算
【参数】
C1 被搜索的字符串
C2 希望搜索的字符串
I 搜索的开始位置,默认为1
J 第J次出现的位置,默认为1
【返回】数值
【示例】select instr('oracle traning','ra',1,2) instring from dual;
返回:9
【示例】select instr('重庆某软件公司','某',1,1),instrb('重庆某软件公司','某',1,1) instring from dual;
返回:3,5
Q249.
Lex De Haan
SELECT LPAD(SUBSTR(cust_name, INSTR(cust_name,' ')), LENGTH(cust_name), '*') "CUST NAME"
FROM customers
WHERE INSTR(cust_name, ' ', 1, 2) <> 0;
SELECT LPAD(SUBSTR(cust_name, 4), LENGTH(cust_name), '*') "CUST NAME"
FROM customers
WHERE INSTR(cust_name, ' ', 1, 2) <> 0;
SELECT LPAD( De Haan, LENGTH(cust_name), '*') "CUST NAME"
FROM customers
WHERE INSTR(cust_name, ' ', 1, 2) <> 0;
SELECT LPAD( De Haan, 11, '*') "CUST NAME"
FROM customers
WHERE INSTR(cust_name, ' ', 1, 2) <> 0;
*** De Haan
Q250.
REPLACE(c1,c2[,c3])
【功能】将字符表达式值中,部分相同字符串,替换成新的字符串
【参数】
c1 希望被替换的字符或变量
c2 被替换的字符串
c3 要替换的字符串,默认为空(即删除之意,不是空格)
【返回】字符型
【示例】
SQL> select replace('he love you','he','i') test from dual;
test
------------------------------
i love you
SELECT CONCAT(SUBSTR(INITCAP(ename),1,3), REPLACE(hiredate,'-')) "USERID"
Q251.
In some cases, the Oracle server receives data of one data type where it expects data of a different data type.
When this happens, the Oracle server can automatically convert the data to the expected data type. This data type conversion can be done implicitly by the Oracle server
or explicitly by the user.
Explicit data type conversions are performed by using the conversion functions. Conversion functions convert a value from one data type to another. Generally, the form
of the function names follows the convention data type TO data type. The first data type is the input data type and the second data type is the output.
Note: Although implicit data type conversion is available, it is recommended that you do the explicit data type conversion to ensure the reliability of your SQL statements.
A选项不正确,inv_amt列是nubmer类型,右边是字符类型,这个是隐式转换。
B选项不正确,inv_date列是date类型,右边的格式和默认格式不一致,需要用to_date显式转换。
C选项不正确,这里是使用隐式转换,转换成字符型。
Q252.
一、原题
You want to display the date for the first Monday of the next month and issue the following command:
SQL>SELECT TO_CHAR(NEXT_DAY(LAST_DAY(SYSDATE),'MON'),
'dd "is the first Monday for" fmmonth rrrr')
FROM DUAL;
What is the outcome?
A. It executes successfully and returns the correct result.
B. It executes successfully but does not return the correct result.
C. It generates an error because TO_CHAR should be replaced with TO_DATE.
D. It generates an error because rrrr should be replaced by rr in the format string.
E. It generates an error because fm and double quotation marks should not be used in the format string.
答案:A
二、题目翻译
要显示下个月的第一个星期一的日期,执行下面的命令,结果是什么?
A.执行成功,并且能得出正确结果。
B.执行成功,但不能返回正确的结果。
C.报错,TO_CHAR应该用TO_DATE替换。
D.报错,格式中,rrrr应该用rr替换。
E.报错,fm和双引号不能用在格式字符串中。
三、题目解析
LAST_DAY显示本月的最后一天的日期,
NEXT_DAY函数返回从第一个参数的日期开始,紧接着下来的指定星期对应的第一个日期。
SQL>
SQL> SELECT TO_CHAR(NEXT_DAY(LAST_DAY(SYSDATE),'MON'),
'dd "is the first Monday for" fmmonth rrrr')
FROM DUAL;
TO_CHAR(NEXT_DAY(LAST_DAY(SYSDATE),'MON'),'DD
---------------------------------------------
04 is the first Monday for july 2016
next_day(d1[,c1])
【功能】:返回日期d1在下周,星期几(参数c1)的日期
【参数】:d1日期型,c1为字符型(参数),c1默认为j(即当前日期)
【参数表】:c1对应:星期一,星期二,星期三……星期日
【返回】:日期
【示例】
select sysdate 当时日期,
next_day(sysdate,'星期一') 下周星期一,
next_day(sysdate,'星期二') 下周星期二,
next_day(sysdate,'星期三') 下周星期三,
next_day(sysdate,'星期四') 下周星期四,
next_day(sysdate,'星期五') 下周星期五,
next_day(sysdate,'星期六') 下周星期六,
next_day(sysdate,'星期日') 下周星期日 from dual
Q253.
C. SELECT TO_CHAR(TO_NUMBER(prod_price,'$99,999.99')* .25,'$99,999.00') FROM PRICE_LIST;
Using the TO_CHAR Function
The TO_CHAR function returns an item of data type VARCHAR2. When applied to items of type NUMBER, several formatting options are available. The syntax is as
follows:
TO_CHAR(number1, [format], [nls_parameter]),
The number1 parameter is mandatory and must be a value that either is or can be implicitly(含蓄的暗中的) converted into a number. The optional format parameter may be used to specify numeric formatting information like width, currency symbol, the position of a decimal point, and group (or thousands) separators and must be enclosed in single
Syntax of Explicit Data Type Conversion
Functions
TO_NUMBER(char1, [format mask], [nls_parameters]) = num1 TO_CHAR(num1, [format mask], [nls_parameters]) = char1 TO_DATE(char1, [format mask],
[nls_parameters]) = date1 TO_CHAR(date1, [format mask], [nls_parameters]) = char1
Q254.
C. SELECT promo_name, TRIM(TO_CHAR(promo_end_date,'Day')) ', ' TRIM(TO_CHAR (promo_end_date,'Month')) ' '
TRIM(TO_CHAR(promo_end_date,'DD, YYYY')) AS last_day FROM promotions;
D. SELECTpromo_name,TO_CHAR(promo_end_date,'fmDay')','
TO_CHAR(promo_end_date,'fmMonth') ' '
TO_CHAR(promo_end_date,'fmDD, YYYY') AS last_day
FROM promotions
to_char(1210.73, '9999.9') 返回 '1210.7'
to_char(1210.73, '9,999.99') 返回 '1,210.73'
to_char(1210.73, '$9,999.00') 返回 '$1,210.73'
to_char(21, '000099') 返回 '000021'
to_char(852,'xxxx') 返回' 354'
to_char(sysdate,'d') 每周第几天
to_char(sysdate,'dd') 每月第几天
to_char(sysdate,'ddd') 每年第几天
to_char(sysdate,'ww') 每年第几周
to_char(sysdate,'mm') 每年第几月
to_char(sysdate,'q') 每年第几季
to_char(sysdate,'yyyy') 年
Q255. A
SELECT SUM(DECODE(SUBSTR(promo_begin_date,8),'00',1,0)) "2000", SUM(DECODE(SUBSTR (promo_begin_date,8),'99',1,0)) "1999"
FROM promotions;
decode(条件,值1,翻译值1,值2,翻译值2,...值n,翻译值n,缺省值)
SUBSTR(c1,n1[,n2])
【功能】取子字符串
【说明】多字节符(汉字、全角符等),按1个字符计算
【参数】在字符表达式c1里,从n1开始取n2个字符;若不指定n2,则从第y个字符直到结束的字串.
【返回】字符型
【示例】
SQL> select substr('13088888888',3,8) test from dual;
test
--------
08888888
Q256.
SELECT TO_CHAR(trans_date,'dd-mon-yyyy hh24:mi:ss'), NVL(TO_CHAR(trans_amt,'$99999999D99'),0) FROM transactions
WHERE TO_CHAR(trans_date,'hh24') < 12;
D(ISO 小数位符号)
HH24 表示小时,为24小时制(0-23)
DD 月份中的某天(1-31)
MON 月的简称,和国家有关系NLS_DATE_LANGUAGE,例如04在中文环境下用4月表示.
MONTH 月的名称,国家有关系NLS_DATE_LANGUAGE,目前在中文下04表示为4月。
【语法】NVL (expr1, expr2)
【功能】若expr1为NULL,返回expr2;expr1不为NULL,返回expr1。
注意两者的类型要一致
【语法】NVL2 (expr1, expr2, expr3)
【功能】expr1不为NULL,返回expr2;expr2为NULL,返回expr3。
expr2和expr3类型不同的话,expr3会转换为expr2的类型
Q257.
Range Conditions Using the BETWEEN Operator
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;
Range Conditions Using the BETWEEN Operator
You can display rows based on a range of values using the BETWEEN operator. The range that you specify contains a lower limit and an upper limit. The SELECT
statement in the slide returns rows from the EMPLOYEES table for any employee whose salary is between $2,500 and $3,500.
Values that are specified with the BETWEEN operator are inclusive. However, you must specify the lower limit first.
You can also use the BETWEEN operator on character values:
SELECT last_name
FROM employees
WHERE last_name BETWEEN 'King' AND 'Smith'
Q258.
B. SELECT promo_name,COALESCE(TO_CHAR(promo_end_date -
promo_start_date),'ONGOING') FROM promos;
C. SELECT promo_name, NVL(TO_CHAR(promo_end_date -promo_start_date),'ONGOING') FROM promos;
D. SELECT promo_name, DECODE(promo_end_date-promo_start_date,NULL,'ONGOING',promo_end_date - promo_start_date) FROM promos;
Oracle COALESCE函数语法为COALESCE(表达式1,表达式2,...,表达式n),n>=2,此表达式的功能为返回第一个不为空的表达式,如果都为空则返回空值。
注意:所有表达式必须为同一类型或者能转换成同一类型。
Q259.
D. SELECT promo_name, DECODE((NULLIF(promo_start_date, promo_end_date)), NULL,'Same day') FROM promos;
【语法】NULLIF (expr1, expr2)
【功能】expr1和expr2相等返回NULL,不相等返回expr1
Q260.
B. NVL(COALESCE(list_price, min_price), 0)
D. COALESCE(NVL2(list_price, list_price, min_price), 0)
Using the COALESCE Function
· The advantage of the COALESCE function over the NVL function is that the COALESCE function can take multiple alternate values.
· If the first expression is not null, the COALESCE function returns that expression; otherwise, it does a COALESCE of the remaining expressions.
Using the COALESCE Function
The COALESCE function returns the first non-null expression in the list.
Syntax
COALESCE (expr1, expr2, ... exprn)
In the syntax:
· expr1 returns this expression if it is not null
· expr2 returns this expression if the first expression is null and this expression is not null · exprn returns this expression if the preceding expressions are null Note that all expressions must be of the same data type
Q261.
Using the AVG and SUM Functions
You can use the AVG, SUM, MIN, and MAX functions against the columns that can store numeric data. The example in the slide displays the average, highest, lowest,
and sum of monthly salaries for all sales representatives
Using the MIN and MAX Functions
You can use the MAX and MIN functions for numeric, character, and date data types. The example in the slide displays the most junior and most senior employees.
答案:(B、D)
解析:
A(X),AVG只能应用于数值类型
C(X), 分组函数嵌套使用,需要使用GROUP BY子句。
Q262.
D. It gives an error because the data type conversion in the SELECT list does not match the data type conversion in the GROUP BY clause.
Answer: D
To_char需要前后转换格式一样,测试:
scott@ORCL>select to_char(hiredate,'rr') from emp group byto_char(hiredate,'yyyy')
2 ;
selectto_char(hiredate,'rr') from emp group by to_char(hiredate,'yyyy')
*
第 1 行出现错误:
ORA-00979: 不是 GROUP BY 表达式
Q263.
Having后不能使用嵌套分组函数,测试:
scott@ORCL>selectavg(max(sal)) from emp group by empno having avg(max(sal));
select avg(max(sal))from emp group by empno having avg(max(sal))
*
第 1 行出现错误:
ORA-00935: 分组函数的嵌套太深
Q264.
A. The HAVING clause can be used with aggregate functions in subqueries
C. The WHERE clause can be used to exclude rows before dividing them into groups.
Q265.
C. It displays the item nos with their average quantity where the average quantity is more than double the minimum quantity of that item in the table.
一、原题
Examine the data in the ORD_ITEMS table:
ORD_NO ITEM_NO QTY
1 111 10
1 222 20
1 333 30
2 333 30
2 444 40
3 111 40
Evaluate the following query:
SQL>SELECT item_no, AVG(qty)
FROM ord_items
HAVING AVG(qty) > MIN(qty) * 2
GROUP BY item_no;
Which statement is true regarding the outcome of the above query?
A. It gives an error because the HAVING clause should be specified after the GROUP BY clause.
B. It gives an error because all the aggregate functions used in the HAVING clause must be specified in the SELECT list.
C. It displays the item nos with their average quantity where the average quantity is more than double the minimum quantity of that item in the table.
D. It displays the item nos with their average quantity where the average quantity is more than double the overall minimum quantity of all the items in the table.
答案:C
二、题目翻译
查看下面ORD_ITEMS表的数据:
评估下面的查询:
关于上面语句的结果哪句话是正确的?
A.报错,因为HAVING子句应该放在GROUP BY子句之后。
B.报错,因为所有在HAVING子句中使用的聚合函数必须被指定到SELECT列表中。
C.显示item_nos和他们的平均数量,平均数量要大于每组item中最小数量的两倍。
D.显示item_nos和他们的平均数量,平均数量要大于所有item最小值的两倍。
三、题目解析
A选项不正确,HAVING子句可以放到GROUP BY子句前面。
B选项不正确,HAVING子句中的聚合函数,不一定要放在SELECT的列表中,这个没有关系的。
Q266.
Answer: AB
解析:
find out if any customers'details have been
entered more thanonce using different CUSTNO, by listing all the duplicate names.
需要用自连接比较names
需要使用子查询得到customers'details have beenentered more than once using different CUSTNO
Q267.
相等连接(第一种写法):
select table1.column,table2.column
from table1, table2
where table1.column1=table2.column2
可以使用表的别名,为了书写的简化。
相等连接(第二种写法):
select table1.column,table2.column
from table1 inner join table2
on table1.column1=table2.column2
可以使用表的别名,为了书写的简化。
左外联接的写法
左外连接(第一种写法):
select table1.column,table2.column
from table1 left outer join table2
on table1.column1=table2.column2
可以使用表的别名,为了书写的简化。
左外连接(第二种写法):
select table1.column,table2.column
from table1, table2
where table1.column1=table2.column2(+)
可以使用表的别名,为了书写的简化。
Q268.
A. JOIN
B. NATURAL JOIN
C. LEFT OUTER JOIN
D. FULL OUTER JOIN
E. RIGHT OUTER JOIN
Answer: A,E
corresponding 相应的相当的
Q269.
C. FROM customers LEFT OUTER JOIN sales USING (cust_id) RIGHT OUTER JOIN countries USING (country_id);
Q270.
C. only LEFT OUTER JOIN
Q271.
C. RIGHT OUTER JOIN; LEFT OUTER JOIN
Q272.
B. FULL OUTER JOIN
C. LEFT OUTER JOIN
Q273.
Using a Subquery to Solve a Problem
Suppose you want to write a query to find out who earns a salary greater than Abel's salary. To solve this problem, you need two queries: one to find how much Abel
earns, and a second query to find who earns more than that amount.
You can solve this problem by combining the two queries, placing one query inside the other query. The inner query (or subquery) returns a value that is used by the
outer query (or main query).
Using a subquery is equivalent to performing two sequential queries and using the result of the first query as the search value in the second query.
Subquery Syntax
A subquery is a SELECT statement that is embedded in the clause of another SELECT statement. You can build powerful statements out of simple ones by using
subqueries. They can be very useful when you need to select rows from a table with a condition that depends on the data in the table itself.
You can place the subquery in a number of SQL clauses, including the following:
WHERE clause
HAVING clause
FROM clause
In the syntax:
operator includes a comparison condition such as >, =, or IN Note: Comparison conditions fall into two classes: single-row operators (>, =, >=, <, <>, <=) and multiple-row
operators (IN, ANY, ALL, EXISTS).
The subquery is often referred to as a nested SELECT, sub-SELECT, or inner SELECT statement. The subquery generally executes first, and its output is used to
complete the query condition for the main (or outer) query.
Guidelines for Using Subqueries
Enclose subqueries in parentheses. Place subqueries on the right side of the comparison condition for readability. (However, the subquery can appear on either side of the comparison operator.) Use single-row operators with single-row subqueries and multiple-row operators with multiple-row subqueries.
Subqueries can be nested (嵌套)to an unlimited depth in a FROM clause but to "only" 255 levels in a WHERE clause. They can be used in the SELECT list and in the FROM,
WHERE, and HAVING clauses of a query.
Q274.
A. Subqueries can contain GROUP BY and ORDER BY clauses.
B. Main query and subquery can get data from different tables.
C. Main query and subquery must get data from the same tables.
D. Subqueries can contain ORDER BY but not the GROUP BY clause.
E. Only one column or expression can be compared between the main query and subquery.
F. Multiple columns or expressions can be compared between the main query and subquery.
Answer: A,B,F
SUBQUERIES can be used in the SELECT list and in the FROM, WHERE, and HAVING clauses
因为专业、所以必过
QQ: 6693 0855 微信: anypass
of a query.
A subquery can have any of the usual clauses for selection and projection. The following are required clauses:
A SELECT list
A FROM clause
The following are optional clauses:
WHERE
GROUP BY
HAVING
The subquery (or subqueries) within a statement must be executed before the parent query that calls it, in order that the results of the subquery can be passed to the
parent.
Q275.
Answer: C,E
Q276.
A. The statement executes successfully and produces the required output.
Q277.
A. SELECT prod_name
FROM products
WHERE (unit_price * qty_in_hand) = (SELECT MAX(unit_price * qty_in_hand) FROM products);
Q278.
C. It generates an error because the subquery does not have a GROUP BY clause.
Q279.
C. It generates output for NULL as well as the other values produced by the subquery
Q280.
A. It shows COST_REMARK for all the promos in the table.
Q281.
A. SELECT prod_category,avg(prod_list_price)
FROM products
GROUP BY prod_category
HAVING avg(prod_list_price) < ALL
(SELECT max(prod_list_price)/2
FROM products
GROUP BY prod_category);
Using the ANY Operator in Multiple-Row Subqueries
The ANY operator (and its synonym, the SOME operator) compares a value to each value returned by a subquery.
>ANY means more than the minimum.
=ANY is equivalent to IN
Using the ALL Operator in Multiple-Row Subqueries
The ALL operator compares a value to every value returned by a subquery.
>ALL means more than the maximum and
The NOT operator can be used with IN, ANY, and ALL operators
Q282.
D. It displays prod IDs in the promos with cost less than the highest cost in the same time interval.
Answer: D
Q283.
A.
SELECT prod_id FROM products
INTERSECT
SELECT prod_id FROM sales;
C. SELECT DISTINCT p.prod_id
FROM products p JOIN sales s
ON p.prod_id=s.prod_id;
Q284.
A. It locks all the rows that satisfy the condition in the statement.
C. The locks are released only when a COMMIT or ROLLBACK is issued.
FOR UPDATE Clause in a SELECT Statement
· Locks the rows in the EMPLOYEES table where job_id is SA_REP. · Lock is released only when you issue a ROLLBACK or a COMMIT. · If the SELECT statement
attempts to lock a row that is locked by another user, the database waits until the row is available, and then returns the results of the SELECTstatement
SELECT employee_id, salary, commission_pct, job_id
FROM employees
WHERE job_id = 'SA_REP'
FOR UPDATE
ORDER BY employee_id
Q285.
FOR UPDATE Clause in a SELECT Statement
Locks the rows in the EMPLOYEES table where job_id is SA_REP. Lock is released only when you issue a ROLLBACK or a COMMIT. If the SELECT statement
attempts to lock a row that is locked by another user, the database waits until the row is available, and then returns the results of the SELECT statement.
FOR UPDATE Clause in a SELECT Statement
When you issue a SELECT statement against the database to query some records, no locks are placed on the selected rows. In general, this is required because the
number of records locked at any given time is (by default) kept to the absolute minimum: only those records that have been changed but not yet committed are locked.
Even then, others will be able to read those records as they appeared before the change (the "before image" of the data). There are times, however, when you may want
to lock a set of records even before you change them in your program. Oracle offers the FOR UPDATE clause of the SELECT statement to perform this locking. When
you issue a SELECT...FOR UPDATE statement, the relational database management system (RDBMS) automatically obtains exclusive row-level locks on all the rows
identified by the SELECT statement, thereby holding the records "for your changes only." No one else will be able to change any of these records until you perform a
ROLLBACK or a COMMIT. You can append the optional keyword NOWAIT to the FOR UPDATE clause to tell the Oracle server not to wait if the table has been locked
by another user. In this case, control will be returned immediately to your program or to your SQL Developer environment so that you can perform other work, or simply
wait for a period of time before trying again. Without the NOWAIT clause, your process will block until the table is available, when the locks are released by the other user
through the issue of a COMMIT or a ROLLBACK command.
Q286.
A. The statement will execute and the new row will be inserted in the SALES table.
Q287.
D. It gives an error because the number of columns to be inserted does not match with the number of columns in the SALE_SUMMARY table.
Answer: D
Q288.
One UPDATE statement can change rows in only one table, but it can change any number of rows in that table
C. It would execute and restrict modifications to only the columns specified in the SELECT statement.
Q289.
B. It executes successfully but does not give the correct result.
Q290.
A. DELETE can be used to remove only rows from only one table at a time.
E. DELETE and TRUNCATE can be used on a table that is a parent of a referential integrity constraint having ON DELETE rule.
Q291.
B. A part or an entire transaction can be undone by using ROLLBACK command.
C. A transaction consists of a set of DML or DCL statements
Q292.
B. Savepoints may be used to ROLLBACK.
C. Savepoints can be used for only DML statements.