Update statement can not contains column names Update empname,empno from emp where empno=40;----Error TIMESTAMP, INTERVAL DAY TO SECOND and INTERVAL YEAR TO MONTH can be used to specify column definition. SELECT empno,empname,NVL(jobid,’none’) from emp;oracle returns error cause:none value is not given as value for number datatype ,if null is there in table with datatype string then ‘none’ can bedisplayed. "Invoice" and "Invoice Items" Not Fk relation,It is "parrent -child relation" ,cause "one invoice can have more than one items and none items also" which is OPTIONAL ,thats why here it is not Fk relation,It is Parrent Child Relation exists. .TRUNCATE TABLE TABLENAME.means it will delete higher water mark Variable defined will remain untill session complete. "USED to change the default character indentifies runtime variable" SET DEFINE COMMAND When null data fed into group functions then the result is always "NULL" like ....... (SUM(SAL)......having sal values as null ). If we are executing mathamatical expressions on "user defined statistics" in our query,then where clause does not indentify the component of a query. If we use mathematical expression on "statistical expression" then where clause identifies: like(select * from emp where empsal =6700-2?.....selects values of sal=6698)where clause identifies. column padded to 7 digits right and have value SMITHY, So length of that column is "13" not "5". Which SQL statement will return the ENAME, length of the ENAME, and the numeric position of the letter "a" in the ENAME column, for those employees whose ENAME ends with a the letter "n"? SELECT ENAME, LENGTH(ENAME), INSTR(ENAME, 'a') FROM EMPLOYEES WHERE SUBSTR(ENAME, -1, 1) = 'n'; MERGE UPDATE DELETE MODIFY all are DML.

 


Top N analysis requires ROWNUM and ORDER BY,An INLINE view and an OUTER QUERY. SELECT * FROM emp WHERE commission = (SELECT commission FROM emp WHERE emp_id = 3);Query returns no rows but not give any error

"Dear Customer customer_name, " SELECT 'Dear Customer ' || customer_name || ',' FROM customers;

  

ROWID:a hexadecimal string representing the unique address of a row in its table

Two Date columns (SUBSTRACTION)MINUS will give numeric value.

Create synonym  Your tables have difficult names  You want to use another schema's tables TO_CHAR function performs  convert 10 to '10'  convert a date to a character expression 

   

the alias Annual Salary for the calculated SELECT id, name AS "Name", salary * 12 AS "Annual salary" FROM employee; SELECT id, name "Name", salary * 12 "Annual salary" FROM employee; SELECT id, name "Name", salary * 12 as Annual salary FROM employee; SELECT name || ' is a ' || jobtitle AS 'Employee Detaisl' FROM employee; INSERT INTO (SELECT * FROM employees WHERE department_id IN (20,50) WITH CHECK OPTION)VALUES (emp_id_seq.NEXTVAL, '&ename', '&jobid', 2000, NULL, &did); DEPARTMENT_ID = NULL,Not to use =,But use IS, DEPARTMENT_ID IS NULL SELECT LOWER (TRIM ('H' FROM 'Hello World')) FROM dual "Nineteenth of March 2001 12:00:00 AM"

  


SELECT TO_CHAR(TO_DATE('19-Mar-2001', 'DD-Mon-YYYY'), 'fmDdspth "of" Month YYYY fmHH:MI:SS AM') NEW_DATE FROM dual;  SELECT LPAD(salary,10,*) has a salary of 17000, return *****17000 , For number (10,2)****170.00 use the USING clause

 The tables to be joined have multiple NULL columns.  The tables to be joined have columns with the same name and compatible data types.  You want to use a NATURAL join, but you want to restrict the number of columns in the
join condition. TO_DATE function  convert any date literal to a date  format 'January 10 1999' for input

 

character manipulation functions TRIM REPLACE DELETE employee_id, salary, job_id FROM employees WHERE dept_id = 90; You cannot specify column names in the DELETE clause of the DELETE statement. SELECT subj1+subj2 total_marks, std_id FROM marks WHERE subj1 > AVG (subj1) AND subj2 > AVG (subj2) ORDER BY total_marks; The statement returns an error at the WHERE clause

MERGE INTO ,We should not use table name in the update set clause and also we should not use table names in insert values() of merge into statement.

