SQL Query Statements
SQL Query Statements
"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.
"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 ).
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';
1
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
ROWID:a hexadecimal string representing the unique address of a row in its table
Create synonym
Your tables have difficult names
You want to use another schema's tables
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;
2
SELECT TO_CHAR(TO_DATE('19-Mar-2001', 'DD-Mon-YYYY'), 'fmDdspth "of"
Month YYYY fmHH:MI:SS AM') NEW_DATE FROM dual;
TO_DATE function
convert any date literal to a date
format 'January 10 1999' for input
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
3
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.
VIEWS
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.
4
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.
What does the FORCE option for creating a view do? creates a view regardless of
whether or not the base tables exist
COMPLEX vIEWS
For complex views we cannot update any columns for two tables if they are not
connected by PK and FK relation
5
To obtain the defination of a view Query the USER_VIEWS data dictionary view to
search for the EMP_DEPT_VU view
In order to identify any objects that may be asociated with that table and primary key
dictionary view used is USER_INDEXES
USER_COL_PRIVS data dictionary table should you query to view the object
privileges granted to the user on specific columns
Constraints
6
• 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
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.
7
Aggregate functions
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
clauses. They are commonly used with the GROUP BY clause in a SELECT statement
SubQuery
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.
8
• 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.
Inner and outer query retrieving data from same table then there are no rows returned
9
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
Sequence
Sequences
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
1
Transactions
"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
JOINS
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.
1
Case to use a FULL OUTER JOIN when You want all unmatched data from both
tables.
all the records from dept(right outer join), null values are in emp table(+)
All the records from emplyee left outer join, null values are in dept table(+)
1
Indexes
• 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".
• For unique and Primary key ,Indexes are automatically created on constraint columns.
Privileges
• If column is if "USERS" ,and Jone is selecting information for Mith,then no error comes
but no data will be displayed to Jone.
Drop user,Create session,Backup any Table are System Privileges, Where as Index is an
object privilege.
• When a Role has password assigned to it,then it should not be made default .But not
the role given with system privileges.
1
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.
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
1
Tables
• DELETE employees;
The data in the EMPLOYEES table is deleted but not the structure.
• For create table we need to use CREATE TABLE not to use CREATE OR REPLACE
TABLE
1
CREATE TABLE EMP9$# AS (empid number(2));valid
CREATE TABLE EMP*123 AS (empid number(2));notvalid
• NVL
• NVL2
• CONCAT
• DECODE
• DUMP
• and REPLACE
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
1
• 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’
• 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;
LOCKS
1
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
1
• 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
1
• Store(we use save in sql)
Store set myfile.out
Save myfile.out
Views
Privileges
Locks