II DCME DBMS Unit-2
II DCME DBMS Unit-2
Lexical Conventions
SQL statements are composed of commands variables and operators which are described m detail in
this and subsequent chapters A SQL statement is constructed from
- Characters A through Z (or the equivalent from your database character ser)
- Numbers 0 through 9
- Spaces
- The following special characters : + - * = ? ! @ ( ) _ . , < > | $ #
Naming in SQL: The following rules apply to the names of schema objects in Oracle •
❖ They may comprise 1 to 30 alphanumeric characters
❖ They must begin with a letter
❖ They may include an underscore (_) They may include a dollar (5) or pound sign (#) although
Oracle discourages the use of these characters They may not be a reserved word
❖ They may not be the name of a SQL command
• Oracle JDeveloper development environment for Java It supports editing, compiling and debugging
PL/SQL applications.
.Oracle HTML DB is used for developing and deploying database related Web applications PL/SQL:
1 | Page
UNIT-II (DBMS)
Generally, you reference schema objects in SQL statements using the following syntax
Schema object_name.object_part@dblink
These syntax elements have the following meaning
• Schema: The name of the schema that owns the object. In Oracle, a schema corresponds one-to-one
with a username if the schema is omitted from a reference to a schema object then the username that is
currently logged in a used by default.
• Object name: The name of the object being referenced, such as a table that
• Object part: The name of a part of an object for those schema objects have a part such as a column
of a table
For example:
SELECT ename, empno, sal
FROM scott.emp@test
WHERE sal> 500;
TEXT OR CHARACTER
Character or text literals are written as sequence of strings written as a sequence character enclosed in
single quotes
2 | Page
UNIT-II (DBMS)
Example:
❖ 'Structured Query Language'
❖ 'Jessica Pearson '
❖ '08065-CM-009'
BIT STRING
A bit string is written either as a sequence of Os and is enclosed in single quotes and preceded by the
letter ' B ' or as sequence of hexadecimal digits enclosed in single quotes and preceded by letter 'X'
Example:
❖ B '1011011'
❖ B'1'
❖ X'A5'
Numeric Literals are used to construct exact numbers and approximate number Syntax rules of
numeric literals are:
A numeric literal can be written in signed integer form, signed real numbers without exponents, or real
numbers with exponents
Examples of Numeric Literals
Quote:
❖1
❖ -22
❖ 33.3
❖ -44 .44
❖ 55.555e5
Date and Time Literals are used to construct date and time values The syntax of date and time literals
are
DATA TYPES:
1. CHAR (Size): This data type is used to store character strings values of fixed length. The size in
brackets determines the number of characters the cell can hold. The maximum number of character is
255 characters.
2. VARCHAR (Size) / VERCHAR2 (Size): This data type is used to store variable length
alphanumeric data. The maximum character can hold is 2000 character.
3. NUMBER (P, S): The NUMBER data type is used to store number (fixed or floating point).
124
Number of virtually any magnitude may be stored up to 38 digits of precision. Number as large as 9.99 * 10 .
3 | Page
UNIT-II (DBMS)
4. DATE: This data type is used to represent date and time. The standard format is DD MM-YY as in
17-SEP-2009. To enter dates other than the standard format, use the appropriate functions. Date time
stores date in the 24-Hours format. By default the time in a date field is 12:00:00 am, if no time
portion is specified. The default date for a date field is the first day the current month.
5. LONG: This data type is used to store variable length character strings containing up to 2GB. Long
data can be used to store arrays of binary data in ASCII format. LONG values cannot be indexed, and
the normal character functions such as SUBSTR cannot be applied.
6. RAW: The RAW data type is used to store binary data, such as digitized picture or image. Data
loaded into columns of these data types are stored without any further conversion. RAW data type can
have a maximum length of 255 bytes. LONG RAW data type can contain up to 2GB.
SQL STATEMENTS:
1. DATA DEFINITION LANGUAGE (DDL): The Data Definition Language (DDL) is used to
create and destroy databases and database objects. These commands will primarily be used by
database administrators during the setup and removal phases of a database project. Let's take a look at
the structure and usage of four basic DDL commands:
1. CREATE 2. ALTER 3. DROP 4. RENAME 1. CREATE:
(a)CREATE TABLE: This is used to create a new relation and the corresponding Syntax: CREATE
TABLE relation_name
Example:
SQL>CREATE TABLE Student (sno NUMBER(3),sname CHAR(10),class CHAR(5));
(b)CREATE TABLE..AS SELECT....: This is used to create the structure of a new relation from the
structure of an existing relation.
4 | Page
UNIT-II (DBMS)
2. ALTER:
(a)ALTER TABLE ...ADD...: This is used to add some extra fields into existing relation. Syntax:
ALTER TABLE relation_name ADD(new field_1 data_type(size), new field_2 data_type(size),..);
2
Example : SQL>ALTER TABLE std ADD(Address CHAR(10));
(b)ALTER TABLE...MODIFY...: This is used to change the width as well as data type of fields of
existing relations.
Syntax: ALTER TABLE relation_name MODIFY (field_1 newdata_type(Size), field_2
newdata_type(Size),....field_newdata_type(Size));
Example:SQL>ALTER TABLE student MODIFY(sname VARCHAR(10),class VARCHAR(5));
3. DROP TABLE: This is used to delete the structure of a relation. It permanently deletes the records
in the table.
Syntax: DROP TABLE relation_name;
4. RENAME: It is used to modify the name of the existing database object. Syntax: RENAME
TABLE old_relation_name TO new_relation_name; Example: SQL>RENAME TABLE std TO std1;
5. TRUNCATE: This command will remove the data permanently. But structure will not be removed.
Syntax: TRUNCATE TABLE <Table name>
5 | Page
UNIT-II (DBMS)
✓ By using truncate command data will be removed permanently & will not get back where as by
using delete command data will be removed temporally & get back by using roll back command.
✓ By using delete command data will be removed based on the condition where as by using truncate
command there is no condition.
✓ Truncate is a DDL command & delete is a DML command.
6 | Page
UNIT-II (DBMS)
3. DELETE-FROM: This is used to delete all the records of a relation but it will retain the structure
of that relation.
4.
a) DELETE-FROM: This is used to delete all the records of relation. Syntax: SQL>DELETE FROM
relation_name;
b) DELETE -FROM-WHERE: This is used to delete a selected record from a relation. Syntax:
SQL>DELETE FROM relation_name WHERE condition; Example: SQL>DELETE FROM student
WHERE sno = 2;
2. SELECT FROM: To display a set of fields for all records of relation. Syntax: SELECT a set of
fields FROM relation_name;
Example: SQL> select deptno, dname from dept; DEPTNO
DNAME
------- ----------
10 ACCOUNTING
20 RESEARCH
30 SALES
7 | Page
UNIT-II (DBMS)
3. SELECT - FROM -WHERE: This query is used to display a selected set of fields for a selected
set of records of a relation.
Syntax: SELECT a set of fields FROMrelation_name WHERE condition; Example: SQL> select *
FROM dept WHERE deptno<=20;
DEPTNO DNAME LOC
------ ----------- ------------
5
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
4. SELECT - FROM -GROUP BY: This query is used to group to all the records in a relation
together for each and every value of a specific key(s) and then display them for a selected set of fields
the relation.
Syntax: SELECT a set of fields FROM relation_name GROUP BY field_name;
Example: SQL> SELECT EMPNO, SUM (SALARY) FROM EMP GROUP BY EMPNO; EMPNO
SUM (SALARY)
------ ---------- 1
3000
2 4000
3 5000
4 6000
4 rows selected.
5. SELECT - FROM -ORDER BY: This query is used to display a selected set of fields from a
relation in an ordered manner base on some field.
Syntax: SELECT a set of fields FROM relation_name ORDER
BY field_name;
Example: SQL> SELECT empno,ename,job FROM emp ORDER BY job; EMPNO ENAME JOB
----- --------- --------
4 RAVI MANAG
ER
8 | Page
UNIT-II (DBMS)
2 aravind Manager
1 Sagar clerk
3 Laki clerk
4rows selected.
6. JOIN using SELECT - FROM - ORDER BY: This query is used to display a set of fields from
two relations by matching a common field in them in an ordered manner based on some fields.
Syntax: SELECT a set of fields from both relations FROM relation_1, relation_2 WHERE
relation_1.field_x = relation_2.field_y ORDER BY field_z;
6 Example: SQL>SELECT empno,ename,job,dname FROM emp,dept WHERE emp.deptno = 20
ORDER BY job;
EMPNO ENAME JOB DNAME
------ ------ ------- ----------
7788 SCOTT ANALYST ACCOUNTI
NG
7902 FORD ANALYST ACCOUNTI
NG
------
7566 JONES MANAGE R OPERATION S
7566 JONES MANAGE R SALES
20 rows selected.
9 | Page
UNIT-II (DBMS)
7876 4400
8.HAVING:
This will work as where clause which can be used only with group by because of
absence of where clause in group by.
Ex:
SQL> select deptno,job,sum(sal) tsal from emp group by deptno,job having sum(sal) > 3000;
SQL> select deptno,job,sum(sal) tsal from emp group by deptno,job having sum(sal) > 3000
order by job;
A transaction is a logical unit of work. All changes made to the database can be referred
to as a transaction. Transaction changes can be made permanent to the database only if they are
committed a transaction begins with an executable SQL statement & ends explicitly with either
role back or commit statement.
1. COMMIT: This command is used to end a transaction only with the help of the commit
command transaction changes can be made permanent to the database.
Syntax: SQL>COMMIT;
Example: SQL>COMMIT
2. SAVE POINT: Save points are like marks to divide a very lengthy transaction to smaller
once. They are used to identify a point in a transaction to which we can latter role back.
Thus, save point is used in conjunction with role back.
10 | Page
UNIT-II (DBMS)
8
3. ROLE BACK: A role back command is used to undo the current transactions. We can
role back the entire transaction so that all changes made by SQL statements are undo (or)
role back a transaction to a save point so that the SQL statements after the save point are role
back.
Syntax: ROLE BACK( current transaction can be role back) ROLE BACK to save point ID;
1. GRANT: The GRANT command allows granting various privileges to other users and
allowing them to perform operations with in their privileges
For Example, if a uses is granted as „SELECT‟ privilege then he/she can only view data but
cannot perform any other DML operations on the data base object GRANTED privileges can
also be withdrawn by the DBA at any time
2. REVOKE: To with draw the privileges that has been GRANTED to a uses, we use the
REVOKE command.
11 | Page
UNIT-II (DBMS)
1. NOT NULL: When a column is defined as NOTNULL, then that column becomes a
mandatory column. It implies that a value must be entered into the column if the record is to
be accepted for storage in the table.
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) NOT NULL, );
Example:
CREATE TABLE student (sno NUMBER(3)NOT NULL, name CHAR(10));
2. UNIQUE: The purpose of a unique key is to ensure that information in the column(s) is
unique i.e. a value entered in column(s) defined in the unique constraint must not be repeated
across the column(s). A table may have many unique keys.
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) UNIQUE, ….);
Example:
CREATE TABLE student (sno NUMBER(3) UNIQUE, name CHAR(10));
3. CHECK: Specifies a condition that each row in the table must satisfy. To satisfy the
constraint, each row in the table must make the condition either TRUE or unknown (due to a
null).
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) CHECK(logical
expression), ….);
12 | Page
UNIT-II (DBMS)
10
✓ It must uniquely identify each record in a table.
✓ It must contain unique values.
✓ It cannot be a null field.
✓ It cannot be multi port field.
✓ It should contain a minimum no. of fields necessary to be called unique. Syntax:
CREATE TABLE Table_Name(column_name data_type(size) PRIMARY KEY, ….);
Example:
CREATE TABLE faculty (fcode NUMBER(3) PRIMARY KEY, fname CHAR(10));
5. FOREIGN KEY: It is a table level constraint. We cannot add this at column level. To
reference any primary key column from other table this constraint can be used. The table in
which the foreign key is defined is called a detail table. The table that defines the primary
key and is referenced by the foreign key is called the master table.
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) FOREIGN
KEY(column_name) REFERENCES table_name);
13 | Page
UNIT-II (DBMS)
(Or)
Syntax: ALTER TABLE table_name ADD CONSTRAINT constraint_name
PRIMARY KEY(colname)
(or)
Syntax: ALTER TABLE student DROP CONSTRAINT constraint_name;
OPERATORS:
Operators :-
An operator manipulates individual data items and returns a result. The data items
are called operands or arguments.
Operators are represented by special characters or by keywords. These can be
divided into 4 types.
1) Arithmetic operators
2) Comparison operators
3) Logical operators
4) Set operators
Arithmeticoperators :-
+, -, *, /
14 | Page
UNIT-II (DBMS)
12
Comparison operators:-
Logical operators: -
AND , OR , NOT
Set Operators: -
Set operators combine the results of two component queries into a single result.
Queries containing set operators are called compound queries.
OPERATORS RETURNS
UNION All rows selected by either query.
UNION ALL rows selected by either query, including all duplicates.
INTERSECT All distinct rows selected by both queries.
MINUS All distinct rows selected by the first query but not the second.
1.Arithmetic Operators
Arithmetic operators can perform arithmetical operations on numeric operands
involved. Arithmetic operators are
addition(+),
subtraction(-),
multiplication(*)
and division(/).
The + and - operators can also be used in date arithmetic.
Comparison operators:-
Ex:=
<
15 | Page
UNIT-II (DBMS)
SQL> select * from student where no < 2;
14
>
<=
>=
!=
Logical operators: -
AND : -This will gives the output when all the conditions become true. Syntax:
select * from <table name> where <condition1> and <condition2> and .. <conditionn>;
OR:-This will give the output when either of the conditions becomes true. Syntax: select *
BETWEEN:-
This will gives the output based on the column and its lower bound, upperbound.
Syntax: select * from <table_name> where <col> between <lower bound> and <upper
bound>;
Ex:SQL> select * from student where marks between 200 and 400;
NOT BETWEEN:-This will gives the output based on the column which values are not in
its lower bound,upperbound.
16 | Page
UNIT-II (DBMS)
Syntax: select * from <table_name> where <col> not between <lower bound> and <upper
bound>;
Ex: SQL> select * from student where marks not between 200 and 400; IN:-This will gives
the output based on the column and its list of values specified. Syntax: select * from
<table_name> where <col> in ( value1, value2, value3 … valuen); Ex: SQL> select * from
NOT IN:- This will gives the output based on the column which values are not in the list of
valuesspecified.
Syntax: select * from <table_name> where <col> not in ( value1, value2, value3 … valuen);
NULL:-
This will gives the output based on the null values in the specified column. Syntax: select *
NOT NULL:- This will gives the output based on the not null values in the specified
column.
UNION:-
This will combine the records of multiple tables having the same structure. Ex: SQL> select
UNION ALL:-
This will combine the records of multiple tables having the same structure but
includingduplicates.
Ex: SQL> select * from student1 union all select * from student2;
INTERSECT :-
17 | Page
UNIT-II (DBMS)
This will give the common records of multiple tables having the same structure. Ex: SQL>
MINUS :-
This will give the records of a table whose records are not in other tables having the
samestructure.
FUNCTIONS
• Numeric functions
• String functions
• Date functions
• Conversion functions
NUMERIC FUNCTIONS
18 | Page
UNIT-II (DBMS)
SQL> update Mahesh set sno=abs(sno);
POWER:-
dual;
e) CEIL: This will produce a whole number that is greater than or equal to the specified
value.
Ex: SQL> select ceil(5), ceil(5.1), ceil(-5), ceil( -5.1), ceil(0), ceil(null) from dual;
f) FLOOR
This will produce a whole number that is less than or equal to the specified value.
Ex:
SQL> select floor(5), floor(5.1), floor(-5), floor( -5.1), floor(0), floor(null) from dual;
g) ROUND
19 | Page
UNIT-II (DBMS)
h) GREATEST
i) LEAST
Ex: SQL> select least(1, 2, 3), least(-1, -2, -3) from dual;
j) COALESCE
FUNCTIONS
Initcap
Upper
Lower
Length
Rpad
Lpad
Ltrim
Rtrim
Trim
Translate
Replace
Soundex
Concat (‘ || ‘ Concatenation operator)
Ascii
20 | Page
UNIT-II (DBMS)
Chr
Substr
Instr
Decode
Greatest
Least
Coalesce
a) INITCAP
Ex:
b) UPPER
This will convert the string into uppercase. Syntax: upper (string)
c) LOWER
This will convert the string into lowercase. Syntax: lower (string)
21 | Page
UNIT-II (DBMS)
SQL> select lower(sname) from students;
d) LENGTH
e) RPAD
This will allows you to pad the right side of a column with any set of characters. Syntax:
will allows you to pad the left side of a column with any set of characters. Syntax: lpad
g) LTRIM
This will trim off unwanted characters from the left end of string. Syntax: ltrim (string
[,unwanted_chars])
student_name=ltrim(student_name,’s’);
h) RTRIM
22 | Page
UNIT-II (DBMS)
This will trim off unwanted characters from the right end of string. Syntax: rtrim (string [,
unwanted_chars])
student_name=rtrim(student_name,’s’);
i) TRIM
This will trim off unwanted characters from the both sides of string. Syntax: trim
SQL> select trim( leading'i' from 'indiani') from dual; -- this will work as LTRIM SQL>
select trim( trailing'i' from 'indiani') from dual; -- this will work as RTRIM sQL>update
j) TRANSLATE
This will replace the set of characters, character by character. Syntax: translate (string,
old_chars, new_chars)
k) REPLACE
This will replace the set of characters, string by string. Syntax: replace (string, old_chars [,
new_chars])
l) SOUNDEX
This will be used to find words that sound like other words, exclusively used in where
clause.
23 | Page
UNIT-II (DBMS)
Syntax: soundex (string)
m) CONCAT
n) ASCII
This will return the decimal representation in the database character set of the
firstcharacter of the string.
Ex:
22
SQL> select ascii('a'), ascii('apple') from dual;
o) CHR
This will return the character having the binary equivalent to the string in either thedatabase
character set or the national character set.
p) SUBSTR
dual;
12345678
24 | Page
UNIT-II (DBMS)
COMPUTER
-8 -7 -6 -5 -4 -3 -2 -1
q) INSTR
This will allows you for searching through a string for set of characters. Syntax: instr
For every value of field, it will checks for a match in a series of if/then tests. Syntax: decode
s) GREATEST
This will give the greatest string.
t) LEAST
This will give the least string.
DATE FUNCTIONS
Sysdate
25 | Page
UNIT-II (DBMS)
Current_date
Current_timestamp
Systimestamp
Localtimestamp
Dbtimezone
Sessiontimezone
To_char
To_date
Add_months
Months_between
Next_day
Last_day
Extract
Greatest
Least
Round
Trunc
New_time
Coalesce
Oracle default date format is DD-MON-YY.We can change the default format to our
desired format by using the following command.
SQL> alter session set nls_date_format = ‘DD-MONTH-YYYY’;
But this will expire once the session was closed.
a) SYSDATE
26 | Page
UNIT-II (DBMS)
Ex:
b) CURRENT_DATE
c) CURRENT_TIMESTAMP
This will returns the current timestamp with the active time zone information. Ex:SQL>
d) SYSTIMESTAMP
This will returns the system date, including fractional seconds and time zone of the
database.
e) LOCALTIMESTAMP
This will returns local timestamp in the active time zone information, with no time
zoneinformation shown.
Ex:SQL> select localtimestamp from dual;
f) DBTIMEZONE
This will returns the current database time zone in UTC format. (Coordinated Universal
Time)
g) SESSIONTIMEZONE
This will returns the value of the current session’s time zone.
27 | Page
UNIT-II (DBMS)
• MONTH -- Fully spelled out month
• RM -- Roman numeral month
• DY -- Three letter abbreviated day
• DAY -- Fully spelled out day
• Y -- Last one digit of the year
• YY -- Last two digits of the year
• YYY -- Last three digits of the year
• YYYY -- Full four digit year
h) TO_CHAR
This will be used to extract various date formats.The available date formats as follows.
Ex:
SQL> select to_char(sysdate,'dd month yyyy hh:mi:ss am dy') from dual; SQL> select
i) TO_DATE
If you are not using to_char oracle will display output in default date format.
j) ADD_MONTHS
28 | Page
UNIT-II (DBMS)
no_of_months is zero then it will display the same date.
This will give difference of months between two dates. Syntax: months_between (date1,
date2)
l) NEXT_DAY
This will produce next day of the given day from the specified date. Syntax: next_day (date,
day)
Ex:
m) LAST_DAY
Ex:
SQL> select last_day(to_date('24-dec-2006','dd-mon-yyyy'),'sun') from dual;
n) EXTRACT
Syntax: extract ((year | month | day | hour | minute | second), date) Ex:
29 | Page
UNIT-II (DBMS)
o) GREATEST
Ex:
p) LEAST
q) ROUND
Round will rounds the date to which it was equal to or greater than the given date. Syntax:
from dual;
s) NEW_TIME
30 | Page
UNIT-II (DBMS)
TIMEZONES
t) COALESCE
Ex:
CONVERSION FUNCTIONS:-
Bin_to_num
Chartorowid
Rowidtochar
To_number
To_char
To_date
a) BIN_TO_NUM
31 | Page
UNIT-II (DBMS)
Syntax: bin_to_num( binary_bits)
Ex:
SQL> select bin_to_num(1,1,0) from dual;
b) CHARTOROWID
This will convert a character string to act like an internal oracle row identifier or rowid.
c) ROWIDTOCHAR
This will convert an internal oracle row identifier or rowid to character string.
d) TO_NUMBER
e) TO_CHAR
This will convert a number or date to character string.
SQL> select to_char(sysdate,'d') from dual;
f) TO_DATE
This will convert a number, char or varchar to a date.
SQL> select to_date('26-dec-06','dd-mon-yy') from dual;
GROUP FUNCTIONS:
• Sum
• Avg
• Max
• Min
• Count
Group functions will be applied on all the rows but produces single output. a) SUM
This will give the sum of the values of the specified column. Syntax: sum (column)
b) AVG
This will give the average of the values of the specified column. Syntax: avg (column)
c) MAX
32 | Page
UNIT-II (DBMS)
This will give the maximum of the values of the specified column. Syntax: max (column)
d) MIN
This will give the minimum of the values of the specified column. Syntax: min (column)
e) COUNT
This will give the count of the values of the specified column.
JOINS
A join is actually performed by the where clause which combines the specified rows of
tables.
If a join involves in more than two tables then oracle joins first two tables based on the
joins condition and then compares the result with the next table and so on.
TYPES
Equi join
Non-equi join
Self join
Cross join
Outer join
Left outer
Right outer
Full outer
Inner join
EQUI JOIN
33 | Page
UNIT-II (DBMS)
A join which contains an ‘=’ operator in the joins condition.
CLAUSE
NON-EQUI JOIN
A join which contains an operator other than ‘=’ in the joins condition. Ex:
SQL> select empno,ename,job,dname,loc from emp e,dept d where e.deptno > d.deptno;
SELF JOIN
Ex:
e1.empno=e2.mgr;
CROSS JOIN
Ex:
OUTER JOIN
Outer join gives the non-matching records along with matching records.
This will display the all matching records and the records which are in left hand side table
those that are not in right hand side table.
Ex:
34 | Page
UNIT-II (DBMS)
SQL> select empno,ename,job,dname,loc from emp e left outer join dept d
on(e.deptno=d.deptno);
This will display the all matching records and the records which are in right hand side table
those that are not in left hand side table.
Ex:
on(e.deptno=d.deptno);
Or
This will display the all matching records and the non-matching records from both tables.
Ex:
on(e.deptno=d.deptno);
INNER JOIN
This will display all the records that have matched.
Ex: SQL> select empno,ename,job,dname,loc from emp inner join dept using(deptno);
35 | Page