OrderBy GroupBy
 default behavior of the ORDER BY clause ASC  Date values are displayed with the earliest Date first .  Numeric values are displayed with the lowest values first.  Null value will be at last if it is asc order.  Null value will be at beginning at desc order Column alias names can not be used in Group by clause,But can be used in Order By clause , otherwise gives an error. Select empname en ,empno no ,max(sal) maxsal from emp


Group by en,order by maxsal.—Error

Select * from emp where dept in (select dept from valid_dept where dept_head='soni' order by dept); Oracle returns error cause order by can not be used in subquery,But group by can be used insub query. ex: SELECT last_name FROM employees WHERE salary IN (SELECT MAX(salary) FROM employees GROUP BY department_id);syntax is correct Select farm_name,cow_name Count(carton) as number From cowmilk Group by cow_name; Oracle returns error cause Non_group columns in the select statements should come left to the group columns and should be mensioned in the grop by clause otherwise oracle returns an error.

• •
be done.

N-dimensional cross Tabulatioun is done by "CUBE " in "GROUP BY " clause. To remove redundancy of group by clause excution by using "With "clause can


For adding forth column for already existing view with 3column then CREATE OR REPLACE VIEW emp_dept_vu AS SELECT employee_id, employee_name Department_name, manager_id FROM employees e, departments d WHERE department_id = d.department_id; Only job alter view can perform is recompiling an invalid viewALTER VIEW EMP_DEPT_VW COMPILE:

Views  A view can be created as read only A view can be created as a join on two or more tables.


   

Can not update,delete,insert data in a view with group functions and distinct Can not modify data of a column in a view with single row functions and functions with pseudo column.Other columns can be modified We can delete the data in a view if this view is not having all columns in the original table also. If we have filter criteria in a view then we have to use check option for that …for users not to enter the values other than the filter option…otherwise oracle gives error….or oracle gives simply 0 rows were inserted.

DELETE, INSERT, SELECT, UPDATE, object privileges can be granted on a view. What does the FORCE option for creating a view do? creates a view regardless of whether or not the base tables exist CREATE VIEW emp_vu AS SELECT * FROM employees WHERE department_id IN (10,20) WITH CHECK OPTION;With check option ,user cannot modify view but he can manipulate data for a view for updatable columns of key preserved tables.


  
For complex views we cannot update any columns for two tables if they are not connected by PK and FK relation Outer join views are not updatable Complex views should not contain group functions,group by,set,distinct,rownum,with,connet by

  

Comment information on table are stored in the view USER_TAB_COMMENTS Comment information on columns are stored in the view USER_COL_COMMENT Information about views in your database are stored in USER_VIEWS


To obtain the defination of a view Query the USER_VIEWS data dictionary view to search for the EMP_DEPT_VU view analyse status of view in database USER_OBJEBTs All_IND_COLUMN will give position of PK column Any objects that associated with pK is USER_INDEXES In order to identify any objects that may be asociated with that table and primary key dictionary view used is USER_INDEXES USER_CONS_COLUMNS, view should a user query to display the columns associated with the constraints on a table owned by the user To find data about the constraints USER_CONSTRAINTS USER_COL_PRIVS data dictionary table should you query to view the object privileges granted to the user on specific columns Position of each column in a table we can know by using USER_TAB_COLUMNS, Just like DESCRIBE USER_UPDATABLE_COLUMNS can tell whether the columns in a complex view can be modified or not. For information about sequence is USER_SEQUENCES Finding Information about users ALL_USERS USER_SYS_PRIVS shows all system privileges associated with this user. SESSION_PRIVS shows all privileges available in this session.

  

         



constraints Constraints can be created after the table is created Constraints can be created at the same time the table is created use of constraints  constraints enforce rules at the view level.  constraints enforce rules at the table level  constraints prevent the deletion of a table if there are dependencies explicitly names a constraint ALTER TABLE student_grades ADD CONSTRAINT student_id_fk FOREIGN KEY (student_id) REFERENCES students (student_id);

Check Constraint can not contain a reference to another table.check (select ID from dept)....these are not valid. and also check constraint will not reference to virtual column like:USERS,ROWID,SYSDATE...etc.


• •

Check constarint correctone is ,it chould contain some set of fixed values,but not the not null values.


Aggregate functions

  

Count, Minimum,Maximum Aggrgate functions are used on the column of datatype DATE It returns a single result row based on groups of rows

