• Oracle Database 11g express edition


    commands :

    show sys

    connect sys as sysdba or connect system as sysdba
    logout or disc
    clear screen or cle screen
    (utlsample.sql  —> unlock scott
    tables.sql  —> all tables
    data.sql  —> add data into tables)
    connect scott/tiger
    start C:utlsample.sql
    @C:utlsample.sql (unlock scott and close SQL)
    @C: ables.sql (create tables)
    @C:data.sql (add data)
    select * from table_name (list the names of all tables in scott user)
    select column_name from table_name
    describe talbe_name or desc table_name (to see the structure of the table)
    select * from table_name;(to display the data from the table) 
    the * means all columns
    select code,fee from table_name;
    create table table_name (to create a table)
    (Stud_ID number(2),
     Stud_Name varchar2(25),
     Stud_Add varchar2(30),
     Stud_Birth date )
    insert into table_name values (number, ‘First_info’, ’second_info’,’ third_info’, ’forth_info’) ; (to add concret info. to the table column)
    insert into table_name (column1_name,column2_name) values (values for col1,values for col2);
    commit (save the data or work)
    select CCode,Fee,from courses;
    to show 15% of fee
    select CCoe,fee,fee *0.15 from courses;
    Fee * 0.5, fee + 1000, fee - 500, fee / 2
    select ccode, fee, fee * 0.5 Discount from courses;(display code,fee,this two columns and create and display a column called discount from fee * 0.5)
    select column_names from table_name where conditions
    eg : select stud_id, name from student_maste where name=22;
    select * from cources where fee=4500; (display all columns fee is equal to 4500)
    select * from cources where fee=4500 and ccode=‘ora’ ; (display all columns where fee is equal to 4500 and ccode = ora )
    select * from cources where fee=5500 or ccode=‘ora'; (display all columns where fee is equal to 5500 or ccode = ora )
     expressions : *, +, -, / .
    order by column_name [ascending order small to large, descending order large to small]
    asc for ascending
    desc for desending
    select name,fee from courses order by fee asc;
    select name,fee fee * 0.20 from courses order by 3;(order by fee * 0.20 when it has no name)
    select name,fee fee * 0.20 discount from courses order by discount;(默认是asc,)
    select name,duration,fee from courses order by duration, fee desc;(按照duration从小到大,fee从大到小排列,并且显示结果第一列优先,即先按照duration从小到大排,再根据fee从大到小排)
    注:列的名的字母大小写是敏感的
     
    where fee in (1000, 5000);
    where city in (‘Beijing’,’Shanghai’,’AAA’,’BBB’)
    where city like ‘%_n%’
    % means zero to any number of chars(表示0个或多个字符)
    _ means single char or single value(表示一个字符)
    escape
    where 后的operator : =;!= or <>;>=;<=;>;<; and ;or,not; in ; like;(between…and…,is null)
     
     google why @c:utlsample.sql not work
    select * from tab;
    select count(*)from tab;
    connect sys/secret as sysdba
    10.20
    constraints to implement standard and business rules
    primary key 
    foreign key
    create table
    alter table change the structure : column name, size, datatype, remove / add columns
    column constraint (rules) PK
    table constraint 
    table_name_column_name_PK
     
    constraint name for column
    type of constraint
    user_constraints
    eg : desc user_constraints
    user_constraints
    constraint_name, constraints_type, constraint_
    P : primary key
    C: check 
    U : unique key
    Test_Student1
    stud_ID number(4) constraint STUDENT1PK PRIMARY KEY
    eg: create table test_student1(stud_id number(4) constraint teststudent1pk primary key);
         desc test_student1
         insert into test_student1 values (1001);
         insert into test_student1 values (1002);
    Test_Student2
    stud_ID
    stud_Phone
    eg: create table test_student2(stud_ID number(4),stud_phone number(11),name varchar2(10),constraint teststudent2cpk primary key(stud_ID, stud_phone));
    insert into test_student2 values (1001,12345,null);
    insert into test_student2 values(1001,12346,’ABC’);
    unique constraint 
    eg: create table test_student3 (stud_name varchar2(15) constraint ABCD unique);
    insert into test-student3 values (null);
    insert into test-student3 values (null);
    insert into test-student3 values (ABC);
    select * from test_student3;
    select rownum,stud_name from test_student3;
    RowID, rownum
    select rownum,rowid,student_name from test_student3;
     
    10.21
    连接运算符:||
    eg : select last_name || job_id as “employees” from employees;
    (将last_name和job_id合并成一列并将该列命名为employees)
    文本字符串需用单引号括起来
    eg : select last_name || ‘ is a ‘ || job_id as “employee details” from employees;
    (将last_name和job_id合并成一列并在其中间加上字符串’ is a ’并将该列命名为employees)
    制定自己的引号分隔符
    eg : select department_name || q’[ , it’s assigned manager ID: ]‘ || manager_id as “Department and Manager” from departments;
    (将department_name和manager_id合并成一列并在其中间引用字符串’, it’s assigned manager ID : ’并将该列命名为Department and Manager。注意:q后的单引号和方括号之间不能有空格)
    去掉重复的行
    eg : select distinct department_id from employees;
    替换变量 : & 和 &&指定列名,表达式和文本
    eg : select employee_id,lastname,salary,department_id from employees where employ_id = &employee_num;(会提示输入employee_num,然后显示该employee_id的所选中的信息)
    eg : select last_name,department_id,salary*12 from employees where job_id = ‘&job_title’;
    &&
     
    define和undefine
    define用来创建并分配一个值给一个变量
    undefine用来删除一个变量
     
    10.22创建表格
    create table pk1(ID number(5) constraint PK123 Primary Key);
    create table fk1(ID number(5) constraint FK1123 Foreign Key);
    delete from table_name;(删除表格中的信息必须先删除child table中的信息,之后才能删除父表中的信息)
    foreign key(child table)
    primary key(parent table)
    on delete cascade(用这个可以直接删除父表中的信息,同时也将删除子表中的信息)
    eg : 
    create table pk1(ID number(4) constraint PK123 Primary Key);
    create table fk1(ID number(4) constraint FK1123 fererences pk1(ID) on delete cascade);
     
    drop table table_name(用来删除表格)
     
    check constraint
    eg : t1 ( grade char(1) constraint ck123 check (grade in (‘A’,’B’,’C')))
    create table t1(grade char(1) constraint ck123 check(grade in (‘A’,’B’,’C’)));
    check (score > 60)
    to convert grade to uppercase before comparison : 
    create table course_faculty(grade char(1) CONSTRAINT course_faculty_grade_chk CHECK(upper(grade) in (‘A’,’B’,’C’) ),
    to get names of constraints of a table : 
    eg : select constraint_name from user_constraints where table_name = ’table_name’;
     
     
    10.27
    change structure and data
    alter table table_name(to alter/change the structure of the table)
    desc user_constraints(to show the constraints of the table)
    constraint_type (包括PK/FK/UK/CH/NN)
    search_condition
    constraint_name
    status(enabled/disabled)
    user_constraints(table_name)
    desc
    select (data inside the columns )
    delete(remove info.)
    rollback(undo 在delete命令后立即使用rollback来撤销delete操作,若commit后则无法撤销)
    commit(save the instructions)
    drop(remove table)
     
    alter table table_name add
    alter table table_name drop column column_name;
     
    desc user_constraints
    create table t123 (ID number(5));
    desc table t123;
    alter table t123 add (ename varchar2(10));
    desc table t123;
    alter table t123 modify (ename varchar2(12));
    desc table t123;
    alter table t123 modify (ename varchar2(5));
    desc table t123;
    alter table t123 modify (ename number(10));
    desc table t123;
    alter table t123 drop column enames;
    desc table t123;
    alter table t123 drop column ID;
    desc table t123;
    alter table t123 add (ename varchar2(10) constraint ename_not_null not null);
    desc table t123;
     
    select constraint_name from user_constraints where table_name = ‘T123’;
    select constraint_name,constraint_type,search_cndition,status from user_constraints where table_Name = ‘T123’;
    insert into t123 values(12345,’ABCDE’);
    alter table t123 disable constraint ename_not_null;
    select constraint_name,constraint_type,search_cndition,status from user_constraints where table_Name = ‘T123’;
    insert into t123 values(12345,null);
    select * from t123;
    alter table t123 enable constraint ename_not_null;
    select * from t123;
    delete from t123 where ename is null;
    select * from t123;
    alter table t123 enable constraint ename_not null;
    alter table t123 drop constraint ename_not null;
    desc t123
    select * from t123;
    insert into t123 values(2222,null);
    insert into t123 values(3333,null);
    select * from t123;
    alter table t123 modify (ename varchar2(10) constraint ename_not_null);
     
     
    10.28
    SQL中的函数(使用单行函数自定义输出 使用组函数报告合集数据)
    单行函数( 字符函数 数字函数 日期函数 转换函数 通用函数 条件表达式)
    接受多个参数并返回一个值
    function_name [(arg1,arg2,…)]
     字符函数(大小写处理函数 字符处理函数)
    大小写处理函数:LOWER, UPPER, INITCAP
    字符处理函数:CONCAT, SUBSTR, LENGTH, INSTR, LPAD | RPAD, TRIM, REPLACE
    eg : LOWER(‘SQL Course’)(输出结果为sql course)
      UPPER(‘SQL Course’)(输出结果为SQL COURSE)
      INITCAP(’SQL Course’)(输出结果为Sql Course)
    eg : 显示雇员Higgins的雇员号,姓名和部门号
    select employee_id,last_name,department_id from employees where LOWER(last_name) = ‘higgins’;
    CONCAT(把两个值并在一起): Joins values together (You are limited to using two parameters with CONCAT.)
    eg : CONCAT(‘Hello’,’World’)(输出结果为HelloWorld)

    SUBSTR(压缩字符串为一个固定的长度): Extracts a string of determined length 

    eg : SUBSTR(‘HelloWorld’,6,5)(输出结果为World) 

    LENGTH(显示一个字符串的长度): Shows the length of a string as a numeric value

    eg : LENGTH(‘HelloWorld’)(输出结果为10)

    INSTR(找到一个字母所在的位置): Finds the numeric position of a named character

    eg : INSTR(’HelloWorld’.’W’)(输出结果为6)

    LPAD(右对齐): Pads the character value right-justified

    eg : LPAD(salary,10,’*’)(输出结果为*****24000)

    RPAD(左对齐): Pads the character value left-justified

    eg : RPAD(salary,10,’*’)(输出结果为 24000*****)

    REPLACE: 字母替换

    eg: REPLACE(‘JACE and JUE’,’J’,’BL’)(输出结果为BLACE and BLUE)

    TRIM(去掉字符串的首字母或尾字母): Trims heading or trailing characters (or both) from a character string (If trim_character or trim_source is a character literal, you must enclose it in single quotation marks.)

    eg : TRIM(‘H’ FROM ‘HelloWorld’)(输出结果为elloWorld)

    eg : SELECT employee_id, CONCAT(first_name, last_name)NAME,job_id, LENGTH (last_name), INSTR(last_name, ‘a’) “Contains ‘a’?” FROM employees WHERE SUBSTR(job_id,4) = ‘REP’;
    eg : select substr(‘Hello World’, 4) from dual;(输出结果为lo World)
           select substr(‘Hello World’, -4) from dual;(输出结果为orld)
           select substr(‘Hello World’, -4,3) from dual;(输出结果为orl)
    round : 四舍五入指定小数的值
    eg : round(45.926,2)(结果为45.93)
    eg : select round(45.926,2),round(45.926,0),round(45.926,-1) from dual;
    注:dual是一个虚拟表,可以用来查看函数和计算的结果
    trunc : 截断指定小数的值
    eg : trunc(45.926,2)(结果为45.92)
    eg : select trunc(45.923,2),trunc(45.923),trunc(45.923,-1) from dual;
    mod : 返回除法的余数
    eg : mod(1600,300)(结果为100)
    eg : select last_name,salary,mod(salary,5000) from employees where job_id = ‘SA_REP’;(计算所有销售代表的雇员的工资被5000除后的余数)
    日期函数(DD-MON-RR)
    eg : select last_name,hire_date from employees where hire_date < ’01-FEB-88’;
    sysdate
    e.g.  : select sysdate from dual;
    eg : select last_name,(SYSDATE_hire_date)/7 AS WEEKS FROM employees WHERE department_id = 90;
    months_between(date1,date2)(返回两个日期之间的月数date1-date2)
    eg : months_between(’01-SEP-95’,’11-JAN-94’)(结果为19.6774194)
    add_months(date,n)(加n个month到date)
    eg : add-months(’11-JAN-94’,6)(结果为11-JUL-94)
    next_day(date,’char’)(下个星期几是几号)
    eg : next_day(’01-SEP-95’,’FRIDAY’)(结果为08-SEP-95)
    last_day(date)(包含这个日期的月的最后一天)
    eg : last_day(’01-FEB-95’)(结果为28-FEB-95)
    eg : to display the employee number,hire date, number of months employed,six-month review date,first Friday after hire date,and last day of the hire month for all employees who have been employed for fewer than 70 months.
    select employee_id,hire_date,months_between(sysdate,hire_date)tenure,add_months(hire_date,6)review,next_day(hire_date,’FRIDAY’),last_day(hire_date) from employees where months_between(sysdate,hire_date) < 70;
    round(date,[‘fmt’(format)])(四舍五入日期)
    trunc(date,[‘fmt’](formate))(截断日期)
    eg : 假定sysdate=’25-JUL-03’;
    select round(sysdate,’month’) from dual;(输出结果为01-AUG-03)
    select round(sysdate,’year’) from dual;(输出结果为01-JAN-04)
    select trunc(sysdate,’month’) from dual;(输出结果为01-JUL-03)
    select trunc(sysdate,’year’) from dual;(输出结果为01-JAN-03)
    eg : to compare the hire dates for all employees who started in 1997,display the employee number,hire date,and start month using the round and trunk functions.
    select employee_id,hire_date,round(hire_date,’month’),trunk(hire_date,’month’) from employees where hire_date like ‘%97’;
     
    转换函数(隐式数据类型转换)(显式数据类型转换)

    隐式数据类型转换 :

    对于直接赋值,Oracle服务其能够自动地进行下面的转换:

    从 varchar2/char 到 number

    从 varchar2/char 到 date

    从 number 到 varchar2

    从 date 到 varchar2

    eg : the expression hire_date > '01-JAN-90' results in the implicit conversion from the string '01-JAN-09' to a date

    对于表达式复制,Oracle服务其能够自动地进行下面的转换:

    从 varchar2/char 到 number

    从 varchar2/char 到  date

    eg : the expression salary = '20000' results in the implicit conversion of the string '20000' to the number 20000.

    显式数据类型转换 :

    数字 <==> 字符(to_number/to_char)

    字符 <==> 日期(to_date/to_char)

    to_char(number | date,[fmt],[nlsparams])(converts a number or date to a varchar2 character string with format model fmt)

    eg : to_char(date,'format_model')

    to_number(char,[fmt],[nlsparams])(converts a character string containing digits to a number in the format specified by the optional format model emt.)

    to_date(char,[fmt],[nlsparams])(convets a character string representing a date to a date value according to the fmt that is specified.If emt is omitted, the format is DD-MON-YY.)

    eg : select employee_id, to char(hire_date,'MM/YY') Month_Hired from employees where last_name = 'Higgins';

    日期格式模版的元素 : 

    YYYY(年的全写(四位数字))

    YEAR(年的拼写)

    MM(月的两位数值)

    MONTH(月的全称)

    MON(月的前三个字母缩写)

    DY(天的前三个字母缩写)

    DAY(天的全称)

    DDD(年)

    DD(月)

    D(周)

    elements of the date format model : 

    HH24:MI:SS AM(15:45:32 PM)

    DD ''of" MONTH

    ddspth

    to_char函数用于日期转换:

    eg : select last_name,to_char(hire_date,'fmDD Month YYYY') as HIREDATE from employees;

    eg : select last_name,to_char(hire_date,'fmDdspth "of" Month YYYY fmHH:MI:SS AM') as HIREDATE from employees;(to display teh dates in a format that appears as "Seventeenth of June 1987 12:00:00 AM.")

    to_char函数用于数字转换:

    to_char(number,'format_model')

    eg : select ro_char(salary,'$99,99.00') SALARY from employees where last_naem = 'Ernst';

    使用to_number函数实现将字符串转换为数字格式:

    to_number(char ,[format_model'])

    使用to_date函数实现将字符串转换为日期格式:

    to_date(char,['format_model'])

    eg : select last_name,hire_date from employees where hire_date = to_date('May 24,1999','fxMonth DD,YYYY');(to display the name and hire date for all employees who started on May 24,1999.because the fx modifier is used,an exact match is required and the spaces after the word May are not recognized. )

    RR 日期格式(取近)
    YY 日期格式(尊原)
    eg : select last_name,to_char(hire_date,’DD-Mon-YYY’) from employees where hire_date < to_date(’01-Jan-90’,’DD-Mon-RR’);(为了找出1990年以前受雇的雇员,使用rr格式,不管该命令运行在1999年还是现在,都会得到相同的结果)
    eg : select last_name,to_char(hire_date,’DD-Mon-YYYY’) from employees where to_date(hire_date,’DD-Mon-YY’) < ’01-Jan-1990’;(this command, on the other hand, results in no rows selected because the YY format interprets the year portion of the date in the current century(2090))
    嵌套函数
    单行函数可以无数层嵌套,嵌套函数从最里层开始计算
    eg : select last_name, upper(concat(substr(last_name,1,8),’_US’)) from employees where department_id = 60;(displays the last_name of employees in department 60)
     

    eg : select to_char(next_day(add_months(hiredate,6),'Friday'),'fmDay,Month DDth,YYYY') "Next 6 Month Review" from employees order by hire_date;(to display the date of the next Friday that is six months from the hire date.(the result date should appear as Friday,August 13th,1999.))

    通用函数(可用于任意数据类型(number,date,char or varchar2),并且适用于null值)

    NVL(expr1,expr2)(converts a null value to an actual value)(expr1 和expr2的数据类型必须一样)

    eg : select last_name,salary,nvl(commission_pct,0),(salary*12) + (salary*12*nvl(commission_pct,0)) AN_SAL from employees;

    NVL2(expr1,expr2,expr3)(if expr1 is not null,nvl2 returns expr2. If expr1 is null, nvl2 returns expr3. the argument expr1 can have any data type,the argument epr2 and expr3 can have any date types except long, if the data types of expr2 and expr3 are different, the oracle server converts expr3 to the data type of expr2 before comparint them unless expr3 is a null constant. so the data type of the return value is always the same as the data type of expr2 unless expr2 is character data, in which case the return value's data type is varchar2.)

    eg : select last_name,salary,commission_pct,nvl2(commission_pct, 'sal_comm', 'sal') income from employees where department_id in (50,80);

    NULLIF(expr1,expr2)(compares two expressions and returns null if they are equal, returns the first exression if they are not equal)

    eg : select first_name,length(first_name) "expr1", last_name, length(last_name) "expr2", nullif(length(first_name),length(last_name)) result from employees;

    COALESCE(expr1,expr2,...,exprn)(returns the first non-null expression in the expression list. all expressions must be of the same data type.)

    eg : sleect last_name,coalesce(manager_id, commission_pct, -1) comm from employees order by commission_pct;

    条件表达式(if-then-else逻辑)(case表达式,decode表达式)

    Note: The CASE expression complies with ANSI SQL. The DECODE function is specific to Oracle syntax.

    case表达式

    eg : case expr when comparison_expr1 then return_expr1 [when comparison_expr2 then return_expr2 when comparison_exprn then return_exprn else else_expr] end

    注:all of the expressions(expr,comparison_expr and return_expr) must be of the same data type, which can be char,varchar2,nchar,or nvarchar2.

    eg : select last_name,job_id,salary,case job_id when 'it_prog' then 1.10*salary when 'st_clerk' then 1.15*salary when 'sa_rep' then 1.20*salary else salary end "revised_salary" from employees;

    eg : select last_name,salary,(case when salary < 5000 then 'Low' when salary < 10000 then 'Mediun' when salary < 20000 then 'Good' else 'Excellent' end) qualified_salary from employees;

    decode函数

    eg : decode(col|expression, search1, result1 [,search2,result2,...,] [,default])

    eg : select last_name,job_id,salary, decode(job_id, 'it_prog', 1.10*salary, 'st_clerk', 1.15*salary, 'sa_rep', 1.20*salary, salary) revised_salary from employees;

    eg : select last_name, salary, decode (trunc(salary/2000,0), 0, 0.00, 1, 0.09, 2, 0.20, 3,0.30,4, 0.40,5, 0.42, 6, 0.44, 0.45) TAX_RATE  from employees where department_id = 80;(显示每一位在部门80的员工的适用税率)

    组函数

    eg : select [column,] group_function(column), ... from table_name [where condition] [group by column] [order by column];

    注:distinct makes the function consider only nonduplicate values; all makes it consider every value, including duplicates. (the default is all and therefore does not need to be specified.)

    avg([distinct|all]n) (average value of n, ignoring null values

    count({*|[distinct|all]expr}) (number of rows,where expr evalutes to something other than null(count all selected rows using * , including duplicates and rows )

    eg : select count(*) from employees where department_id = 50; (displays the number of employees in department 50.) (返回ID为50的行数)

    eg : select count(commission_pct) from employees where department_id = 80; (displays the number of employees in department 8 who can earn a commission.)(返回commission为非空值的行数)

    注 :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.

    eg : select count(distinct department_id) from employees; (to display the number of distinct department values in the employees table.)

    组函数忽略空值的列:

     eg : select avg(commission_pct) from employees; (返回值为 .2125)

    nvl函数强制组函数包括空值:

    eg : select avg(nul(commission_pct,0)) from employees; (返回值为 .0425)

    max([distinct|all]expr) (maximun value of expr,ignoring null values)

    min([distinct|all]expr) (minimum value of expr, ignoring null values)

    stddev([distinct|all]x) (standard deviation of n, ignoring null values)

    sum([distinct|all]n) (sum values of n, ignoring null values)

    variance([distinct|all]x) (variance of n, ignoring null values)

    在数值型数据中可以适用avg 和 sum

    eg : select avg(salary), max(salary), min(salary), sum(salary) from employees where job_id like '%REP%';

    对于数字,字符和日期数据类型,可以使用min 和 max

    eg : select min(hire_date),max(hire_date) from employees;

    创建组群数据(group by)

    eg :select column, group_function(column) from table [where condition] [group by group_by_expression] [order by column];

    注:group_by_expression specifies columns whose values determine the basis for grouping rows.

    you cannot use a column alias in the group by clause(group by条件句后不能有别名)

    all columns in the select list that are not in group functions must be in the group by clause.(select 后的列不在组函数里就必须在group by 条件句里)

    eg : select department_id, avg(salary) from employees group by department_id; (displays the department number and the average salary for each department.)

    the group by column does not have to be in the select list(group by条件句中的列不必要在select中)

    eg : select avg(salary) from employees group by department_id;(displays the average salaries for each department without displaying the respective department numbers. without the department numbers, however, the results do not look meaningful.)

    you can use the group function in the order by clause : 

    select department_id,avg(salary) from employees group by department_id order by avg(salary);

    using the group by clause on multiple columns

    eg : select department_id dept_id,job_id,sum(salary) from employees group by department_id,job_id;

    注 :1.any column or expression in the select list that is not an aggregate function must be in the group by clause(whenever you use a mixture of individual items (eg : department_id) and group functions (eg : count(last_name) in the same select statement, you must include a group by clause that specifies the individual items. If the group by clause is missing, then the error message "not a single_group group function" appears and an asterisk(*) points to the offending column))

    注 : 2. you cannot use the where clause to restrict groups. you use the having clause to restrict groups.

    注 : 3. you cannot use group functions in the where clause. 

    eg : select department_id, avg(salary) from employees having avg(salary) > 8000 group by department_id;

    restricting group results with the having clause

    eg : select column, group_function from table_name [where condition] [group by group_by_condition] [having group_condition] [order by column];

    eg : select department_id, max(salary) from employees group by department_id having max(salary) > 1000;(displays department numbers and amximum salaries for those departments with a maximum salary that is greater than $10000.)

    注: you can use the group by clause without a group function in the select list(select后没有组函数也可以使用group by 条件句)

    eg : select department_id, avg(salary) from employees group by department_id, having max(salary) > 10000;(displays the department numbers and average salaries for those departments with a maximum salary that is greater than $10000.)

    eg : select job_id, sum(salary) payroll from employees where job_id not like '%rep%' group by job_id having sum(salary) > 13000 order by sum(salary);(displays the job_id and total monthly salary for each job thqt has a total payroll exceeding $13000. the example excludes sales representives and sort the list by the total monthly salary.)

    eg : select max(avg(salary)) from employees group by department_id;(displays the maximum average salary.)

    04 retrieving data from several tables

    displaying data from multiple tables(joins)

    using subqueries to solve queries

    using the set operators

    types of joins : 

    cross joins 

    natural joins

    using clause

    full (or two-sided) outer joins

    arbitrary join conditions for outer joins

    e.g. : select table.column, table2.column from table1 [natural join table2] | [join table2 using (column_name)] | [join table2 on (table1.column_name = table2.column_name)] | [left | right | full outer join table2 on (table1.column_name = table2.column_name)] | [cross join table2];

    注 : table1.column denotes the table and column from which data is retrieved . natural join joins two tables based on the same column name. join table using column_name performs an equijoin based on the column name. join table on table1.clumn_name = table2.column_name performs an equijoin based on the condition in the on clause. left/right/full outer is used to perform outer joins. cross join returns a cartesian product from the two tables.

    qualifying ambitious column names
    use table prefix to qualify column names that are in multiple tables.
    use table prefixes to improve performance.
    use column aliases to distinguish columns that have identical names but reside in different tables.
    do not use aliases on columns that are identified in the using clause and listed elsewhere in the sql statement.

    e.g. : select employees.employee_id,employees.last_name,departments.department_id,departments.location_id from employees join departments on employees.department_id = departments.department_id;

    note : when joining with the using clause,you cannot qualify a column that is used in the using clause it self. furthermore, if that column is used anywhere in the sql statement, you cannot alias it.

    using table aliases : 

    use table aliases to simplify queries

    use table aliases to improve performance.

    e.g. : select e.employee_id,e.last_name,d.location_id,department_id from employees e join departments d using (department_id);

    note : table alias is valid for only the current select statement.

    natural joins

    creating natural joins : 

    the natural join clause is based on all columns in the two tables that have the same name.

    It select rows from the two tables that have equal values in all matched columns.

    If the columns having the same names have different data types, an error is returned.

    You can join tables automatically based on columns in the two tables that have matching data types and names by using the keywords natural join.

    e.g. : select department_id,department_name,location_id,city from departments natural join locations;(the locations table is joined to the departments table by the locationn_id column,which is the onoy column of the same name in both tables. if other common columns were present,the join would have used them all.)

    natural joins with a where clause : 

    e.g. : select department_id,department_name,location_id,city fom departments natural join locations where department_id in (20,50);(limits the rows of output to those with a department id equal to 20 or 50)

    creating joins with the using clause : 

    if several columns have the same names but the data types do not match, the natural join clause can be modified with the using clause to specify the columns that should be used for an equijoin.

    use the using clause to math only one column when more than one column matches.

    do not use a table name or alias in the referenced columns.

    the natural join and using clauses are mutually exclusive.

    e.g. : select l-city,d.department_name from locations l join departments d using (location_id) where location_id = 1400;

    notes : eauijoins are also called simple joins or inner joins.

    e.g. : select employees.employee_id,employees.last_name,departments.location_id,department_id from employees join departments using (department_id);(joins the department_id column in the employees and departments tables, and thus shows the location where an employee works.

    the on clause

    creating joins with the on clause : 

    the join condition for the natural join is basically an equijoin of all columns with the same name.

    use the on clause to specify arbitrary conditions or specify columns to join.

    the join condition is separated from other search conditions.(use the on clause to specify a join condition. this lets you specify join conditions separate from any search or fitter conditions in the where clause.)

    the on class makes code easy to understand.

    e.g. : select e.employee_id,e.last_name,e.department_id,d.department_id,d.location_id from employees e join departments d on (e.department_id = d.department_id);(the department_id columns in the employees and departments table are joined using the on clause. wherever a department id in the employees table equals a department id in the departments table , the row is returned.)

    note : you can also use the on clause to join columns that have different names.

    self-joins using the on clause : 

    e.g. : select e.last_name emp,m.last_name mgr from employees e join employees m on (e.namager_id = m.manager_id);

    note : the on clause can also be used to join columns that have different names, within the same table or in a different table.

    applying additional conditions to a join : 

    e.g. : select e.employee_id,e.last_name,e.department_id,d.department_id,d.location_id from employees e join departments d on (e.department_id = d.department_id) and e.manager_id = 149;(performs a join on the employees and departments tables and in addition, displays only employees who have a manager id of 149.to add additional conditions to the on clause, you can add and clauses. alternatively, you can use a where clause to apply additional conditions.)

    e.g. : select

    e.employee_id,e.last_name,e.department_id,d.department_id,d.location_id from employees e join departments d on (e.department_id = d.department_id) where e.manager_id = 149;

    creating three-way joins with the on clause : 

    e.g. : select employee_id,city,department_name from employees e join departments d on d.department_id = e.department_id join locations l on d.location_id = l.location_id;

    note : a three-way join is a join of three tables. joins are performed from left to right.

    non-equijoins

    e.g. : select e.last_name,e.salary,j.grade_level from employees e join job_grades j on e.salary between j.lowest_sal and j.highest_sal;(creates a non-equijoin to evaluate an employee’s salary grade. the salary must be between any pair of the low and high salary ranges.)

    note : remember to specify the low value first and the high value last when using between.

    outer joins

    inner versus outer joins : 

    in sql : the join of two tables returning only matched rows is called an inner join.

    a join between two tables that returns the result of the inner join as well as the unmatched rows from the left (or right) tables is called a left(or right) outer join.

    a join between two tables that returns the results of an inner join as well as the results of a left and right join is a full outer join.

    left outer join : 

    e.g. : select e.last_name,e.department_id,d.department_name from employees e left outer join departments d on (e.department_id = d.department_id);(retrieves all rows in the employees table, which is the left table even if there is no match in the departments table.)

    right outer join : 

    e.g. : select e.last_name,e.department_id,e.department_name from employees e right outer join departments d on (e.department_id = d.department_id);(retrieves all rows in the departments table, which is the right table even if there is no match in the employees table.)

    full outer join : 

    e.g. : select e.last_name,d.department_id,d.department_name from employees e full outer join departments d on (e.department_id = d.department_id);(retrieves all rows in the departments table, even if there is no match in the employees table. it also retrieves all rows in the employees table, even if there is no match in the departments table.)

    cross joins

    cartesian products : 

    a cartesian product is formed when : (a join condition is omitted/a join condition is invalid/all rows in the first table are joined to all rows in the second table)

    to avoid a cartesian product , always include a valid join condition.

    note : when a join condition is invalid or omitted compiletely, the result is a cartesia product, in which all combinations of rows are displayed,all rows in the first table are joined to all rows in the second table. a cartesian product tends to generate a large number of rows ,and the result is rarely useful. you should always include a valid join condition unless you have a specific need to combine all rows from all tables.

    generating a cartesiann product : 

    e.g. : select last_name,department_name from employees cross join departments;(produces a cartesian product of the employees and departments tables.)

    advanced retrieval

    using subqueries to solve queries

    using the set operators

    hierarchical retruval

    single-row subqueries

    syntax : select select_list from table where expr operator (select select_list from table);

    the subquery (inner query) executes once before the main query (outer query).

    the result of the subquery is used by the main query.

    note : a subquery is a sellct statement that is embedded in a clause if 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).operator includes a comparison condition such as >, =, or in.(comparison conditions fall into two classes : single-row operators(>, =, >=, <, <>, <=) and multiple-row operators (in,all,any).)

    e.g. : select last_name from employees where salary > (select salary from employees where last_name = ‘Abel’);(the inner query determines the salary of employee Abel. the outer query takes the result of the inner query and uses this result to display all the employees who earn more than this amount.)

    guidelines for using subqueries : 

    enclose subqueries in parentheses.

    place subqueries on the right side of the comparison condition.

    the order by clause in the subquery is not needed unless you are performing top-N analysis.

    use single-row operators with single-row subqueries, and use multile-row operators with multiple-row subqueries.

    e.g. : select last_name,job_id from employees where job_id = (select job_id from employees where employee_id = 141);(displays the employees whose job id is the same as that of employee 141.)

    e.g. : select last_name,job_id,salary from employees where job_id = (select job_id from employees where employee_id = 141) and salary > (select salary from employees where employee_id = 143);(displays employees whose job id is the same as that of employee 141 and whose salary is greater than that of employee143.)

    note : the outer and inner queries can get data from different tables.

    using group functions in a subquery : 

    e.g. : select last_name,job_id,salary from employees where salary = (select min(salary) from employees);(displays the employee last name,job id and salary of all employees whose salary is equal to the minimum salary. the min group function returns a single value (2500) to the outer query.)

    the having clause with subqueries : 

    e.g. : select department_id,min(salary) from employees group by department_id having min(salary) > (sellct min(salary) from employees where department_id = 50);(displays all the departments that have a minimum salary greater than that of department 50.)

    e.g. : select job_id,avg(salary) from employees group by job_id having avg(salary) = (select min(avg(salary)) from employees group by job_id);(find the job with the lowest average salary.)

    multiple-row subqueries

    e.g. : select last_name,salary,department_id from employees where salary in (select min(salary) from employees group by department_id);(find the employees who earn the same salary as the minimum salary for each department.)

    using the any operator in multiple-row subqueries :

    e.g. : select employee_id,last_name,job_id,salary from employees where salady < any (select salary from employees where job_id = ‘IT_PROG’) and job_id <> ‘IT_PROG’;(displays employees who are not it programmers and whose salary is less than that of any it programmer.)

    note : the any operator (and its synonym, the some operator) compares a value to each value returned by a subquery.

    using the all operator in multiple-row subqueries : 

    e.g. : select employee_id,last_name,job_id,salary from employees where salary < all (select salary from employees where job_id = ‘IT_PROG’) and job_id <> ‘IT_PROG’;(displays employees whose salary is less than the salary of all employees with a job id of it_prog and whose job is not it_prog

    null values in a subquery : 

    e.g. : select emp.last_name from employs emp where emp.employee_id not in (select mgr.manager_id from employees mgr);(it attempts to display all the employees who do not have any subordinates. logically, this statement should have returned 12 rows. however, the sql statement does not return any rows. one of the values returned by the inner query is a null value, and hence the entire query returns no rows.the reason is that all conditions that compare a null value result in a null. so whenever null values are likely to be part of the results set of a subquery, do not use the not in operator. the not in operator is equivalent to <> all.)

    e.g. : select emp.last_name from employees emp where emp.employee_id in (select mgr.manager_id from employees mgr);(to display the employees who have subordinates.)

    e.g. : select last_name from employees where employee_id not in (select manager_id from employees where manager_id is not null);(alternatively, a where clause can be included in the subquery to display all employees who do not have any subordinates.)

    using the set operators

    union operators

    intersect operator

    minus operator

    the set operators combine the results of two or more component queries into one result. queries containing set operators are called compound queries.

    union (all distinct rows selected by either query)

    e.g. : select employee_id,job_id from employees union select employee_id,job_id from job_history;(display the current and previous job details of all employees.display each employee only once.)

    e.g. : select employee_id,job_id,department_id from employees union select employee_id,job_id,department_id from job_history;

    union all (all rows selected by either query, including all duplicates.)

    e.g. : select employee_id,job_id,department_id from employees union all select employee_id,job_id,department_id from job_history order by employee_id:(display the current and previous departments of all employees.)

    intersect (all distinct rows selected by both queries)

    e.g. : select wmployee_id,job_id from employees intersect select employee_id,job_id from job_history;(display the employee ids and job ids of those employees who currently have a job title that is the same as their job title when they were initially hired (that is , they changer jobs but have now gone back to doing theyr original job.)

    e.g. : select employee_id,job_id,department_id from employees intersect select employee_id,job_id,departmetn_id from job_history;

    minus (all distinct rows that are selected by the first select statement and not selected in the second sellct statement.)

    note : all of the columns in the where clause must be in the select clause for the minus operator to work.

    e.g. : select employee_id,job_id from employees minus select employee_id,job_id from job_history;(display the employee ids of those employees who have not changed their jobs even once.)

    e.g. : select employee_id,department_id from employees where (employee_id,department_id) in (select employee_id,department_id from employees union select employee_id,department_id from job_history);

    guidelines : 

    the expression in the select lists must match in number and data types.

    parentheses can be used to alter the sequence of execution.

    the order by clause can appear only at the very end of the statement and will accept the column name,aliases form the first select statement,or the positional notation.

    duplicate rows are automatically eliminated except in union all.

    column names from the first query appear in the result.

    the output is sorted in ascending order by default except in union all.

    matching the select statements : 

    e.g. : select department_id,to_number(null) location,hire_date from employees union select department_id,location_id,to_date(null) from departments;

    e.g. : select employee_id,job_id,salary from employees union select employee_id,job_id,0 from job_history;

    produce an  english sentence using two union operators.

    e.g. : select ‘sing’ as “My dream”, 3 a_dummy from dual union select ‘I’ ‘d like to teach’, 1 a_dummy from dual union select ‘the world to’,2 a_dummy from dual order by a_dummy;

    hierarchical retrieval

    syntax :

    select [level],column,expr… from table [where condition(s)] [connect by prior comdition(s)];

    where condition : expr comparison_operator expr

    note : hierarchical queries can be identified by the presence of the connect by and start with clauses.

    start with : specifies the root rows of the hierarchy (where to start). this clause is required for a true hierarchical query.

    connect by : specifies the columns in which the relationship between parent and child prior rows exist.. this clauses is required for a hierarchical query.

    start with column1 = value

    connect by prior column1 = column2

    direction : from the bottom up :

    e.g. : select employee_id,last_name,job_id,manager_id from employees start with employee_id = 101 connect by prior manager_id = employee_id;(displays a list of managers starting with the employees whose employee id is 101.)

    direction : from the top down : 

    e.g. : select last_name || NVL2(PRIOR last_name, ‘reports to ‘ || PRIOR last_name, ‘ is the boss’) “Walk Top Down” from employees start with employee_id = 100 connect by prior employee_id = manager_id;(display the names of the employees and their manager. use employee king as the starting point. print only one column.)

    e.g. : select LPAD(last_name, LENGTH(last_name) + 9LEVEL*2) -2, ‘_’) as org_chart from employees start with last_name = ‘king’ connect by prior employee_id = manager_id;(create a report displaying company management levels,beginning with the highest level and indenting cache of the following levels.

    pruning branches : 

    use the where clause to climinate a nod. 

    e.g. : where last_name != ‘Higgins’

    use the connect by clause to eliminate a branch.

    e.g. : connect by prior employee_id = manager_id and last_name != ‘Higgins’

    e.g. : select department_id,employee_id,last_name,job_id,salary form employees where last_name != ‘Higgins’ start with manager_id is null connect by prior employee_id = manager_id;(starting at the root,walk from the top down, and eliminate employee Higgins in the result, but process the child rows.

    select department_id,employee_id,last_name,job_id,salary from employees start with manager_id is null connect by prior employee_id = manager_id and last_name != ‘Higgins’;(starting at the root, walk from the top down, and eliminate employee Higgins and all child rows.)

    manipulating data

    describe each data manipulation language(DML) statement

    insert rows into a table

    update rows into a table

    delete rows in a table

    control transactions

    insert statement

    update statement and default

    delete statement and truncate

    merge statement

    transactions control

    insert statement

    data manipulation language

    a DML statement is executed when you( add new rows in a table / modify existing rows in a table / remove existing rows from a table)

    a transaction consists of a collection of DML statements that form a logical unit of work.

    add new rows to a table by using the insert statement : 

    syntax : insert into table [(column, [column … ])] values (value [,value … ]);

    note : in the syntax, table is the name of the table, column is the name of the column in the table to populate, value is the corresponding value for the column. this statement with the values clause adds only one row at a time to a table.

    inserting new rows

    insert a new row containing values for each column.

    list values in the default order of the columns in the table.

    optionally, list the columns in the insert clause.

    e.g. : insert into departments(department_id,department_name,manager_id,location_id) values (70,’Public Relations’,100,1700);

    enclose character and data values in single quotation marks.

    insert rows with null values

    implicit method : omit the column from the column list.

    e.g. : insert into departments(department_id,department_name  ) values (30,’Purchasing’);

    explicit method : specify the null keyword in the values clause.

    e.g. : insert into departments values(100,’Finance’,null,null);

    inserting special values

    the sysdate function records the current date and time.

    e.g. : insert into employees (employee_id,first_name,last_name,email,phone_number,hire_date,job_id,salary,commission_pct,manager_id,dapartment_id) values (113, ’Louis’, ’Poop’ ‘LPOPP’, ’515.124.4567’, sysdate, ‘AC_ACCOUNT’, 6900, NULL, 205, 100);

    confirming additions to the table

    e.g. : select employee_id,last_name,job_id,hire_date,commission_pct from employees where employee_id = 113;

    the user function records the current username.

    inserting specific date values

    add a new employee

    e.g. : insert into employee values (114, ‘Den’, ‘Raphealy’, ‘DRAPHEAL’, ’515.127.4561’, to_date(‘FEB 3,1999’ ‘MON DD, YYYY’), ‘AC_ACCOUNT’, 11000, NULL, 100, 30);

    create a script

    use & substitution in a sql statement to prompt for values.

    & is a placeholder for the variable value.

    e.g. : insert into departments (department_id, department_name, location_id) values (&department_id,’&department_name’ ,&location);

    note : you can save commands with substitution variables to a file and execute the commands in the file. run the script file and you are prompted for input for each of the & substitution variables. after entering a value for the substitution variable, click the continue button. the values that you input are then substituted into the statement.this enables you to run the same script file over and over but supply a different set of values each time you run it.

    copying rows from another table

    write your insert statement with a subquery :

    syntax : insert into table [column,(column)] subquery;

    e.g. : insert into sales_reps(id,name,salary,commission_pct) select employee_id,last_name,salary,commission_pct from employees where job_id like ‘%REP%’;

    note : do not use the values clause. match the number of columns in the insert clause to those in the subquery.

    e.g. : insert into copy_emp select * from employees;

    update statement and default

    modifying existing rows with the update statement:

    update table set column = value[column = value,…] [where condition]

    eg : update employees set department_id = 70 where employee_id = 113;(specific row or rows are modified if you specify the where clause.)

    e.g. : update copy_emp set department_id = 100;(all rows in the table are modified if you omit the where clause.)

    e.g. : update employees set job_id = (select job_id from employees where employee_id = 205), salary = (select salary from employees where employee_id = 205) where employee_id = 114;(update employee 114’s job and salary to match that of employee 205.)

    note : you can update multiple columns in the set clause of an update statement by writing multiple subqueries.

    syntax: update table set column = (select column from table where condition) [,column = (select column from table where condition)] [where condition];

    updating rows based on another table

    use subqueries in update statement to update rows in a table based on values from another table: 

    e.g. : update copy_emp set department_id = (select department_id from employees where employee_id = 100) where job_id = (select job_id) from employees where employee_id = 200);(updates the copy_emp table based on the values from the employees table.It changes the department number of all employees with employee 200’s job_id to employee 100’s current department number.)

    with the explicit default feature, you can use the default keyword as a column value where the column default is desired.

    this allows the user to control where and when the default value should be applied to data.

    explicit defaults can be used in insert and update statements.

    default with insert :

    e.g. : insert into deptm3 (department_id,department_name,manager_id) values(300,’Enginerring”,default);

    e.g. : update deptm3 set manager_id = default where department_id = 10;

    specify default to set the column to the value previously specified as the default value for the column. If no default value for the corresponding column has been specified, the Oracle server sets the column to null.

    removing a row from a table

    syntax: delete [from] table [where condition];

    note : in the syntax, table is the table name. condition identifies the rows to be deleted and is composed of column names,expressions,constants,subqueries,and comparison operators.

    specific rows are deleted if you specify the where clause :

    e.g. : delete from departments where department_name = ‘Finance’;(deletes the Finance department from the departments table.)

    all rows in the table are deleted if you omit the where cause :

    e.g. : delete from copy_emp;(deletes all rows from the copy_emp table.)

    note : you can confirm the delete operation by displaying the deleted rows using the select statement.

    e.g. : select * from departments where department_name = ‘Finance’;

    e.g. : delete from employees where employee_id = 114;

    e.g. : delete from departments where department_id in (30,40);

    deleting rows based on another table

    use subqueries in delete statements to remove rows from a table based on values from another table:

    e.g. : delete from employees where department_id = (select department_id from departments where department_name like ‘%Public%’);(deletes all the employees who are in a department where the department name contains the string publis. the subquery searches the departments table to find the department number based on the department name containing the string public. the subquery then feeds the department number to the main query, which deletes rows of data from the employees table based on this department number.)

    truncate statement(remove all rows from a table,leaving the table empty and the table structure intact.)

    is a data definition language(DDL) statement rather than a DML statement cannot easily be undone.

    syntax : truncate table table_name;

    e.g. : truncate table copy_emp;

    merge statement

    provides the ability to conditionally update or insert data into a table.

    run an update if the row already exists and an insert if the row does not exist.(avoid separate updates/simplifies use and improve performance/very useful in datawarehouing applications.)

    the merge statement will allow to insert or update into a table on a condition.

    syntax : merge into table_name table_alias using (table | view | sub_query) alias on (join condition) when matched then update set col1 = col1_val, col2 = col2_val when not matchen then insert (column_list) values (column_values);

    insert or update rows in the copy_emp table to match the employee table : 

    e.g. : merge into copy_emp c using employees e on (c.employee_id = e.employee_id) when matched then update set c.first_name = e.first_name, c.last_name = e.last_name,…,c.department_id = e.department_id when not matched then insert values(e.employee_id,e.first_name,e.last_name,e.email,e.phone_number,e.hire_date,e.job_id,e.salary,e.commission_pct,e.manager_id,e.department_id);

    control transactions

    commit and rollback

    database transactions(a database transaction consists of one of the following : DML statements that constitute one consistent change to the data./one DDL statement./one data control language(DCL) statement.)

    transaction type

    data manipulation language (DML)(consists of any number of DML statements that the oracle server treats as a single entity or a logical unit of work.

    data definition language (DDL) (consists of only one DDL statement.

    data control language (DCL) (consists of only one DCL statement.

    database transactions :

    begin when the first DML SQL statement is excited.

    end with one of the following events : (a commit or rollback statement is issued./a DDL or DCL statement excites (automatic commit)./the user exits iSQL*PLUS./the system crashes.)

    after one transaction ends,the next executable SQL statement automatically starts the next transaction.

    a DDL statement or a DCL statement is automatically committed and therefore implicitly ends a transaction.

    advantages of commit and rollback statements ,you can :(ensure data consistency, preview data changes before making changes permanent,group logically related operations)

    commit (ends the current transaction by making all pending data changes permanent.)

    savepoint name (marks a savepoint within the current transaction.)

    rollback (ends the current transaction by discarding all pending data changes.)

    rollback to savepoint_name (rolls back the current transaction to the specified save point, thereby discarding any changes and or save points that were created after the save point to which you are rolling back if you omit the to savepoint clause,the rollback statement rolls back the entire transaction. because save points are logical,there is no way to list the save points that you have created.

    note : save point is not ANSI standard SQL.

    rolling back changes to a marker

    create a marker in a current transaction by using the save point statement.

    roll back to that marker by using the rollback to save point statement.

    update … save point update_done;

    insert rollback to update_done;

    implicit transaction processing

    an automatic commit occurs under the following circumstances : (DDL or DCL statement is issued / normal exit from iSQL*PLUS, without explicitly issuing commit or rollback statements.)

    an automatic rollback occurs under an abnormal termination of iSQL*PLUS or a system failed.

    automatic commit (DDL statement or DCL statement is issued. iSQL*PLUS exited normally,without explicitly issuing commit or rollback commands.)

    automatic rollback (abnormal termination of iSQL*PLUS or system failure.)

    note : a third command is available in iSQL*PLUS. the auto commit command can be toqqled on or off.if set on,each individual DML statement is committed as soon as it is excited.you cannot roll back the changes. if set off, the commit statement can still be issued explicitly. also, the commit statement is issued when a DDL statement is issued or when you exit iSQL*PLUS.

    system failures

    when a transaction is interrupted by a system failure, the entire transaction is automatically rolled back. this prevents the error from causing unwanted changes to the data and returns the tables to their state at the time of the last commit. in this way, the oracle server protects the integrity of the tables.

    from iSQL*PLUS, a normal exit from the session is accomplished by clicking the exit button. with SQL*PLUS, a normal exit is accomplished by typing the command exit at the prompt. closing the window is interpreted as an abnormal exit.

    commit and rollback

    state of the data before commit or rollback : (the previous state of the data can be recovered.

    the current user can review the results of the DML operations by using the select statement.

    other users cannot view the results of the DML statements by the current user.

    the affected rows are locked; other users cannot change the data in the affected rows.)

    note : every data change made during the transaction is temporary until the transaction is committed. the state of the data before commit or rollback statements are issued can be described as follows:(data manipulation operations primaritly affect the database buffer, therefore, the previous state of the data can be recovered. the current user can review the results of the data manipulation operations by querying the tables. other users cannot view the results of the data manipulations made by the current user.the oracle server institutes read consistency to ensure that cache sees data as it existed at the last commit.

    the affected rows are locked; other users cannot change the data in the affected rows.)

    state of the data after commit : (the previous state of the data can be recovered. the current user can review the results of the DML operations by using the select statement. other users cannot view the results of the DML statements by the current user. the affected rows are locked, other users cannot change the data in the affected rows.)

    note : make all pending changes permanent by using the commit statement. here is what happens after a commit statement : (data changes are written to the database. the previous state of the data is no longer available with normal SQL queries. all users can view the results of the transaction. the locks on the affected rows are released; the rows are now available for othe users to perform new data changes. all save points are erased.)

    e.g. : delete from employees where employee_id = 9999;(delete a row from the employees table)

    e.g. : insert into departments values (290, ‘Corporate Tax’, NULL, 1700);(insert a new row into the departments table.)

    e.g. : commit;(make the changes permanent)

    e.g. : delete from departments where department_id in (290,300);

    e.g. : update employees set department_id = 80 where employee_id = 206;

    e.g. : commit;(remove departments 290 and 300 in the departments table, and update a row in the copy_emp table.make the data change permanent.)

    discard all pending changes by using the rollback statement : (data changes are undone. previous state of the data is restored. locks on the affected rows are released.)

    e.g. : delete from copy_emp;

    e.g. : rollback;

    e.g. : while attemptingg to remove a record from the test table you can accidentally empty the table. you can correct the mistake, reissue the proper statement, and make the data change permanent.

    e.g. : delete from test;

    e.g. : rollback;

    e.g. : delete from test where id = 100;

    e.g. : select * from test where id = 100;

    eg : commit;

    statement-level rollback

    if a single DML statement fails during execution, only that statement is rolled back.

    the oracle server implements an implicit save point.

    all other changes are retained.

    the user should terminate transactions explicitly by executing a commit or rollback statement.

    read consistency

    read consistency guarantees a consistent view of the data at all times.

    changes made by one use do not conflict with changes made by another user.

    read consistency ensures that on the same data : (readers do not wait for writers/writers do not wait for readers.)

    creating schema objects

    categorise the main database objects

    review the table structure

    create simple and complex views

    using DDL statements to create and manage tables

    objects and data types

    objects :

    table : stores data,basic unit of storage; composed of rows

    view : logically represents subsets of data from one or more tables.

    sequence : generates numeric values.

    index : improves the performance of some queries.

    synonym : gives alternative names to objects.

    datatypes :

    varchar2(size) : variable-length character data.

    char(size) : fixed-length character data.

    number(p,s) : variable-length numeric data.(p stands for precision and s stands for scale. the precision is the total number of decimal digits, and the scale is the number of digits to the right of the decimal point. the precision can range from 1 to 38, and the scale can range from 84 to 127.)

    data : date and time values.(to the nearest second between January 1,4712 B.C.,and December 31, 9999 A.D.)

    long : variable-length character data(up to 2 GB).

    clog : character data (up to 4 GB).

    raw and long row : raw binary data.

    blob : binary data (up to 4 GB)

    bfile : binary data stored in an external file(up to 4 GB)

    rowid : a base-64 number system representing the unique address of a row in its table.

    note : (a long column is not copied when a table is created using a subquery. a long column cannot be included in a group by or an order by clause. only one long column can be used per table. no constraints can be defined on a long column. you might want to use a clog column rather than a long column.)

    timestamp : variable-length character data

    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.

    e.g. : timestamp[(fractional_seconds_predision)]

    e.g. : timestamp[(fractional_seconds_precision)] with time zone

    e.g. : timestamp[(fractional_seconds_precision)] with local time zone

    note : the timestamp data type is an extension of the data type. It stores the year.month,and day of the date type plus hour,minute,and second values. this data type is used for storing precise time values.

    the fractional_seconds_precision optionally specifies the number of digits in the fractional part of the second date time field and can be a number in the range 0 to 9. the default is 6.

    e.g. : create table new_employees(employee_id number, first_name varchar2(15),last_name varchar2(15),.. start_date timestamp(7),… );(a table is created named new_employees, with a column start_date that has a data type of timestamp.)

    date time data types

    the interval year to month data type stores a period of time using the year and month date time fields:

    e.g. : interval year [(year_precision)] to month

    the interval day to second data type stores a period of time in terms of days,hours,minutes,and seconds:

    e.g. : interval day [(day_precision)] to second [(fractional_seconds_precision)]

    managing tables

    naming rules : (table names and column names : (must begin with a letter. must be 1-30 characters long. must contain only A-Z, a-z, 0-9, _, $, and #. must not duplicate the name of another object owned by the same user. must not be an oracle server reserved word.))

    create table statement

    you must have create table privilege and a storage area.

    e.g. : create table [schema.] table (column datatype [default expr] [,… ]);

    you specify table name and column name,column data type and column size.

    note : schema is the same as the owner’s name. default expr specifies a default if a value is omitted in the insert statement.

    referencing another user’s tables

    tables belonging to other users are not in the user’s schema. 

    you should use the owner’s name as a prefix to those tables.

    e.g. : select * from userB.employees;(for userA)

    e.g. : select * from userA.employees;(for userB)

    schema is a collection of objects. schema objects are the logical structures that directly refer to the data in a database. schema objects include tables, views, synonyms, sequences, stored procedures, index, clusters,and database links.

    default option

    specify a default value for a column during a insert.

    e.g. : … hire_date date default sysdate,…

    literal values, expressions, or SQL functions are legal values.

    another column’s name or a pseudocolumn are illegal values.

    the default data type must match the column data type.

    e.g. : create table hire_dates(id number(8), hire_date date default sysdate);

    create the table.

    e.g. : create table dept (dept no number(2), dame varchar2(14), loc varchar2(13), create_date date default sysdate);

    confirm table creation.

    eg : describe dept

    note : because creating a table is a DDL statement, an automatic commit takes place when this statement is executed.

    alter table statement

    use the alter table statement to : (add a new column./modify an existing column./define a default value for the new column./drop a column.)

    dropping a table

    all table and structure in the table are deleted.

    any pending transactions are committed.

    all indexes are dropped.

    all constraints are dropped.

    you cannot roll back the drop table statement.

    e.g. : drop table dept8;

    note : the drop table statement, once executed, is irreversible(不可逆的).as with all DDL statements, drop table is committed automatically.

    advanced creation

    creating a table by using a subquery

    syntax. : 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.

    e.g. : create table dept80 as select employee_id, last_name, salary*12 ANNSAL, hire_date from employees where department_id = 80;(creates a table named dept80,which contains details of all the employees working in department 80.)

    note : be sure to provide a column alias when selecting an expression.

    constraints

    including constraints

    constraints enforce rules at the table level.

    constraints prevent the deletion of a table if there are dependencies.

    the following constraints types are valid : 

    not null : specifies that the column cannot contain a null value.

    unique : specifies a column or combination of columns whose values must be unique for all rows in the table.

    primary key : uniquely identifies each row of the table.

    foreign key : establishes and enforces a foreign key relationship between the column and a column of the referenced table.

    check : specifies a conditio that must be true.

    constraints guidelines

    you can name a constraint or the oracle server generates a name by using the SYS_Cn format.

    create a constraint at either of the following times : (at the same time as the table is created./ after the table has been created.)

    define a constraint at the column or table level.

    view a constraint in the data dictionary.

    defining constraints

    syntax :

    create table [schema.]table (column datatype [default expr] [column_constraint], … [table_constraint] [,…]);

    column-level constraint :

    syntax : column [constraint constraint_name] constraint_type,

    e.g. : create table employees(employee_id number(6) constraint emp_emp_id_pk primary key, forst_name varchar2(20), … );

    table-level constraint : 

    syntax : column, … [constraint constraint_name] constriant_type (column,…),

    e.g. : create table employees(employee_id number(6),first_name varchar2(20), … job_id varchar2(20) not null, constraint emp_emp_id_pk primary key (employee_id));

    note : 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.

    not null 

    not null constraint(ensures that null values are not permitted for the column : 

    unique

    unique constraint(requires that every value in a column or set of columns(key) be unique. that is, no two rows of a table can have duplicate values in a specified column or set of columns.

    e.g. : create table employees (employee_id number(6), last)name varchar2(25) not null, email varchar2(25), salary number(8,2), commission_pct number(2,2), hire_date date not null, … constraint emp_email_uk unique(email);

    primary key

    primary key constraint(unique and not null)

    foreign key

    foreign key constraint

    note : a foreign key value must match an existing value in the parent table or be null.

    foreign keys are based on data values and are purely logical, rather than physical,pointers.

    e.g. : create table employees(employee_id number(6),last_name varchar2(25) not null, email varchar2(25), salary number(8,2), commission_pct number(2,2), hire_date date not null, … department_id number(4), constraint emp_dept_fk foreign key(department_id) references departments(department_id), constraint emp_email_uk unique)email));

    foreign key constraint : keywords

    foreign key : defines the column in the child table at the table_constraint level.

    references : identifies the table and column in the parent table.

    on delete cascade : deletes the dependent rows in the child table when a row in the parent table is deleted.

    on delete set null : converts dependent foreign key values to null.

    check

    check constraint

    defines a condition that each row must satisfy.

    the following expression are not allowed : (references to curial,nextval,level,and rownum pseudocolumns./calls to sysdate, hid,user,and userenv functions./queries that refer to other values in other rows.)

    e.g. : … , salary number(2) constraint emp_salary_min check (salary > 0), …

    e.g. : create table employees (… salary number(8,2) constraint emp_salary_min check (salary > 0), … 

    how to use

    e.g. : create table employees(employee_id number(6) constraint emp_employee_id primary key, first_name varchar2(20),last_name varchar2(25) constraint emp_last_name_nn not null, email varchar2(25) constraint emp_email_nn not null constraint emp_email_uk unique, phone_number varchar2(20), hire_date date constraint emp_hire_date_nn not null, job_id constraint emp_job_nn not null, salary number(8,2) constraint emp_salary_ck check (salary > 0), commission_pct number(2,2), manager_id number(6), department_id number(4) constraint emp_dept_fk references departments(department_id));

    violating constraints

    e.g. : update employees set department_id = 55 where department_id = 110;(department 545 does not exist in the parent table departments , so you receive the parent key violation ora-02291.)

    you cannot delete a row that contains a primary key that is used as a foreign key in another table.

    e.g. : delete from departments where department_id = 60;(tries to delete department 60 from the departments table, but it results in an error because that department number is used as a foreign key in the employees table. If the parent record that you attempt to delete has child records, then you receive the child record found violation ora-02292.)

    creating other schema objects

    views

    sequences

    indexes

    synonyms

    managing objects with data dictionary views.

     views

    a view is a logical table based on a table or another view. a view contains no data of it’s own but is like a window through which data from tables can be viewed or changed. the tables on which a view is based are called base tables. the view is stored as a select statement in the data dictionary.

    advantages of views : (to restrict data access/to make complex queries easy/to provide data independence/to present different views of the same data.)

    a simple view is one that : (derives data form only one table./contains no functions or groups of data. /can perform DML operations through the view.)

    a complex view is one that : (derives data from many tables./contains functions or groups of data./does not always allow DML operations through the view.)

    creating a view 

    syntax : create [or replace] [force | noforce] view view [(alias [,alias]…)] as subquery [with check option [constraint constraint] [with read only [constraint constraint]];

    note : force means create the view regardless of whether or not the base tables exists. no force means creates the view only if the base table exist (this is the default.). with check option specifies that only those rows that are accessible to the view can be inserted or updated. with read only ensures that no DML operations can be performed on this view.

    e.g. : create view empvu80 as select employee_id,last_name,salary from employees where department_id = 80;(crewte empvu80 view, which contains details of employees in department 80.)

    e.g. : describe empvu80(describe the structure of the view.)

    create a view by using column aliases in the subquery :

    e.g. : create view salvu50 as select employee_id ID_NUMBER, last_name NAME, salary*12 ANN_SALARY from employees where department_id = 50;

    e.g. : create or replace view salvu50(ID_NUMBER, NAME, ANN_SALARY) as select employee_id, last_name, salary*12 from employees where department_id = 50;

    retrieving data form a view

    e.g. : select * from salvu50;

    modifying a view

    e.g. : create or replace view empvu80 (id_number, name, sal, department_id) as select employee_id, first_name || ‘ ‘ || last_name, salary, departmetn_id from employees where department_id = 80;(modify the empvu80 view by using a create or replace view clause. add an alias for each column name .)

    e.g. : create or replace viewdept_sum_vu (name, minsal, maxsal, avgsal) as select d.deaprtment_name, min(e.salary), max(e.salary), avg(e.salary) from employees e join departments d on (e.department_id = d.department_id) group by d.department_name;(create a complex view that contains group functions to display values from two tables.)

    rules for performing DML operations on a view : (you can usually perform DML operations on simple views. you cannot remove a row if the view contains the following : (group functions / a group by clause / the distinct keyword / the pseudo column row num key word.) you cannot modify data in a view if it contains : (group functions / a group by clause/ the distinct keyword / the pseudo column rownum keyword/columns defined by expressions) you cannot add data through a view if the view includes : (group functions/a group by clause/the distinct keyword/the pseudo column rownum keyword/columns defined by expressions/not null columns in the base tables that are not selected by the view))

    using the with check option clause

    e.g. : cease or replace view empvu20 as select * from employees where department_id = 20 with check option constraint empvu20_ck;(ensure that DML operation performed on the view stay in the domain of the view by using the with check option clause.)

    any attempt to change the department number for any row in the view fails because it violates the with check option constraint.

    denying DML operations

    you can ensure that no DML operations occur by adding the with read only option to your view definition.

    any attempt to perform a DML operation on any row in the view results in anORacle server error.

    e.g. : create or replace view empvu10 (employee_number, employee_name, job_title ) as select employee_id, last_name, job_id from employees where department_id = 1- with read only;

    removing a view 

    syntax : drop view view;

    e.g. : drop view empvu80;

    note dropping views has no effect on the tables on which the view was based.

    sequences

    a sequence : (can automatically generate unique numbers/is a sharable object/can be used to create a primary key value/replaces application code/speeds up the efficiency of accessing sequence values when cached in memory.)

    create sequence statement

    syntax : create sequence sequence [increment by n] [start with n] [{maxvalue n | nomaxvalue}] [{minvalue n | nominvalue}] [{cycle | nocycle}] {{cache n | nocache}];

    e.g. : create sequence dept_deptid_sep increment by 10 start with 120 maxvalue 9999 nocache nocycle;

    nextval and currval pseudocolumns

    nextval returns the next available sequence value. it returns a nuibue value every time it is referenced, even for different users.

    curial obtains the current sequence value. nextval must be issueed for that sequence before curial contains a value.

    using a sequence 

    e.g. : insert into departments)department_id, department_name, location_id) values (dept_deptid_seq.nextval, ’Support’, 2500);(insert a new department named ‘support’ in location ID 2500.)

    e.g. : select dept_dept_id_seq.currval from dual;(view the current value for the dept_deptid_seq sequence.)

    caching sequence values

    caching sequence values in memory gives faster access to those values.

    gaps in sequence values can occur when : (a rollback occurs/the system crashes/a sequence is used in another table)

    modifying a sequence

    e.g. : alter sequence dept_deptid_seq increment by 20 maxvalue 999999 nocache nocycle;(change the increment value, maximum value, minimum value, cycle option, or cache option.)

    guidelines for modifying a sequence :

    you must be the owner or have the alter privilege for the sequence.

    only future sequence numbers are affected.

    the sequence must be dropped and re-created to restart the sequence at a different number.

    some validation is performed.

    to remove a sequence, use the drop statement:

    e.g. : drop sequence dept_deptid_seq;

    indexed

    an index : (is a schema object. /can be used by the oracle server to speed up the retrieval of rows by using a pointer/can reduce disk I/O by using a rapid path access method to locate data quickly/is indepentedt of the table that it indexed/is used and maintained automatically by the oracle server)

    automatically(unique) : a unique index is created automatically when you define a primary key or unique constraint in a table definition.

    manually(nonunique) :users can create non unique indexed on columns to speed up access to the rows.

    creating an index

    syntax : create index index on table (column, […column]);(create an index on one or more columns.)

    e.g. : create index emp_last_name_idx on employees(last_name);(improve the speed of query access to the last_name column in the employees table.)

    index creation guidelines 

    create an index when : (a column contains a wide range of values/a column contains a large number of null values/one or more columns are frequently user together in a where clause or a join condition/the table is large and most queries are expectted to retrieve less than 2% to 4% of the rows in the table.)

    removint an index

    syntax : drop index index;(remove an index from the data dictionary by using the drop index command.)

    e.g. : drop index emp_last)name_idx;(remove the upper_last_name_idx index from the data dictionary.)

    note : you cannot modify indexes. to change an index, you must drop it and then re-create it.to drop an index, you must be the owner of the index or have the drop any index privilege. if you drop a table, indexes and constraints are automatically dropped but views and sequences remain.

    synonyms

    simplify access to objects by creation a synonym(another name for an object). with synonyms, you can : (create an easier reference to a table that is owned by another user/shorten lengthy object names.)

    syntax : create [public] synonym synonym for object;

    creating and removing synonyms

    e.g. : create synonym d_sum for dept_sum_vu;(create a shortened name for the dept_sum_vu view.)

    e.g. : drop synonym d_sum;(drop a synonym.)

    managing objects with data dictionary views

    view naming convention

    user :(user’s view(what is in your schema;what you own)

    all :(expanded user’s view(what you can access)

    dab : (database administrator’s view(what is in everyone’s schemas)

    v$ : (performance-related data)

    how to use the dictionary views

    start with dictionary.it contains the names and descriptions of the dictionary tables and views.

    eg : describe dictionary

    e.g. : select * from dictionary where table_name = ‘USER_OBJECTS’;(enclose character and date values in single quotation marks.)

    note : the names in the data dictionary are uppercase.

    user_objects : (query user_objects to see all of the objects that are owned by you/ is a useful way to obtain a listing of all object names and types in your schema, plus the following info. : (date created/date of last modification/status(valid or invalid)))

    all_objects views : (query all_objects to see all objects to which you have access.)

    e.g. : select object_name, object_type, created, status from user_objects order by object_type;(shows the names, types, dates of creation, and status of all objects that are owned by this user.)

    note : for a simplified query and output, you can query the cat view, this view contains only two columns (table_name,and table_type.)it provides the names of all your index,table,cluster,view,synonym,sequence,or undefined objects.

    e.g. : describe user_tables

    e.g. : select table_name from user_tables;

    note : the tabs view is a synonym of the user_tables view. you can query it to see a listing of tables that you own. e.g. : select table_name from tabs;)

    e.g. : describe user_tab_columns

    e.g. : select column_name, datat_ype, data_length, data_precision, data_scale, nullable from user_tav_columns where table_name = ‘EMPLOYEES’;

    constraint info.

    user_constraints describe the constraint definitions on your tables.

    user_cons_columns describe columns that are owned by you and that are specified in constraints.

    e.g. : select constraint_name, constraint_type, search_condition, r_constraint_name, delete_rule, status from user_constraints where table_name = ‘EMPLOYEES’;(the user constraints view is queried to find the names, types, check conditions, name of the unique constraint that the foreign key references, deletion rule for a foreign keym and status for constraints on the employees table.

    note : the constraint_type can be : (C : (check constraint on a table)/P : (primary key) U : (unique key) R : (referential integrity) V : (with check option, on a view) O : (with read_only, on a view).) the delete_rule can be : (cascade : if the parent record id deleted, the child records are deleted too. no action : a parent record can be deleted only if no child records exist.)  the status can be : (enabled : constraint is active. disabled : constraint is made not active.)

    constraint info.

    e.g. : describe user_cons_columns

    e.g. : select constraint_name, column_name from user_cons_columns where table_name = ‘EMPLOYEES’;

    view info.

    e.g. : describe user_views

    e.g. : select distinct view_name from user_views;

    e.g. : select text from user_views where view_name = ‘EMP_DETAILS_VIEW’;

    sequence info.

    e.g. : describe user_sequences

    e.g. : select sequence_name, min_value, max_value, increment_by, last_number from user_sequences;

    synonym info.

    e.g. : describe user_synonyms

    e.g. : select * form user synonyms;

    adding comments to a table

    you can add comments to a table or column by using the comment statement

    e.g.: comment on table employees IS ‘Employee Information’;

    comments can be viewed through the data dictionary views : (ALL_COL_COMMENTS/USER_COL_COMMENTS/ALL_TAB_COMMENTS/USER_TAB_COMMENTS)

    note : you can drop a comment from the database by setting it to empty string (‘ ‘)

    e.g. : comment on table employees is ‘ ‘;

    controlling user access

    differentiate system privileges from object privileges

    grant or revoke accesses to users

    controlling user access

    presentation

    system provileges

    managing users

    object privileges

    roles

    with oracle server database security, you can do the following : (control database access/give accesses to specific objects in the database/confirm given and received privileges with the oracle data dictionary/create synonyms for database objects)

    privileges 

    database security(system security/data security)

    system privileges : gaining access to the database

    more than 100 privileges are available

    the database administrator has high-level system privileges for task such as : (creating new users/removing users/removing tables/backing up tables)

    e.g. : create user (grantee can create other oracle users.)

    e.g. : drop user (grantee can drop another user.)

    e.g. : drop any table (grantee can drop a table in any schema.)

    e.g. : backup any table (grantee can back up any table in any schema with the export utility.)

    e.g. :select any table (grantee can query tables,view, or materialised views in any schema.)

    e.g. : create any table (grantee can create tables in any schema.)

    user system privileges

    after a user is created, the dab can grant specific system privileges to that user.

    syntax : grant privilege [,privilege …] to user [,user | role. public …];

    an application developer, for example, may have the following system privileges : (create session/create table/create sequence/create view/create procedure)

    create session : connect to the database

    create table : create a sequence in the user’s schema

    create sequence : create a sequence in the user’s schema

    create view : create a view in the user’s schema

    create procedure : create a stored procedure, function, or package in the user’s schema

    note : in the syntax, public designates that every user is granted the privilege. current system privileges can be found in the session_privs dictionary view.

    granting system privileges

    the dab can grant specific system privileges to a user.

    e.g. : grant create session, create table, create sequence, create view to scott;(user scott has been assigned the privileges to create sessions, tables, sequences, and views.)

    confirming privileges granted

    user_sys_privs : system privileges granted to the user

    note : you can access the data dictionary to view the privileges that you have.

    managing users

    the dab creates users with the create user statement

    syntax : create user user identified by password;

    e.g. : create user hr identified by hr;

    changing your password

    the dab creates your user account and initialises your password.

    you ca change you password by using the alter user statement.

    e.g. : alter user hr identified by employ;

    note : you must have the alter user privilege to change any other option.

    object privileges : manipulating the content of the database objects

    an object privilege is a privilege or right to perform a particular action on a specific table, view, sequence, or procedure. each object has a particular set of grantable privileges.

    note : for table, there are 7 privileges : (alter, delete, index, insert, reference, select, update) for view, there are 4 privileges : (delete, insert, select, update). for sequence, there are 2 privileges : (alter, select). for procedure, you can only execute. a privilege granted on a synonym is converted to a privilege on the base table referenced by synonym.

    object privileges vary from object to object.

    an owner has all the privileges on the object.

    an owner can give specific privileges on that owner’s object.

    syntax : grant object_priv [(columns)] on object to {user | role | public} [with grant option];

    note : if the grant includes with grant option, then the grantee can further grant the object privilege to other users. otherwise, the grantee can user the privilege but cannot grant it to other users.

    granting object privileges 

    e.g. : grant select on employees to sue, rich;(grant query privileges on the employees table. grants user Sue and Rich the privilege to query your employees table.)

    e.g. : grant update (department_name, location_id) on departments to scott, manager;(grant privileges to update specific columns to users and roles. grants update privileges on specific columns in the departments table to Scott and to the manager role.)

    passing on your privileges 

    gives a user authority to pass along privileges

    e.g. : grant select, insert on departments to scott with grant option;(gives user Scott access to your departments table with the privileges to query the table and add rows to the table, also grants the user Scott the right to give others these privileges.)

    e.g. : grant select on alice.departments to public;(allows all users on the system to query data from alice’s departments table.)

    confirming privileges granted

    data dictionary view

    user_tab_privs_made : object privileges granted on the user’s objects.

    user_tab_privs_recd : object privileges granted to the user.

    user_col_privs_made : objects privileges granted on the columns of the user’s objects

    user_col_privs_recd : objects privileges granted to the user on specific columns.

    revoking privileges

    you use the revoke statement to revoke privileges granted to other users.

    privileges granted to others through the with grant option clause are also revoked.

    syntax : revoke {privilege [,privilege …] | all} on object from {user [,user …] | role | public} [cascade constraints];

    note : in the syntax, cascade is required to remove any referential integrity constraints made to the constraints object by means of the references privilege. if a user were to leave the company and you revoke his privileges, you must re-grant any privileges that this user may have granted to other users. if you drop the user account without revoking privileges from it, then the system privileges granted by this user to other users are not affected by this action.

    e.g. : revoke select, insert on department from scott;(as user Alice, revoke the select and insert privileges given to user Scott on the departments table.)

    schemas : collection of objects such as tables,views,and sequences

    role

    a role is a named group of related privileges that can be granted to the user. this method makes it easier to revoke and maintain privileges.

    a user can have access to several roles, and several users can be assigned the same role. roles are typically created for a database application.

    syntax : create role role;

    after the role is created, the dab can use the grant statement to assign the role to users as well as assign privileges to the role.

    roles

    creating the role

    e.g. : create role manager;(creates a manager role.)

    e.g. : grant create table, create view to manager;(enables managers to create tables and views.)

    e.g. : grant manager to de_haan, kochhar;(grants De Haan and Kochaar the role of managers.)

    confirming privileges granted

    data dictionary view

    role_sys_privs : system privileges granted to roles.

    role_tab_privs : table privileges granted to roles.

    user_role_privs : roles accessible by the user.

    manage schema objects

    drop columns and set column unused

    add constraints

    create indexes

    create indexes using the create table statement

    create function-based indexes

    create and use external tables

    altering a table

    adding a column(using the add clause)

    syntax : alter table table add (column datatype [default expr] [,column datatype]…);

    e.g. : alter table dept80 add (job_id varchar2(9);(adds a column named job_id to the dept80 table.)

    the new column becomes the last column.

    modifying a column

    you can change a column’s data type,size, and default value with the modify clause.

    syntax : alter table table modify (column datatype [default expr] [,column datatype]…);

    e.g. : alter table dept80 modify (last_name varhar2(30));

    a change to the default value affects only subsequent insertion to the table.

    dropping a column

    use the drop column clause to drop columns you no longer need from the table.

    syntax : alter table table drop column (column);

    e.g. : alter table dept80 drop column job_id;

    the set unused option

    you use the set unused option to mark one or more columns as unused.

    syntax : alter table table_name set unused (column_name);

    syntax : alter table table_name set unused column column_name;

    you use the drop unused solumns option to remove the columns that are marked as unused.

    syntax : alter table table_name drop unused columns;

    note : set unused information is stored in the user_unused-col_tabs dictionary view.

    e.g. : alter table dept80 set unused(last_name);

    e.g. : alter table dept80 drop unused columns;

    managing constraints

    adding a constraint

    syntax : alter table table_name add [constraint constraint_name] type (column_name);

    e.g. : alter table emp2 modify employee_id primary key;(modifies the emp2 table to add a primary key constraint on the employee_id column.)

    e.g. : alter table emp2 add constraint emp_mgr_fk foreign key(manager_id) references emp2(employee_id);(creates a foreign key constraint on the emp2 table. the constraint ensures that a manager exists as a valid employee in the emp2 table.)

    on delete cascade

    delete child rows when a parent key is deleted.

    e.g. : alter table emp2 add constraint emp_dt_fk foreign key (department_id_ references departments on delete cascade;

    deferring constraints

    constraints can have the following attributes : (deferrable or not deferrable/initially deferred or initially immediate.)

    e.g. : alter table dept2 add constraint dept2_id_pk primary key (department_id) deferrable initially deferred ;(deferring constraint on creation)

    e.g. : set constraint dept2_id_pk immediate;(change a specific constraint attribute)

    e.g. : alter session set constraints = immediate;(changing all constraints fro a session)

    note : you can defer checking constraints for validity until the end of the transaction. a constraint is deferred if the system checks that it is satisfied only on commit. if a deferred constraint is violated, then commit causes the transaction to roll back. if a constraint is immediate(not deferred), the it is checked at the end of each statement, if it is violated, the statement is rolled back immediately. if a constraint causes an action(for example, delete cascade), that action is always taken as part of the statement that caused it, whether the constraint is deferred or immediate. use the set constraints statement to specify, for a particular transaction, whether a deferrable constraint is checked following each DML statement or when the transaction is committed. in order to create deferrable constraints, you must create a non uniqueindex for that constraint. you can define constraint as either deferrable or not deferrable, and either initially deferred or initially immediate. these attributes can be different for each constraint. 

    dropping a constraint

    e.g. : alter table emp2 drop constraint emp_mgr_fk;(remove the manager constraint from the emp2 table.)

    e.g. : alter table dept2 drop primary kay cascade;(remove the primary key constraint on the dept2 table and drop the associated foreign key constraint on the emp2.department_id column.)

    note : to drop a constraint, you can identify the constraint name from the user_constraints and user_cons_columns data dictionary views. the use the alter table statement with the drop clause. the cascade option of drop clause causes any dependent constraints also to be dropped.

    activating a constraint

    disabling constraints

    execute the disable clause of the alter table statement to deactivate an integrity constraint.

    apply the cascade option to disable dependent integrity constraints.

    eg : alter table emp2 disable constraint emp_de_fk;

    note : you can use the disable clause in both the crdate table statement and the alter table statement. the cascade clause disables dependent integrity constraints. disabling a unique or primary key constraint removes the unique index.

    enabling constraints

    activate an integrity constraint currently disabled in the table definition by using the enable clause.

    syntax : alter table table_name enable constraint constraint_name;

    eg : alter table emp2 enable constraint emp_dt_fk;

    a unique index is automatically created if you enable a unique key or primary key constraint.

    note : enabling a primary key constraint that was disabled with the cascade option does not enable any foreign keys that are dependent on the primary key. to enable a unique or primary key constraint, you must have the privileges necessary to create an index on the table.

    cascading constraints

    the cascade constraint constraints clause is used along with the drop column clause.

    the cascade constraints clause drops all referential integrity constraints that refer to the primary and unique keys defined on the dropped columns.

    the cascade constraints clause also drops all multicolumn constraints defined on the dropped columns.

    e.g. : alter table emp2 drop column employee_id cascade constraints;

    if all columns fererenced by the constraints defined on the dropped columns are also dropped, then cascade constraints is not required.

    e.g. : alter table test1 drop (pk, fk, col1);

    managing indexes

    creating an index

    automatically : (primary key creation/unique key creation)

    manually : (create index statement/create table statement)

    e.g. : create table new_emp (employee_id number(6) primary key using index (create index emp_id_idx on new_emp(employee_id)), first_name varchar2(20), last_name varchar2(25));

    e.g. : select index_name, table_name from user_index where table_name = ‘NEW_EMP’;

    e.g. : create table emp_unnamed_index (employee_id number(6) primary key, first_name  varchar2(20), last_name varchar2(25);

    e.g. : select index_name, table_name from user_indexes where table_name = ‘EMP_UNNAMED_INDEX’;

    step 1 : creating the table

    e.g. : create table new_emp2 (employee_id number(6), first_name varchar2(20), last_name varchar2(25));

    step 2 : create the index

    e.g. : create index emp_id_idx2 on new_emp2(employee_id);

    step 3  : create the primary key

    e.g. : alter table new_emp2 add primary key (employee_id) using index emp_id_idx2;

    function-based indexes

    a function-based index is based on expressions.

    the index expression is built from columns, constraints, SQL functions, and user-defined functions.

    e.g. : create index upper_dept_name_idx on dept2(upper(department_name));

    e.g. : select * from dept2 where upper(department_name) = ‘SALES’;

    note : function-based indexes defined with the OPPER(column_name or LOWER(column_name) keywords allow case-insensitive searches. 

    e.g. : create index upper_last_name_idx on emp2 (upper(last_name));

    e.g. : select * from emp2 where upper(last_name) = ‘KING’;

    e.g. : select * from employees where upper(last_name) is not null order by upper(last_name);

    removing an index

    remove an index from the data dictionary by using the drop index command.

    syntax : drop index index;

    remove the upper_dept_name_idx index from the data dictionary.

    e.g. : drop index upper_dept_name_idx;

    to drop an index, you must be the owner of the index or have the drop any index privilege.

    note : you cannot modify indexes. to change an index, you must frop it and then re-create it. remove an index definition from the data dictionary by issuing the drop index statement. 

    external tables

    advanced manipulations

    manipulate data using subqueries

    describe the features of multitable inserts

    use the following types of multitable inserts : (unconditional insert/pivoting insert/conditional all insert/conditional first insert)

    merge rows in a table

    track the changes to data over a period of time

    manipulating data using subqueries

    retrieving data with a subquery as source

    e.g. : select a.last_name, a.salary, a.department_id, b.salavg from employees a, (select departmetn_id avg(salary) salavg from employees group by department_id) b where a.department_id = b.department_id and a.salary > b.salavg;(displays employee last names, salaries, department numbers, and average salaries for all the employees who earn more than the average salary in their department. the subquery in the from clause is named b, and the outer query references the salavg column using this alias.

    note : you can use a subquery in the from clause of a select statement, which is very similar to how views are used. a subquery in the from clause of a select statement is also called an inline view. a subquery in the from clause of a select statement defines a data source for that particular select statement, and only that select statement,

    copying rows from another table

    write your insert statement with a subquery.(you use a subquery in place of the values clause.)

    syntax : insert into table [column, (column)] subquery;

    e.g. : insert into sales_reps(id, name, salary, commission_pct) select employee_id, last_name, salary, commission_pct from employees where job_id like ‘%REP%’;

    do not use the values clause.

    to create a copy of the rows of a table, use select * in the subquery.

    e.g. : insert into empl3 select * from employees;

    match the number of columns in the insert clause with that in the subquery.

    inserting using a subquery as a target

    e.g. : insert into (select employee_id, last_name, email, hire_date, job_id, salary, department_id from emp13 where department_id = 50) values (99999,’Taylor’, ‘DTAYLOR’, to_date(’07-JUN-99’, ‘DD-MON-RR’), ’ST_CLERK’, 5000, 50);

    note : you can use a subquery in place of the table name in the into clause of the insert statement. this application of subqueries helps avoid having to create a view just for performing an insert.

    verify the result

    e.g. : select employee_id, alst_name, email, hire_date, job_id, salary, department_id from employees where department_id = 50;

    updating rows based on another table

    e.g. : update emp13 set department_id = (select department_id from employees where employee_id = 100) where job_id = (select job_id from employees where employee_id = 200);(use subqueries in update statements to update rows in a table based on values from another table. updates the empl3 table based on the values from the employees table. it changes the department number of all employees with employee 200’s job id to employee 100’s current department number.)

    e.g. : update empl3 set job_id = (select job_id from employees where employee_id = 205), salary = (select salary from empoyees where employee_id = 168) where employee_id = 114;(update the job and salary of employee 112 to match the job of employee 205 and salary of employee 168.)

    deleting rows based on another table

    e.g. : delete from empl3 where department_id = (select department_id from departments where departmetn_name like’%Public%’);(deletes all the employees who are in a department where the department name contains the string ‘Public’. )

    using the with check option keyword

    a subquery is used to identify the table and columns of the DML statement.

    the with check option keyword prohibits you from changing rows that are not in the subquey.

    e.g. : insert into (select employee_id, last_name, email, hire_date, job_id, salary from empl3 where department_id = 50 with check option values (99998, ’Smith, ‘JSMITH’, to_date(’07-JUN-99’, ‘DD-MON-RR’), ’ST_CLERK’, 5000);(returns error.)

    multitable inserts

    insert all

    syntax : insert all into table_a values(…,…,…) into table_b values(…,…,…) into table_c values(…,…,…) select … from sourcetab where …;

    the insert …select statement can be used to insert rows into multiple tables as part of a single DML statement.

    multiple insert statements can be used in data warehousing systems to transfer data from one or more operational sources to a set of a target tables.

    they provide significant performance improvement over : (single DML versus multiple insert … select statements./single DML versus a procedure to do multiple inserts using IF…THEN syntax.)

    syntax : insert [all] [conditional_insert_clause] [insert_into_clause values_clause] (subquery)

    conditional insert clause syntax : 

    [all] [first] [when condition then] [insert_into_clause values_clause] [else] [insert_into_clause values_clause]

    e.g. : insert all into sal_history values(empid,hiredate,sal) into mgr_history values(empid,mgr,sal) select employee_id empid, hire_date hiredate, salary sal, manager_id mgr from employees where employee_id > 200;(select the employee_id, hire_date, salary, and manager_id values from the employees table for those employees whose empoyee_id is greater than 200. inserts rows into both the sal_history and the mgr_history tables.)

    conditional

    select the employee_id, hire_date, salary, and manager_id values from the employees table for those employees whose employee_id is greater than 200.

    if the salary is greater than $10000, insert these values into the sal_history table using a conditional multi table insert statement.

    if the manager_id is greater than 200, insert these values into the ngr_history table using a conditional multitable insert statement.

    eg : insert all when sal > 10000 then into sal_history values(empid,hiredate,sal) when mgr > 200 then into mgr_history values(empid,mgr,sal) select employee_id empid, hire_date hiredate, salary sal, manager_id mgr from employees where employee_id > 200;

    insert first

    conditional 

    select the department_id, sum(salary), and max(hire_date) from the employees table.

    if the sum(salary) is greater than $25000, then insert these values into the special_sal, using a conditional first multitable insert.

    if the first when clause evaluates to true, then the subsequent when clause for this row should be skipped.

    for the rows that do not satisfy the first when condition, insert into the hiredate_history_00, hiredate_history_99, or hiredate_history tables, based on the value in the hire_date column using a conditional multitable insert.

    e.g. : insert first when sal > 25000 then into special_sal values(dept,sal) when hiredate like (‘500%’) then into hiredate_history_00 values(dept,hiredate) when hiredate like (‘%99%’) then into hiredate_history_99 values(deptid,hiredate) else into hiredate_history values(deptid, hiredate) select department_id deptid, sum(salary) sal, max(hire_date) hiredate from employees group by department_id;

    pivoting insert

    suppose you receive a set of sales records from a non relational database table, sales_source_data, in the following format : employee_id, week_id, sales_mon, sales_tue, sales_wed, sales_thur, sales_fri.

    you want to store these records in the sales_info table in a more typical relational format : employee_id, week, sales.

    using a pivoting insert, convert the set of sales records from the nonrelational database table to relational format.

    e.g. : insert all into sales_info values(employee_id, week_id, sales_mon) into sales_info values(employee_id, week_id, sales_tue) into sales_info values(employee_id, week_id, sales_wed) into sales_info values(employee_id, week_id, sales_thur) into sales_info values(employee_id, week_id, sales_fri) select employee_id, week_id, sales_mon, sales_tue, sales_wed, sales_thur, sales_fri from sales_source_data;

    e.g. : desc sales_source_data

    the merge statement (merge)

    provides the ability to conditionally update or insert data into a database table.

    performs an update if the row exists, and an insert if it is a new row : (avoids separate updates/increases performed and ease of use./is useful in data warehousing applications.)

    syntax : merge into table_name table_alias using (table | view | sub_query) alias on (join condition) wen matched then update set col1 = col1_val, col2 = col2_val when not matched then insert (column_list) values (column_values);

    e.g. : merge into emp13 c using employees e on (c.employee_id = e.employee_id) when matched then update set c.first_name = e.first_name, c.last_name = e.last_name, … , c.department_id = e.department_id when not matched then insert values (e.employee_id, e.first_name, e.last_name, e.email, e.phone_number, e.hire_date, e.job_id, e.salary, e.commission_pct, e.manager_id, e.department_id);(matches the emloyee_id in the empl3 table to the employee_id in the employees table.if a match is found, the row in the empl3 table is updated to match the row in the employees table. if the row is not found, it is inserted into the empl3 table.)

    e.g. : merge into empl3 c using employees e on (c.employee_id = e.employee_id) when matched then update set c.first_name = e.first_name, c.last_name = e.last_name, c.email = e.email, c.phone_number = e.phone_number, c.hire_date = e.hire_date, c.job_id = e.job_id, c.salary = e.salary, c.commission_pct = e.commission_pct, c.manager_id = e.manager_id, c.department_id = e.department_id when not matched then insert values(e.employee_id, e.first_name, e.last_name, e.email, e.phone_number, e.hire_date, e.job_id, e.salary, e.commission_pct, e.manager_id, e.department_id);

    merging rows

    eg : truncate table empl3;

    e.g. : merge into empl3 c using employees e on (c.employee_id = e.employee_id) when matched then update set … when not matched then insert values …;

    e.g. : select * from empl3;

    other large data sets manipulations

    flashback version query

    the versions between clause

    use multiple flashback queries to view row data at specific points in time. more efficiently, you can use the flashback version query feature to view all changes to a row over a period of time.you can use a query on aa table with a versions clause to produce all the versions of all the rows that exists or ever existed between the time the query was issued and the undo_retention seconds before the current time. undo_retention is an initialisation parameter which is an auto-tuned parameter. a query that includes a versions clause is referred to as a version query. the results of a version query behaves as if the where clause were applied to the versions of the rows. the version query returns versions of the rows only across transactions.

    the oracle server assigns a system change number(SCN) to identify the redo records for each committed transaction.

    e.g. : select salary from employees3 where employee_id = 107;(the salary for employee 107 is retrieved.)

    e.g. : update employees3 set salary = salary * 1.30 where employee_id = 107;(the salary for employee 17 is increased by 30 percent.)

    e.g. : commit;(the change is committed.)

    e.g. : select salary from employees3 versions between scn min value and maxvalue where employee_id - 107;(the different versions of salary are displayed.)

    the versions between clause

    e.g. : select versions_starttime “start_date”, version_endtime “END_DATE”, salary from employees versions between SCN MINVALUE AND MAXVALUE where last_name = ‘Lorentz’;

    advanced group functions

    use the rollup operation to produce subtotal values 

    use the cube operation to produce cross-tabulation values

    use the grouping function to identify the row values created by rollup or cube

    use grouping sets to produce a single result set

    review of group functions

    syntax of group functions

    group functions operate on sets of rows to give one result per group

    syntax : select [column,] group_function(column) … from table [where condition] [group by group_by_expression] [order by column];

    e.g. : select avg(salary), stddev(salary), count(commission_pct), amx(hire_date) from employees where job_id like ’SA%’;(calculates the average salary, standerd deviation on the salary, number of employees earning a commission, and the maximum hire date for those employees whose job_id begins with SA.)

    the group by clause

    syntax : select [column,] group_function(column) … from table [where condition] [group by group_by_expression] [order by column];

    e.g. : select department_id, job_id, sum(salary), count(employee_id) from employees group by department_id, job_id;

    the having clause

    use the having clause to specify which groups are to be displayed.

    you further restrict the groups on the basis of a limiting condition.

    syntax : select [column,] group_function(column) … from table [where condition] [group by group_by_expression] [having having_expression] [order by column];

    generating reports by grouping related data

    rollup operator

    rollup is an extension to the group by clause.

    use the rollup operation to produce cumulative aggregates, such as subtotals.

    syntax : select [column,] group_function(column) … from table [where condition] [group by [rollup group_by_expression] [having having_expression]; [order by column];

    e.g. : select department_id, job_id, sum(salary) from employees where department_id < 60 group by rollup(department_id, job_id);

    cube operator

    cube is an extension to the group by clause.

    you can use the cube operator to produce cross-tabulation values with a single select statement.

    syntax : select [clumn,] group_function(column) … from table [where by [cube] group_by_expression] [having having_expression] [order by column];

    e.g. : select department_id, job_id, sum(salary) from employees where department_id < 60 group by cube (department_id, job_id);

    grouping function

    the grouping function : (is used with either the cube or rollup operator/is used to find the groups forming the subtotal in a row./is used to differentiate stored null values from null values created by rollup or cube/returns 0 or 1.)

    syntax : select [column,] group_function(column) … , grouping(expr) from table [where condition] [group by [rollup] [cube] group_by_expression] [having having_expression] [order by column];

    e.g. : select department__id deptno, job_id job, sum(salary), grouping(department_id) grp_dept, grouping(job_id) grp_job from employees where department_id < 50 group by rollup(department_id, job_id);

    grouping sets

    grouping sets syntax is used to define multiple grouping in the same query.

    all grouping specified in the grouping sets clause are computed and the results of individual groupings are combined with a union all operation.

    grouping set efficiency : (only one pass over the base table is required./there is no need to write complex union statements./the more elements grouping sets has, the greater the performance benefit.)

    e.g. : select department_id, job_id, manager_id, avg(salary) from employees group by grouping sets ((department_id,job_id), (job_id, manager_id));

    composite columns

    a composite column is a collection of columns that are treated as a unit.

    rollup (a, (b, c), d)

    use parentheses within the group by clause to group columns, so that they are treated as a unit while computing rollup or cube operations.

    when used with rollup or cube, composite columns would require skipping aggregation across certain levels.

    e.g. : select department_id, job_id, manager_id, sum(salary) from employees group by rollup(department_id,(job_id,manager_id));

    concatenated groupings

    concatenated grouping offer a concise way to generate useful combinations of groupings.

    to specify concatenated grouping sets, you separate multiple grouping sets, rollup, and cube operations with commas so that the oracle server sombines them into a single group by clause.

    the result is a cross-product of groupings from each grouping set.

    e.g. : group by grouping sets(a,b), grouping sets(c,d)

    e.g. : select department_id, job_id, manager_id, sum(salary) from employees group by department_id, rollup(job_id), cube(manager_id);

     

    10.29

    insert into table_name values(123,default);
    desc user_constraints(用来找到所有constraints 的名称)
    alter table courses drop primary key cascade;(删除primary key constraint需要使用cascade option)
    alter table table_name drop column column_name;(删除a column)
    set unused (hide)
    drop (remove/delete)
    insert 
    delete
    update
    commit(to save)
    show autocommit
    set autocommit on(这样就不用每次都commit了)
    rollback(undo)
    savepoint a1
    delete
    insert
    savepoint a2
    rollback to a1
    update table_name set column_name = column_name_value where conditions;
    delete from table_name where conditions;
    eg: create table t123 (ID Number(5), ename Varchar2(10));
    insert into t123 (ename,id) values(‘ABCD’,12);
    insert into t123 values(13,’SSSS’);
    update t123 set ename = ‘AAAA’;
    update t123 set ename = ‘AAAA’ where id = 13;
    update t123 set ename = ‘FFFF’, ID = 21 where id = 13;
    insert into t123 values(99,’LAST’);
    savepoint s1;
    update t123 set ID = 55 where ID = 99;
    savepoint s2;
    rollback to s1;
    select * from t123;
    SQL函数可以无参数但必须返回值
    dual表
    abs(value)(取绝对值)
    eg : select abs(-100) from dual;
    ceil(value)(取大整)
    eg : select ceil(6.7) from dual;
    floor(value)(取小整)
    eg : select floor(6.7) from dual;
    mod(m,n)(取余m/n的余数)
    eg : select mod(10,2)from dual;
    power(m,n)(幂方m的n次方)
    eg : select power(3.2) from dual;
    sqrt(n)(求平方根square root)
    eg : select sqrt(9) from dual;
    round(number,[decimal_places])(近似到小数点后几位)
    eg : select round(125.315,1) from dual;
    trunc(number,[decimal_places])(留到小数点后几位(不取四舍五入值))
    add_months(date1,n)(返回一个加了n的日期)
    eg : select acc_month(’01-Aug-03’,3) from dual;
    months_between(date1,date2)(返回两个日期之间相差的月份数)
    eg : select months_between(TO_DATE(‘2001/08/02’,’yyy/mm/dd’),TO_DATE(‘2003/06/02’,’yyy/mm/dd’)) from dual;(结果返回2)
    last_day(date)(返回月份的最后一天)
    eg : 
    next_day(date,weekday)(显示最近的即将到来的weekday)
    round(date,[format])(跳到下个年/月/季度(fromat)的第一天)
    eg : select round(to_date(’22-aug-03’),’month’)(返回值为01-sep-03)
    trunc(date,[format])(跳到本年/月/季度( fromat)的第一天)
    eg : 
     
     
     
     
    10.30
     
    select column_name || ‘the_string_that_you_want_to_add’ || column_name from table_name;
    eg : select empno ||’has the name:’ || ename from emp;
    lower(’string’)
    upper(’string’)
    initcap(’string’)
    eg : select initcap(‘hello abc’) from dual;
    eg : select ename,lower(ename),upper(ename),initcap(‘hello,this is an example’) from emp;
    instr(’string1’,’string2’)(to return the position(number) of string2 in string1)
    eg : select instr(‘How do you do’,’do’) Position from dual;
    eg : select instr(‘How do you do’.’di’,8) Position from dual;(从第八个字符(y)开始寻找‘do’字符串)
    substr( ’string’ or column_name, number1,number2 )(to extract a part of the string from the given string从第number1个字符开始向后取number2个字符串,如果没有number2,则取number1字符后所有的字符串,包括第number1个字符)
     
    注:instr —> result is a number
           substr —> result is a string
    eg : select substr(name,1,instr(name,’ ‘)-1) from faculty;(to extract the first name from name)
    eg : select substr(name,instr(name,’ ‘)+1) from faculty;(to extract the last name from name)
    ltrim(’string1’,’string2')(to trim/remove off the unwanted characters(all in string2) from the left in string1)
    rtrim(’string1’,’string2')(to trim/remove off the unwanted characters(all in string2) from the right in string1)
    eg : select ltrim(‘aabcbadxyabc’,’abc’) Result from dual;(结果为dxyabc)
    eg : select rtrim(‘abndefe’,’a’) Result from dual;(结果为abndefe)
    trim(‘       string     ‘)(remove spaces from left and right side)(结果为string)
    translate(’string1’,’string2’,’string3’)(将string1中的string2中的字符用string3中的字符逐个代替)
    replace(’string1’,’string2’,’string3’)(将string1中的string2用string3代替)
    eg : select replace(‘ABC ABAC XYZ DABC’,’ABC’,’PQR’) Result from dual;(结果为PQR abac XYZ DPQR)
    eg : select translate('ABC ABAC XYZ DABC’,’ABC’,’PQR’) Result from dual;(结果为PQR PQPR XYZ DPQR)
    length(’string’)(计算string的长度)
    to_char(date/number,’model')(to convert the given date or number to char type)
    eg : select to_char(sysdate,’dd-mm-yyyy’) Result from dual;
    eg : select to_char(sysdate,’dd Month yyyy hh24:mi:ss’) from dual;
    to_number(’string’,’string’)(to convert formatted number to number or sort char data in numeric order)
    eg : select to_number(‘$333’,’$999’) * 20 from dual;
    eg : select * from t2 order by to_number(id) desc;
    decode(column_name,value,what you want to display,value2)
    eg : select fcode,ccode,grade,decode(grade,’A’,’Very Good’,’B’,’Good’,’C’,’Average’,’Unknown’) grade from course_faculty;
    grouping data(group by clause)
    eg : select bckode,count(rollno) from students group by bcode;(groups rows of students table on bcode using group by clause. then it counts number of students we have in each batch using group function count)
    eg : selectt deptno,count(empno) from emp group by deptno;
    eg : select job,sum(sal) from emp group by job;
    group functions : 
    sum()(returns the sum of the given column)
    avg()(returns the average of the given column.)
    min()(returns the minimum value in the given column)
    max()(returns the maximum value in the given column)
    count()(returns the number of not null values in the given column)
    eg : select count(deptno) from emp;
    eg : select count(distinct deptno) from emp;
    eg : select count(unique deptno) from emp;
    eg : select job,sum(sal) from emp where job not in (‘president’,’manager’) group by job;
    eg : select sal,deptno from emp where deptno !=20 group by dept no;
    eg : select sal,deptno from emp group by dept no;
    注:where条件句不能用在group by 后面,必须用在前面。having条件句可用在group by 后面。
    having clause
    select … where(conditions)
    group by —> check the condition
    eg : select dept no,count(empno) from emp group by dept no having counting(empno) > 5;(display the department number and numbers of employees in that department from emp table that have more than 5 employees)
    using where and having together
    oracle first selects rows based on where clause,after that it groups the selected data, then groups are selected based on having clause.
    join —> PK —>FK
    sub query —> more than one sql command
    outer query (sub query)
    eg : select ename fm emp where sal = (sleect max(sal))
    types of join : 
    product(cartesian join)(all rows1 * all rows2)
    equi join  PK —> FK (equal join)
    non-equi join(not PK —> FK)
    outer join( PK = FK (+) )
    self join(same table)
    product
    eg : select dname, ename from emp,dept;
    equi join
    eg : select emp.ename,dept.dname from emp,dept where dept.deptno = emp.deptno;
    eg : select emp.deptno,dept.dname from emp,dept where dept.deptno = emp.deptno;
    table aliases
    eg : select e.ename,d.dname from emp e,dept d where e.deptno = d.deptno;(using e as temporary name for emp table and d for the dept table)
    non equi join(is used where a value (column) is within a range of values rather than equal to a specific value.)
    eg : select emp.ename,emp.sal,salgrade.grade from emp,salgrade where emp.sal between salgrade.losal and salgrade.higrade;
    outer join(to join tables together and still return rows even if one side of a condition is not sastified)
    eg : select emp.deptno,dept.deptno from emp,dept where emp.deptno = dept.deptno;
    eg : select e.ename,d.dname from emp e,dept d where d.deptno = e.deptno(+);
    注:the (+) in the above statement creates an outer join,which means still return a row from dept table even if the join condition fails.
    self join(join a table to itself , to select from the same table more than once within the same sql statement.)
    eg : select e.ename employee_name,m.ename manger_name from emp e,emp m where m.empno = e.mgr;(select the employee name from emp and call it employee_name,then select the employee name again and call it manager_name from emp where the employee number(empno) is the same as the manager(mgr) stored on the first record.)
    eg : select count(e.ename) no_of_employees,m.ename manager_name from emp e,emp m where m.empno = e.mgr group by (m.ename); (using self join group by manager count(e.ename))
    show line(show line size)
    set line 120
    set operators(union,intersect,minus)
    union (combine the results of two or more queries and returns all distinct rows from all queries)
    eg : select job from emp where dept no = 10 union select job from emp where dept no = 30;
    union all —>(return all rows from both queries)
    intersect(combines the results of two or more queries and returns only rows which appear in both queries.)
    eg : select dept no from dept intersect select dept no from emp;
    minus (combines the results of two or more queries and returns only rows that appear in the first query and not the second.)
    eg : select dept no from dept minus select dept no from emp;
    subqueries(a select statement within another select statement .allows you to select data based on unknown conditional values.subquery will excite first and give the result back to outer query)
    eg : select column(s) from table(s) where column(s) = (select column(s) from table(s) where condition(s));
    eg : select * from emp where dept no = (select deptno from emp where ename = ‘BLAKE’);(find the dept of blake and show all the emp from that dept.)
    eg : select ename,job from emp where job = (select job from emp where ename = ‘blake’);(find all employees who have the same job as blake.)
    eg : select * from emp where sal = (select max(sal) from emp); (find the employees who are getting maximum salary.)
    eg : select * from emp where deptno in (select dept no from emp where sal > 1000);
    single row subqueries(returns a single row to the outer query.)
    eg : select ename,sal from emp where sal = (select min(sal) from emp);
     
    multiple row subqueries(returns more than one row)
    in operator in multiple row subqueries :
    eg : select * from emp where (dept no,job) in (select deptno,job from emp where sal > 1000);
    eg : select where (deptno,sal) in (select deptno,min(sal) from emp group by deptno);
    eg : select ename,job,empno form emp where (dept no,sal) in (select deptno,min(sal) from emp group by deptno);(find the employee name,job,empno from each department who are getting lowest salary.)
    any/some operator in multiple row subqueries : (compares a value to each row returned from the sub query.)
    eg : select ename,sal,job,deptno from emp where sal > any (select distinct sal from emp where dept no = 30);
    e.g. : select ename,job,sal from emp where sal > any (select unique sal from emp where deptno = 30); (find all employees who are getting salary which is greater than the salary of any employee who is working in dept 30.)
    all operator in multiple row subqueries : 
    eg : select ename,sal,job,deptno from emp where sal > all (select distinct sal from emp where deptno = 30);
    e.g. : select ename,job,sal from emp where sal > all (select unique sal from emp where deptno = 30); (find all employees who are getting salary which is greater than the salary of all employees who is working in dept 30.)
    correlated subqueries(a way of exciting a sub query once for each row found in the outer query.)
    eg : select empno,ename,sal,deptno from emp e where sal > (select avg(sal) from emp where deptno = e.deptno);(list all employees who earn a salary greater than the average salary for their department.)
    =, in, any, all, 
    exists (to find if any rows are returned from the sub query.)
    eg : select empno,ename,job,deptno from emp e where exists(select * from emp where emp.mgr = e.empno);(to select all employees who are manager to someone.)
    not exists (to check if no rows are returned from the sub query.)
    eg : select empno,ename,job,deptno from emp e where not exists (select * from emp where emp.mgr = e.empno);
    rename a column using sub query
    eg : create table products (id number(5), pric number(5));
    eg : create table new products as select id, price price from products;
    remove the product table : drop table products;
    rename the new table to old table name : rename new product to product;
    eg : create table emp1 as select * from emp;(copy the structure and the data.)
    eg : create table emp2 as select * from emp where empno = 0000;(copy the structure only.)
    views (the create view command)
    a view is a virtual table which is made up of the rows that your query returns.
    e.g. : create or replace view emp_dept as select e.ename employee_name,d.dname department_name from emp e,dept d where d.deptno = e.deptn0; (have a query that lists employee names along with department names.)
    login with sys 
    grant create view to scott;(give the user scott the permission to create view.)
    select * from tab;(show all the tables you have.)
    emp table —> base table
    emp view —> virtual table (image)
    create or replace view view_name as select ……
    desc user_views
    user_constraints —>all types of constraints
    user_views —> view_name,text
    user_objects —> status,object_name...
    delete or deep the base table
    create base table with the same name of details(then the status will change to valid.)
    getting info. about updatable columns(using user_updatable_columns.)
    eg : create table t2(ID number(5));
    eg : create or replace view t2_view as select *  from t2;
    eg : select * from user_datable_columns where table_name = ‘T2_VIEW’;
    eg : insert into t2_view values(10);
    eg : select * from t2;
    sequence(a sequence is simply an object within the database that returns a unique number.)
    create sequence(to create a sequence)
    syntax: create sequence sequence_name increment by n start with m;
    eg : create sequence my_seq01 increment by 10 start with 100;
    referencing a sequence(using nextval)
    eg : select  my_seq01.nextval from dual;
    eg : select my)seq01.currval from dual;(without increasing its value.)
    adding value using sequence
    eg : insert into students values (my-SEQ01.NEXTVAL,…);
    dropping/removing a sequence
    syntax: drop sequence sequence_name;
    eg : drop sequence my_seq01;
    security
    create new user
    eg : create user student identified by student;(to create a user whose secret is student.)
    note : in order too create a new user you must login either as system or as sys.
    eg : grant connect,resource to student;
    note : to create a session and also creating tables,view etc.,user must be granted(given) connect and resource roles as above.
    alter user user_name identified by new_password;(to change password in system user or the current user)
    grant permissions
    eg : grant select on emp to student;
    eg : grant update(comm) on emp to student;
    eg : grant select,insert,update,select on emp to student;
    eg : grant all on emp to student;
    eg : grant update(column_name) on table_name to user_name;
    access data from other users
    eg : select * from hr.emp;
    syntax : select * from user_name.table_name;
    eg : select * from scott.emp;
    eg : update scott.emp set comm = comm+10;
    eg : update scott.emp set sal = comm+10;
    using synonyms(a synonym is an alias to a table or a view.)
    by creating a synonym you can avoid giving the owner name while accessing tables of others.
    eg : grant create any synonym to student;(login with sys user.)
    eg : create synonym emp for scott.emp;(login with student user.)
    eg : select * from emp;
    with grant option
    using option with grant option with grant command allows grantee(who received the permission) to grant the privilege that he/she received to other users.
    eg : grant select on dept to student with grant option;
    revoking object privilege
    eg : revoke select on emp from student;
    eg : revoke select,insert,update,delete on emp from student;
    eg : revoke all on emp from student;
    revoking is cascading
    when a privilege(perission) is revoked(removed) from a user,if that user has previously granted that privilege(permission) to other users then all other users will also lose that privilege.
    alter user command(to modify the password of a user.)
    eg : alter user student identified by stu_test;
     
     
     
    FINAL EXAM
    11.19
    1.fill in the blanks
    2.true or false
    3.explain the following queries
    4.match the following
    5.create the table with constraints(rules).
    6.short notes
    7.write sql queries for the following
     
    help command
    sp_helpdb
    sp_help
    sp_help [table_name]
  • 相关阅读:
    Windows Server 2003 服务器备份和恢复技巧
    查询表一张表的列名及字段类型
    aix 维护常用命令
    从 p12 格式 SSL 证书解出 pem 格式公钥私钥给 Postman 使用
    微信添加好友、加群的限制
    python requests 设置 proxy 和 SSL 证书
    blog post template(步骤类)
    post template(调查类)
    clip at cnblogs log
    《什么才是公司最好的福利》读后感
  • 原文地址:https://www.cnblogs.com/jilili/p/4108271.html
Copyright © 2020-2023  润新知