SQL Language Course Material
SQL Language Course Material
1. Introduction
6. Sub Queries
7. Manipulating Data
9. Including Constarints
10. Views
12. Index
Joining: You can choose the join capability in SQL to bring together
data that is stored in different tables by creating a link between them.
Note: Selection and projection often considered as horizantal and
vertical partinioning.
We can also display all columns of alll rows by lisitng column names
after the seelct keyword
In this case we can specify the column names in the order in which you
want them to appear on the output.
A column alias
- Renames column heading
- It is useful for calculations
- Immediately followed by the column name,there can also be optional
keyword AS keyword betweeen the column name and alias.
- Enclose alias name in double quotations if it contains a special
characters such as # or $ or is case sensitive.
- Column aliases can be used in both select clause and the order by
clause you cannot use column aliases int eh where clause.
Duplicate Rows:
Distinct can also be used with multiple columns and it affects all the
columns selected
From table
1. column name
2. comparison condition
Character strings and date values are enclosed in single quotation marks.
Character values are case sensitive ,and date values are format sensitive
Comparison conditions:
Operator Meaning
= Equal to
> Greater than
>= Greater than or equl to
< Less than
<= Less than or equl to
<>,!=,^= Not equl to
Operator Meaning
Between ----- AND----- Between two values (inclusive)
In (set) Match any of a list a values
Like Match a character pattern
Is null Is a null value
Between and AND are actually translated by the oracle server to a pair
of and conditions (a>=lower limit) AND (a<= higher limit).
Ex: select first – name from employees where first –name like ‘s%’;
The above query returns all the rows whose first letter is uppercase s
and it ignores lower case s.
This query displays all the names of the employees whose last name
have an 0 as the second character .
You can use the ESCAPE identifier to search for the actual % and –
symbols.
The escape option identifies the backslash(\) as the escape character .in
the pattern ,the escape character precedes the underscope(-).this causes
the oracle server to interpret the underscore literally.
Null condition:
Logical Conditions:
Operator Meaning
AND Returns true if both component
conditions are true
OR Returns true if either component
condition is true
NOT Returns true if either condition
is false
OR Truth Table:
NOT Operator:
Truth Table:
Rules Of Precedence:
Ex: select last-name , job-id ,salary from employees where job-id =’sa-
rep’
OR Job-id=’ad-pres’
AND Salary>15000
The first condition is that the job-id is ad-pres and the salary is greater
than 15000.
(job-id=’sa-
rep’
job-id=’ad-
pres’)
Salary>15000;
OR
AND
Select the row it an employee is a president or a sales representative and
it the employee carns more than 15,000.
Order By Clause:
[where condition(s)]
[order by { column,expr}[asc/dsc]];
order by clause is executed last in the query execution .it is placed last
unless the for update clause is used.
Date values are displayed with earliest value first ex:01-jan-92 before
01-jan-95.
Null values are displayed last for ascending sequences and first for
descending sequences.
Ex:select last_name , job_id ,department_id,hire –date from employees
order by hired_date desc.
1. from clause
2. where clause
3. select clause
4. orderby clause
You can also order by columns that are not included in the select clause.
Function
Arg1
Result
value
Arg2
Arg n
Functions
Single Multiple
Row Row
Functions Functions
Single row functions operate on single rows only and return one result
per row.
1.Character
2.Number
3.Date
4.Conversion
Single Row
Functions
Date
Conversion
Single row functions accepts one or more Arguments and return one
value for each row returned by the query.an argument can be
2.Variable Name
3.Column Name
4.Expression
General Functions :
- NVL
- NVL2
- NULLIF
- COALSECE
- CASE
- DECODE
Character Functions:
Character
Functions
Case-Manipulation Character –
Functions Manipulation
Functions
LOWER CONCAT
UPPER SUBSTR
INITCAP LENGTH
INSTR
LPAD/RPAD
TRIM REPLACE
Function Result
Lower (‘SQL Course’) Sql course
Upper (‘SQL Course’) Sql course
INITCAP(‘SQL Course’) Sql course
Ex: To display the data for those employees whose last names end with
n..
Number Functions:
ROUND: (column/expression,n)
Rounds the column, expression or value to n decimal places
or if n is omitted ,
No decimal places (if n is negative , numbers to the left of the
decimal point are rounded)
TRUNC: ( column/expr)
Truncates the column , expression or value to n decimal places
or if n is omitted ,then n defaults to zero.
MOD(min): returns the remainder of m divided by n .
Note: dual is a dummy table you can use to view results from functions
and calculations.
DATE: you can change the default date display setting for a user session
by executing a command
Alter session set NLS-DATE-FORMAT=’date format model’;
Valid oracle dates are between January 1, 4712 b.c and December
31,9999 a.d.
Subtract two dates to find the the number of days between those dates
Ex: select last-name ,(sysdate – hire _ date )/7 as weeks from employees
where department-id=90;
Note: SYSDATE is a sql function that returns the current date and time .
Date Functions:
Functions Description
Months_Between No.of months between two dates
Add_Months Add calender months to date
Next_Day Next day of the date specified
Round Round date
Trunc Truncate date
Note: all date functions return a value of DATE datatype except months
– between which returns a numeric value.
Find the date of the last day of month that contains date.
Round: (date[,’fmt’]);
Returns date rounded to the unit specified by the format model fmt. If
the format model fmt is omitted is rounded to nearest day .
Trunc: ( date[,’fmt]);
Returns date with the position of the day truncated to the unit specified
by the
Format model fmt is omitted ,date is truncated to the nearest day.
Ex:Months_between (’01-sep-95’,’11-jan-94’)-------19.6774194.
Ex:Add_months(’11-jan-94’,6)--------------------------11-jul-94.
Ex:Next_day01-feb-95’,’friday’)------------------------’08-sep-95’
Ex:Last_day (’01-feb-95’)--------------------------------’28-feb-95’
Ex:compare the hire dates for all employees who started in 1997. dis
play the employee number ,hire date and start month using the round and
trunc function .
Data Type
Conversion
Conversion Conversion
From To
Varchar2 to Char Number
Varchar2 or Char Date
Number Varchar2
Date Varchar2
To_number To_date
To_Char To_Char
To_Char(number/date,[fmt],[nls params]):
1. decimal character
2. group separater
if nls params or any other parameter is omitted ,this function uses the
default parameter values for this session.
To_Number : (char ,[fmt],[nlsparams])
To-Char(date,’format-date’)
Format Model:
HH24:MI:SS AM 15:42:32 PM
Ddspth fourteenth.
AM or PM , A.M or P.M
HH or HH12 or HH24
Other formats:
Ex: Select last-name to-char (hire-date , ‘fm ddspth “ of” month yyyy
fm HH:MI:SS AM’) HIREDATE from employees;
To_char (number,’format_model’)
There are some of the format element you can use with the to – char
function to display
0---------------forces 0 to be displayed
Ex:9999V99.
tx is used an exact match is required and the spaces after the word
‘may’ are not recognized.
Nesting Functions:
Nested functions are evaluated from deepest level to the least deep
level.
Step1=result1
Step2=result2
Step3=result3
Ex: display the date of the next Friday that is six months from the hire
date.
General Functions:
These functions work with any data type and pertain to using nulls.
NVL(expr1 , expr2)
NULLIF(expr1 , expr2)
COALESCE(expr1,expr2 ----------------exprn).
NVL2: if expr1 is not null, NVL2 returns expr2. if expr1 is null NVL2
returns expression3 the argument expr1 can have any data type .
NULLIF: compares two expressions and returns null if they are equal or
the first expression it they are not equal.
NVL Functions:
Data types that can be used are date , character ,and number
Ex2: NVL(hire-date,’01-jan-97’)
You can use NVL value to convert any data type ,but the return value is
always the same as the data type of expr1.
NVL2 mines first expression .if the first expression is not null , then the
NVL2 returns second expression. If the first expression is null then
NVL2 returns third expression.
Syntax: NVL2(expr1,expr2,exor3)
The arguments expr2 and expr3 can have any data type except long .
If data types of expr2 and expr3 are diff.the oracle server converts expr3
to the Data type of expr2 before comparing them unless expr2 is a null
constant in that Case data type conversion is not necessary.
Data type of return value is always data type of expr2 ,unless expr2 is
char in Which case the return values data type is varchar2.
NULLIF function compares two expressions .if they are equal the
function
Returns null.if they are not equal the function returns the first expression
.
The advantage of coalesce function over the nvl function is that the
coalesce function Can take multiple alternative values.
If the first expression is not null it returns that expression ,other wise it
does coalesce Of the remaining expressions.
Syntax: COALESCE(expr1,expr2------------exprn)
Conditional Expression:
1. case expression
2. decode function
Case expression:
Case expr when comparison---expr1 then returns expr1
[when comparison----expr2 then returns expr2
when comparison---expr3 then returns expr3
-
when comparison-exprn then returns exprn
else
else-expr
end
Case expressions let you use if-then –else logic in sql statements without
having to Invoke procedures.
In simple case oracle searches for the first when then pair for which the
expression
Meets the condition and an else clause exists then oracle returns else –
expr other wise Oracle returns null.
You cannot specify null value for all the return –expr and else-expr.
Ex: Select last-name ,job-id ,salary, case job-id when ‘it-prog’ then
1.10*salary When ‘st-clerk’ then 1.20*salary Else salary END “revised
salary” From employees;
Decode(col/expression,search1,result1 [,search2,result2,------,]
[,default])
Equi join: Equi joins are also called Simple joins or Inner joins.
Ex: For example, if you want to display the name and department
number of all the employees who are in the same department as
goyal: you can start by making the following decision free .
Non-Equijoins:
NOTE: other conditions , such as <= and >= can be used , but
BETWEEN is the simplest.
Outer joins:
- We use an outer join to see rows that do not meet the join
condition .
- The outer join operator is the PLUS sign(+).
The missing rows can be returned if an outer join operator is used in the
join condition .
- The outer join operator can appear on only one side of the expression
the side that has information missing.
Cross join :
- The cross join clause produces the cross product of two tables.
Natural join:
- The natural join clause is based on all columns in the two tables
that have the same name.
- It selects rows from the two tables that have equal value from all
matched columns.
- If the columns having the same names have different datatypes , an
error is returned.
Ex: Select department_id,department_name,location_id,city from
departments natural join location.
- If several columns have the same names but the data types do not
match, then
Natural join clause can be modified with the USING clause to
specify the
Column that should be used for an equi join
- use the using clause to match 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.
- the join condition for the natural join is basically an equi join of
all columns with the same name.
- To specify arbitrary conditions or specify columns to join , the ON
clause is used
- The join condition is separated from other search conditions.
- The ON clause makes code easy to understand.
- The join between two tables that returns the results of the inner
join as well as unmatched rows left(or right) tables is a left (or
right) outer join
- A join between the two tables that returns the results of an inner
join as well as the results of the left and right join is a full outer
join
Oracle Sql:1999
Equi join Natural/Inner join
Outer join Left Outer join
Self join Join ON
Non-equi join Join Using
Cartesian Product Cross join
- AVG([Distinct/All]n)
-
- COUNT({*|[Distinct/All]Expr})
-
- MAX([Distinct/All] Expr)
-
- MIN([Distinct/All] Expr)
-
- STDDEV([Distinct/All]x)
-
- SUM([Distinct/All]n)
-
- VARIANCE([Distinct/All]x).
[where condition]
[Group by column]
[Order by column];
Count(*)
Count(expr)
Count(Distinct expr)
- using where clause you can include rows before dividing them into
groups.
- you must include the columns in the group by clause.
- You cannot use a column alias in the group by clause.
- By default it ,rows are sorted by ascending order of the columns
included in the group by list.you can override this by using order
by clause.
Note: The group by column does not have to be in the select list .
Ex: Select avg(salary) from employees group by department _id;
Grouping By More Than One Column:
Having Clause:
[where condition]
- Oracle server performs the following steps when we use the having
clause
3. the group that match the criteria in the having clause are
displayed.
Note: the having clause can precede the group by clause but it is
recommended that you place the group by clause first because it is
more logical.
Note: The oracle server imposes no limit on the number of sub queries
the limit is releated to the buffer size that the query uses.
Types Of Subqueries
Sub query
Main Query
Sub Query
Returns
St-clerk,St-man
Note: There are also multiple – column subqueries.
Operator Meaning
= Equal to
> Greater than
>= Greater than or Equal to
< Less than
<= Less than or Equal to
<> Not Equal to
Note: The outer and inner queries can get data from different tables.
Operator Meaning
IN Equal to any member in the list
ANY Compare value to each values
returned by the subquery
ALL Compare value to every value
retterned by the subquery
Note: When using some or ANY you often use the DISTINCT
keyword to prevent rows from being selected several times.
Notice that the null value as part of the results set of a subquery is not a
problem if you e IN operater .the IN operater is equivalent to=ANY, for
example ,to display the employees who have subordinates ,use the
following sql statement.
Insert Statement:
Note: List values in the default order of the columns in the table.
-To create copy of the rows of a table, use select * in the subquery.
Ex: Insert into copy_emp select * from employees;
-All rows in the table are modified if you omit the where clause.
Removing a row from a table: After all the rows has been eliminated
with the DELETE statement only the data structure of the table
remains.A more efficient method of emptying a table is with the
truncate statement.you can use the truncate statement to quickly remove
all rows from the table or cluster.Removing rows with the truncate
statement is faster than removing rows with the delete staement for the
follwing reasons
The truncate statement is DDL statement and generates no
rollback information.
Truncating a table does not fire the delete triggers of the table
If the table is the parent of a referential integrity constriant, you
cannot truncate the table.
Note: The delete statement does not ask for confirmation.How ever
the delete operation is not made permanent until the date transaction
is commited. Therefore youu can undo the operation with the
ROLLBACK statement.
Error at line 1
- 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 values
should be applied to data.
- Explicit defaults can be used in insert and update statements to
identify a default column value.If no default value exists, a null
values is used.
Ex: Default with insert
Insert into departments (department_id,
department_name,manager_id) values(300,’ engineering’,default);
The merge statement is deterministic you cannot update the same row
of the target table multiple times in the same merge statement.
Controlling Transcations:
Statement Description
Commit Ends the current transaction by
making al pending data changes
permanent
SavePoint Marks the savepoint with in the
current transaction
Rollback Rollback ends the current
transaction by discarding all
pending data changes
Rollback to Savepoint Rollback to savepoint roll back
the current transaction to the
specified savepoint, thereby
discard any changes and or
savepoints created after the
savepoint to which you are
rolling back.If you omit to
savepoint clause the rollback
statement rollbacks entire
transcation as savepoints are
logical there is no way to list the
savepoint you have created.
Note: Savepoints are not schema objects and cannot be referenced in the
data dictionary.
Update……..
Savepoint update_done;
Savepoint created
Insert…..
Rollback to update_done;
Rollback complete.
Note: if you create a second savepoint with the same name as an earlier
savepoint,the earlier savepoint is deleted.
Status Circumstances
Automatic Commit DDL or DCL statement is issued
or isql*plus exited normally or
without explicitly issuing
commit or rollback commands
Automatic Rollback Abnormal termination of
isql*plus or system failure.
Note: With the oracle server data changes can actually be written to the
database files before transactions are committed,but they are still only
temporary.
Note: By default oracle server has row level locking.It is possible to alter
the default locking mechanism.
Note: Commit ensures that two related operations occur togethere or not
at all in this case commit prevents empty departments from being
created.
Oracle issues an implicit commit before and after any data definition
language(DDL) statement.So even if your DDL statement does not
execute successfully you cannot roll back the previous statement
because the server issued the commit.
Read Consistency:
- The database reader and writer are ensured a consistent view of the
data
- Readers do not view data that is in the process of being changed.
- Writers are ensured that the changes to the database are done in a
consistent way.
- Changes made by one writer do not disrupt or conflict with
cahnges another writer is making.
Creating And Managing Tables
Database Objects:
Object Description
Table Basic unit of storage composed
of rows and columns
View Logically represents subsets of
data from one or more tables
Sequence Index Numeric value generator
Index Improves the performance of
some queries
Synonym Gives alternative names to
objects
Create Table:
Tables can be created at any time even while users are using the
database.
You donot specify size of any table.The size is ultimately defined by the
amount of space allocated to the database as awhole.It is important
however to estimate how much space a table will use over time.
If a table does not belong to the user the owners name must be prefixed
to the table.
Tables are categorized in two ways user tables and data dictionary.
Collection of views and tables in the oracle database are known as data
dictionary.This collection is created and maintained by orcle server and
contains information about database.
Prefix Description
User_ These views contains
information about objects
owned by the user.
All_ These views contain information
about all of the tables accessible
to the user
Dba_ These views are restricted views
which can be acccessed only by
people who has been assigned
DBA role
V$ These views are dynamic
performance views, database server
performance memory and locking
Quering the data dictionary:
You can query the data dictionary tables to view various database
objects owned by you. The data dictionary tables frequently used are
those
User_tables
User_objcets
User_catalog
Ex: Select * from user_catalog;
TO create a table with the same structure as an existing table but with
out the data from the exixting table use a subquery with a where clause
that always evaluate as false.
If a table already contains rows when a column is added then the new
column is initially null for all the rows.
GuideLines:
Drop:
Guidelines:
Note: When a column is dropped fronm a table any other columns in that
table that are marked with setunused option are dropped too.
The set unused option marks one or more columns as unused so that they
can be dropped when the demand on system resources is
lower.Specifying this clause does not actually remove the target columns
from each row in the table.Therefore the response time is faster than if
you executed the drop clause. Unused columns are treated as if they
were dropped even though their column data remains in the tables
rows.After the column has been marked as unused you have no acess to
that column. A select * query will not retreive the data from unused
columns. In addition the names and types of columns marked unused
will not be described using a describe and you can add to the table a new
column with same name as an uuused column. Set unused information is
stored in user_unused_col_tabs dictionary view.
The drop unused columns removes from the table all columns currently
marked as unused.
Dropping a table:
Ex: Drop table dept80;
Guidelines:
ALL_COL_COMMENTS
USER_COL_COMMENTS
ALL_TAB_COMMENTS
USER_TAB_COMMENTS
Not Null: Specifies that the column cannot contain a null value.
You can view the constraint defined for a specific table by looking at
the USER_CONSTRAINTS data dictionary table.
Constraints are usually created at the same time as the table. Constraints
can be added to a table after its creation and also temporarily disabled.
Unique constraints allows the input of nulls unless you also define not
null constraint on the same column. In fact any number of rows can
include nulls for the columns with out not null constraints because nulls
are not considered equal to anything. A null in a column always satisfy a
unique constraint.
A table can have only one primary key constraint but can have several
unique constraints.
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, not
physical pointers.
You cannot create a foreign key ithout existing primary key values.
The foreign key can also be defined at the column level provided the
constraint is based on a single column. The syntax differs in that the
keywords foreign keys donot appear.
Foreign Key: Defines the column in the child table at the table
constraint level.
On Delete Cascade: Delete the dependent rows in the child table when
a row in the parent table is deleted.
The default behavior is called the restrict rule, which disallows the
update or deletion of referenced data.
Without the on delete cascade or the on delete set null options the row
in the parent table cannot be deleted if it is referenced in the parent table.
Check Constraint:
It defines a condititon that each row must satisfy the condition can use
the same constructs as query conditions with the following exceptions
A single column can have multiple check constraints which refer to the
column in its definition. There is no limit to the number of check
constraints which you can define on a column.
In the Syntax:
Guidelines: you can add, enable or disable a constraint but you cannot
modify its structure
Note: you can define Not Null column only if the table is empty or if the
column has a value for every row.
Add aforeign key constraint to the employees table indicating that the
manager must already exist as a valid employee in the employees table.
To add a not null constraint use the alter table modify syntax.
Ex: Remove the primary key constraints on the departments table and
drop the associated foreign key constraint on the employees
department_id column
Alter table departments drop primary key cascade;
If you enable a constraint that constraitnt applies to all the data in the
table. All the data in the table must fit the constraint.
You can use the enable clause in both the create table statement and the
alter tablel statement.
Enabling a primary key constraint that was disabled with the cascade
option does not enable any foreign keys that are dependent upon the
primary key.
Ex: create table test1( pk number primary key, fk number, col1 number,
col2 number, constraint fk_constraint foreignkey(fk) references test1,
constraint ck1 check(pk>0 and col1>0), constarint ck2 check(col2>0));
Viewing Constraints:
After creating a table you can confirm its existence by issuing a describe
command. The only constraint that you can verify is the not null
constraint. The view all the constraints on your table query the
user_constraints table.
Note: Constraints that are not named by the table owner receive the
system assigned constraitnt name. In constraint type C stands for check,
P stands for primary key, R for referential integrity and U for unique
key. Notice that the NOT NULL constraint is really a check constraint.
Select constraint_name, constraint_type, search_condition from
user_constraints where table_name=’employees’;
We use views
- To restrict data access
- To make complex queries easy
- To provide data independence
- To provide different views of the same data
Creating a view:
With check option: Specifies that only rows accessible to the view can
be inserted or updated.
When you access data using a view the oracle server performs the
following operations
Modifying a view:
With the or replace option a view can be created even if one exists with
this name already thus replacing old version of the view for ots owner.
You can ensure that DML operations performed on the view stay within
the domain of the view by using the with check option.
Any attempt to change the department number for any row in the view
fails because it violates the with check option constraint.
You can ensure that no DML operations occur by adding the with read
only option to your view definition.
Removing a view:
Inline view:
1. Sequence
2. Index
3. Synonym
[increment by n]
[start with n ]
[{cycle| no cycle}]
[{ cache n | no cache}].
Cache n | no cache: specifies how many values the oracle server
preallocats and keep In memory (by default ,the oracle server caches 20
values).
Note: If sequence values are cached ,they will be lost if there is a system
failure.
Confirming sequences:
Verify your sequence values in the user_ sequence data dictionary table.
Note: The last number columns displays the next available sequence
value. It returns a Unique value every time it is referenced ,even for a
different users.
The select list of select statement that is not a part of the subquery.
Using a Sequence:
A rollback occurs
If the sequence was created with nocache view the next available
value,by Querying the user sequence table.
Modifying a Sequence :
Increment by 20
No cache
No cycle;
Guidelines for modifying:
You must be the owner or the alter privilege for the sequence .
Removing a Sequence:
Remove a sequence from the data dictionary by using the drop sequence
statement.
An index provides direct and fast access to rows in a table ,its purpose is
to reduce the necessity of disk i/o by using an indexed path to locate data
quickly. The index is used and maintained automatically by the oracle
server .once the index is created ,nodirect activity is required by the user
Note: when you drop a table ,corresponding indexes are also dropped.
The user_ind_columns view contains the index,the table name ,and the
column name.
The index expression is built from table columns ,constants sql functions
and user defined functions .
Removing a Index:
You cannot modify a index ,to change an index you must drop it and
recreate it.
SET OPERATORS
Intersect
Minus
Union all: All rows selected by either query , including all duplicates.
Minus : All distinct rows that are selected by the first select statement
and not selected in the second select staement.
Union: The no.of columns and the data types of the columns being
selected must be identical in all the select statements used in the query
the names of the columns need not be identical.
Union all: Unlike union ,duplicate rows are not eliminated and the
output is not sorted by default.
Note: With the exception of the above , the guidelines for union and
union all same.
Reversing the order of the intersected tables does not alter the result.
Intersect
Minus: The number of columns and the data types of the columns being
select ed by the select statements in the queries must be identical in all
the select statements used in the query the names of the columns need
not be identical .
All of the columns in the where clause most be in the select clause for
the minus operator to work.