aggregate functions

 You can mix single row columns with aggregate functions in the column list of a SELECT statement by grouping on the single row columns.  You can pass column names, expressions, constants, or functions as parameters to an aggregate function


Aggregate functions can appear in select lists and in ORDER BY and HAVING They are commonly used with the GROUP BY clause in a SELECT statement

  A single row subquery can retrieve data from more than one table. A SQL query statement cannot display data from table B that is referred to in its subquery, unless table B is included in the main query's FROM clause.

Subqueries are used with the SELECT, INSERT, UPDATE, and DELETE statements. Subqueries must be enclosed within parentheses.


• •

A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns. An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery.

• •

Subqueries that return more than one row can only be used with multiple value operators, such as the IN operator. The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or NCLOB. A subquery cannot be immediately enclosed in a set function. The BETWEEN operator cannot be used with a subquery; however, the BETWEEN can be used within the subquery WE can query upto 255 subqueries

• •

SubQueries  A single row subquery can retrieve only one row but many columns  A multiple row subquery can retrieve multiple rows and multiple columns  A single row subquery can use the IN operator

Subqueries  A subquery can retrieve zero or more rows.  When a subquery is used with an inequality comparison operator in the outer SQL statement, the column list in the SELECT clause of the subquery should contain only one column. NOT IN operator can be used with multi row subquery. Inner and outer query retrieving data from same table then there are no rows returned Sub query can be used in the FROM clause of a SELECT statement in the WHERE clause of a SELECT statement in the SET clause of an UPDATE statement in the VALUES clause of an INSERT statement

  
   


SELECT * FROM orders WHERE cust_id = (SELECT cust_id FROM customers WHERE cust_name = 'Smith') The query fails because the subquery returns more than one row.

the main query fails because the multiple-row subquery cannot be used with the comparison operator.


Need of co-rrelated sub query comes in case of "Exists" in where clause , Not in case of "IN" in where clause, cause for "IN " in where clause we can contain set of values where as for exists we should have so-rrelated sub query. Definitely subquery is reqired to create one table from another table with same structure and columns



 You use a CURRVAL pseudo column to look at the current value just generated from a
sequence,without affecting the further values to be generated from the sequence.  You use a NEXTVAL pseudo column to obtain the next possible value from a sequence by actually retrieving the value form the sequence

• •

Sequence by default start with 1 and by default increment by 1.

Once created, a sequence belongs to a specific schema



Update,Delete,Insert Will be Roll backed,DDL (like:CREATE,ALTER,DROP) will not be roll backed.TRUNCATE also will not be roll backed,cause data will be deleted at once. "Save Point" is not a begining of new transaction.A transaction can have more than one "Save points". At begining of transaction ,if we want to make the next coming statements should not alter database ,then we can use "SET Transaction", we cant use "Save points" there cause it is at the begining of transaction. Complete a transaction * ROLLBACK TO SAVEPOINT C; * ALTER TABLE employees SET UNUSED COLUMN sal; CREATE USER scott IDENTIFIED by tiger; No privileges till yet even cannot connect to database,for this he needs session privileges

 Two tables with different columns have been given and asked to calculate Tax for each employee,we can calculate cause in tax column minsal and maxsal provided ,for each employee sal lies between these two salaries only.

USE OF AN OUTER JOIN D. You use an outerjoin to see only the rows that do not meet the join condition. E. In the WHERE condition, you use (+) following the name of the column in the table without matching rows, to perform an outerjoin. F. You cannot link a condition that is involved in an outerjoin to another condition by using the OR operator.

Cases to use an outer join  The columns being joined have NULL values  The tables being joined have both matched and unmatched data. 


Case to use a FULL OUTER JOIN when You want all unmatched data from both tables. SELECT emp_name, department_name, city FROM employees e JOIN departments d USING (department_id) JOIN locations l USING (location_id) WHERE salary > 10000; is same as SELECT emp_name, department_name, city FROM employees e, departments d, locations l WHERE e.department_id = d.department_id AND d.location_id = l.location_id AND salary > 10000;

all the records from dept(right outer join), null values are in emp table(+) select empno,empname,job,emp1.deptno,deptloc from emp1,dept where emp1.deptno(+)=dept.deptno select empno,empname,job,emp1.deptno,deptloc from emp1 right outer join dept on (emp1.deptno=dept.deptno) select empno,empname,job,emp1.deptno,deptloc from emp1,dept where dept.deptno=emp1.deptno(+) All the records from emplyee left outer join, null values are in dept table(+) select empno,empname,job,emp1.deptno,deptloc from emp1 left outer join dept on (emp1.deptno=dept.deptno) select empno,empname,job,emp1.deptno,deptloc from emp1,dept where emp1.deptno=dept.deptno(+) select empno,empname,job,emp1.deptno,deptloc from emp1,dept where dept.deptno(+)= emp1.deptno



If most of the values start with some values(like" "C001") ,then it is better to use "Reverse Index"rather than to use "B Tree Index",In this case(some values start with perticular value) Cardinality for root node is low, B-Tree index works fine for "column having Root having High cardinality".

Pk and Unique will create indexes automatically.

For unique and Primary key ,Indexes are automatically created on constraint columns.

• •
 If column is if "USERS" ,and Jone is selecting information for Mith,then no error comes but no data will be displayed to Jone. GRANT registrar TO user1, user2, user3;----where register is role For user creation we don't have create or replace CREATE USER SUPER IDENTIFIED BY SUPER; At this time No privileges to User SUPER Grant option is not valid when granting object privilege to a role. Drop user,Create session,Backup any Table are System Privileges, Where as Index is an object privilege. • User Davids wants to access table EMPLOYEE owned by MARTIN.Public and privetae sysnonyms created by martin would work best and also.David created synonym for martin.employee would work best.but synonym created by david for just employee would not work because he is creating synonym in his own schema. When a Role has password assigned to it,then it should not be made default .But not the role given with system privileges.


Inorder to administer that access for others ,we should use "grant update on emp to soni with grant option" Reed gives object privillages to Mann ,Mann gives session privillages to Snow,and Reed revokes privilages from Mann. Ans: Able to Connects to database Reed and Snow Able to Connects to database and Does operations on database Reed Only Reed gives session privillages to Mann ,Mann gives session privillages to Snow,and Reed revokes privilages from Mann. Ans: Able to Connects to database Reed and Snow Able to Connects to database and Does operations on database Reed and Snow

Table Spaces
 For making tablespace read only , we need to make sure that * Table space is not involved for any active rollbacks and * Tablespace is not involved for any open backups and also * Tablespace should be online. Rename datafile with alter tablespace, then we should make sure of database is open and datafiles must be offline before renaming.

Manage tablespace make tablespace * To take backup and * End backup and * Take the table space offline * Take the table space online

the following is true if you use the alter tablespace statement and specify the TEMPORARY clause (Choose all that apply)?

A. Oracle no longer perform any checkpoint for the online datafiles in the tablespace B. Oracle performs a checkpoint for all online datafiles in the tablespace C. Oracle does not ensure that all files are written D. The offline files may require media recovery before you bring the tablespace online



   

DROP TABLE DEPT; You cannot roll back this statement All pending transactions are committed All indexes based on the DEPT table are dropped. All data in the table is deleted, and the table structure is also deleted. DELETE employees; The data in the EMPLOYEES table is deleted but not the structure.

 CREATE TABLE EMP (empno NUMBER(4), ename VARCHAR2(35), deptno NUMBER(7,2) NOT NULL, CONSTRAINT emp_deptno_fk FOREIGN KEY deptno REFERENCES dept deptno); naming database tables must be 1-30 characters long should not be an Oracle Server reserved word. must contain only A-Z, a-z, 0-9, _, $, and # must begin with a letter • ALTER TABLE EMPLOYEES MODIFY (SALARY DEFAULT 5000); A change to the DEFAULT value affects only subsequent insertions to the table.not the already inserted null values are not modified to 5000. • For create table we need to use CREATE TABLE not to use CREATE OR REPLACE TABLE TRUNCATE TABLE DEPT;  It releases the storage space used by the table.  You can NOT roll back the deletion of rows after the statement executes.  You must be the owner of the table or have DELETE ANY TABLE system privileges to truncate the DEPT table 

    


 CREATE TABLE EMP9$# AS (empid number(2));valid CREATE TABLE EMP*123 AS (empid number(2));notvalid • Maximum number of columns that a table can have 1000.

Single row functions
* Manipulate data items * Act on each row returned * Return one result per row * Accept arguments which can be a column or an expression
• • • • • •


 can return non-NULL value when called with a NULL argument.  TO_DATE(s[, fmt[, nls]]) Converts string s to DATE  TO_CHAR(x[, fmt[, nls]]) Takes up to three arguments, where x is either a date
or a number

four are types of functions available in SQL character ,numeric, date, conversion

lpad('tech', 7); lpad('tech', 2); lpad('tech', 8, '0'); lpad('tech on the net', 15, 'z'); lpad('tech on the net', 16, 'z');

would return ' tech' would return 'te' would return '0000tech' would return 'tech on the net' would return 'ztech on the net'

• A version of SQL*PLUS which runs in a browser,Usnig browser we can connect to an isql prompt. SQL: Manuplates data and table definitions in the database. iSQL*PLUS: Does not allow manuplation of values in database.


• SQL and SQL* differencess http://courses.dsu.edu/infs788_krebsbach/pdf_files/Simple%20iSQLPLUS%20Web.pdf http://www.scottsdalecc.edu/trollen/CIS119/Formatting_Output.pdf
http://ct.xab.ac.cn/Portals/0/Oracle%20SQL/D33053%20introduction%20to%20oracle %209i_sql%20v3.pdf

• Selection,projection,join Select empid,empname,deptname from emp,dept where emp.deptid=dept.deptid • Projection,selection.join Select empid,empname,deptname from emp,dept where emp.deptid=dept.deptid and empjob=’manager’
• display 2000 in the format "$2,000.00"? B. SELECT TO_CHAR(2000, '$0,000.00') FROM dual; C. SELECT TO_CHAR(2000, '$9,999.00') FROM dual; D. SELECT TO_CHAR(2000, '$9,999.99')

• If users wants to give a runtime value then it is best to use accept command only • NVL2 function displays NOT NULL values and then NULL value. select empname,nvl2(joinid,'yes','no') from employee; •

INSERT INTO T1(A) VALUES(2); INSERT INTO T1 VALUES(1,DEFAULT); this works if secound column is having default value for that.This explicitly tell oracle to use default.We can also use DEFAULT in the update statement also.UPDATE SAMPLE SET COL2=DEFAULT WHERE COL1=3; UPDATE SET PROFITS=NULL WHERE PRODUCT_TYPE=’TOYS’;Deleting one column data with respect to other column

• • • •


Utlsampl.sql and demobld.sql • Sql>c/’none’/o; • ORA-00904-Invalid column • ORA-00923 From key word nort expected • ORA-00943 Table or View does not exist • 1.Sql>get crtlprod.sql / • 2.sql>@crtlprod.sql; SQLPLUS commands Describe List SP-0023 No lines in sqlbuffer • Del 3 • Append ‘soni’ • Clear buffer • Input • Run • 6 ‘new line being added’ • Spool ctrl.out Select * from emo; Spool off Save ctrlprod.sql Exit Afiedt.buf buffer • • OrderBy Group By Single Row functions o Text functions:Rpad,Lpad,Initcap,Lower,Upper,length,Substr,Instr o Arithemetic functions:Abs,Ceil,Floor,Mod,Round,Sqrt,Trunc,sinh() o List functions: greatest,least,Decode,

• • •

• •

• • •

Date functions:months_between,add_months,next_day,last_day,new_time Conversion functions:To_char,To_date,To_number JOINS


• • • • •

Cartesian join Natural join: used with filter condition Left outer join Right outer join Self join • •

• • • • • •

Group Functions Avg(),sum(),count(),min(),max(),stddev(),variance() Using group by clause-Rollup and Cube Using group by and having

Sub Quries Single row subqueries Multi row subqueries.Multi column subqueries Inline views Using with clause for group by

• • • •

Readable Output substitution variable:& and set define ? lexical substitution variable:&& Automatic difination at runtime :define and undefine:reuse substitution variable bypassing value from one statement to other. Accept Prompt:when you want more accurate and explicit datatype conversion :accept allows only string information to be accepted by user

SQLPLUS COMMANDS • Feedback, • break on deptno:Will make duplicate values not to display in deptno:clear breaks • compute sum of sal on deptno :calculate sum of sal in each dept depending on deptno:clear computes • column sal format $9999.99, • btitle • ttitle • linesize • pagesize • Array size • Auto trace • Set pagesize • Set termout on/off


Store(we use save in sql) Store set myfile.out Save myfile.out

Views Privileges Locks


Sign up to vote on this title
UsefulNot useful