0% found this document useful (0 votes)
10 views26 pages

Dbms 2

This document provides an overview of SQL, its evaluation, features, benefits, and its role in database management systems. It explains embedded SQL, lexical conventions, and Oracle tools that support SQL, as well as schema objects and naming conventions. Additionally, it covers data types, pseudo-columns, comments within SQL statements, and various functions used in SQL.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views26 pages

Dbms 2

This document provides an overview of SQL, its evaluation, features, benefits, and its role in database management systems. It explains embedded SQL, lexical conventions, and Oracle tools that support SQL, as well as schema objects and naming conventions. Additionally, it covers data types, pseudo-columns, comments within SQL statements, and various functions used in SQL.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

CM305 –DATABASE MANAGEMENT SYSTEMS UNIT II

UNIT II
Concept of SQL
Understand the concept of SQL: (14-18 M)
• SQL is the language used by RDBMS for database information.
• It enables users to define, access and manage the relational database
• All tasks related to relational data management
I. Creating tables
II. Querying the database information
III. Modifying the data in the database
IV. Deleting the data in the database
V. Granting access to users and so on….
All the above tasks can be performed easily by using SQL.
• The name SQL pronounced as “ess-cue-ell”
• The SQL consists of set of facilities for defining, accessing and managing relational databases.
Evaluation of SQL:
• In 1970 Edgar F codd, member of IBM lab in sanjose, California, published the classic paper called
as, “ a relational model of data for large shared data banks.” Which proposes different principles
of database management, and all these principles are called as relational model.
• With codd’s papers, a great research is going and design number of relational languages. One
such language was “structured English query language”(SEQUEL) defined by Donald chamberlain
and others of the IBM sanjose lab in 1974, and was implemented the IBM model called as
SEQUEL–XRM in 1974-75.
• A revised version of SEQUEL was released in 1976-77 called SEQUEL / 2. This name was later
changed to SQL.
• Another SEQUEL model was developed by IBM called SystemR.
• SystemR is based on SEQUEL/2 or SQL
• ORACLE from relation software Inc.(now called as ORACLE corporation) in 1981.
• IBM announced its SQL product, SQL/DS. This was followed by virtual machine version in 1982.
• In 1983 IBM announced another product called DB2 compatible with SQL/DS.
• The American national standard institute approved the SQl database language project in 1978.
Structured Query Language (SQL): SQL stands for structured query language. It is a tool for
1. Managing
2. Retrieving
3. Organizing data stored by a computer database
When you need to retrieve a data from database. You need SQL language to make the request. DBMS
process SQL request retrieves required data.
Features of SQL:
1. SQL allows you to access a database
2. SQL is an ANSI standard computer language.
3. SQL can execute queries against a database
4. SQL can retrieve data from a database.
5. SQL can insert new records into a database.
6. SQL can delete records from a database.
7. SQL can update records in a database.

Explain the benefits of SQL Benefits of


SQL: The benefits of SQL are
• SQL is an English like language
• Easy to learn
• SQL is non procedural language. SQL specifies what is required and not how it should be done

1
CM305 –DATABASE MANAGEMENT SYSTEMS UNIT II

• More productivity. With a single statement we can perform task like creation of table etc.
• SQL operations are performed at a set level. One select statement can retrieve multiple rows, one
modify statement can modify multiple rows.
• More powerful than record at a time processing languages like COBOL.
• Application portability
• Cross system communication
• SQL standard exists. All RDBMS support SQL.
• Both interactive and embedded access.
• Can be used by specialist and non-specialist
• SQL programming is done at the logical level; there is little need to deal with the details of
implementation.
• SQL provides automatic navigation to data.

Understand the embedded SQL, Lexical conventions, oracle tools support for SQL
Embedded SQL: It is a method of combining the programming language and database manipulation
capabilities of SQL. It allows us to place SQL statements directly into a programs source code. The
program may be written in a language like C, C++, FORTRAN, Pascal etc.
Embedded SQL statements are SQL statements written within application programming
languages and preprocessed by a SQL preprocessor before the application program is compiled.
The SQL standard defines embedding SQL as embedded SQL and the language in which SQL
queries are embedded is referred as host language. A popular host language is C and the mixed C and
embedded SQL is called Pro*c in Oracle and Sybase DBMS.
Steps to write embedded SQL program:
Write a C program with embedded SQL commands and save this file.
Example: int age;
char accno[6];
:
:
scanf(“%d”,&age);
scanf(“%d”,&accno);
EXEC SQL UPDATE ACCOUNT SET age := age where accno := accno;

• Compile this program using Pro*C compiler provided by oracle. It generates a ‘C’ file.
• Compile the .C file using C compiler.
• The compiler creates .exe file, run this file.
Syntax for embedded SQL is
EXEC SQL
<embedded SQL statement>;
END EXEC

Lexical Conventions: SQL statements are composed of commands, variables and operators. A SQL
statement is constructed with
➢ Characters A to Z (or a-z)
➢ Numbers 0 to 9
➢ spaces
➢ special characters: + - * = >? ! @ ( ) - . , < > | $ #
A SQL statement can contain one or more of the following items
1. Tab 2. Carriage return (enter) 3. Multiple spaces 4. comments

2
CM305 –DATABASE MANAGEMENT SYSTEMS UNIT II

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 a underscore( _ )
➢ They may not be a reserved word
➢ They may not be the name of a SQL command
Note: A name may begin with and / or contain any characters if it is enclosed in double quotes.

Oracle Tools Supported for SQL: Oracle provides a number of utilities to facilitate your SQL
development process. The following are the Oracle Tools support for SQL :
➢ SQL*PLUS : SQL*Plus is a command line SQL. It allows direct access to the oracle RDBMS.
➢ PL/SQL: procedural language extension to SQL
➢ SQL*FORM: to design forms
➢ SQL*REPORT: To generate reports
➢ SQL*GRAPH: it is a graphic support tool that translates your SQL
➢ PRO*C: Embedded SQL support
➢ SQL*MENU: To create menus for integrating various applications
➢ ORACLE HTML DB: It is used for developing and deploying database – related web applications.
➢ ORACLE JDEVELOPER: It is a multiple platform integrated development environment for java

Name the objects and parts, and refer them


Schema Objects: “A schema object is a logical collection of data or user objects stored in database.” The
following types of objects are considered schema objects:
➢ Clusters ➢ Packages ➢ Views
➢ database links ➢ Sequences ➢ synonyms
➢ triggers ➢ Stored functions ➢ Tables
➢ Indexes ➢ Stored procedures ➢ snapshots
Parts of Objects: some objects are made up of parts that you must also name, such as:
➢ Columns in a table or view
➢ Integrity constraints on a table
➢ Packaged procedures
➢ Packaged stored functions
➢ Other objects stored within a package
Refer Objects: Generally we refer schema objects in SQL statements using 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. If the schema is omitted then the
currently logged username is taken by default.
object_name : The name of the object being referenced, such as table
object_part : The name of a part of an object, for those schema objects that have a part, such
as a column of a table.
dblink : The name of a database link referencing a remote database
Example: The following SQL statement queries data from a table, which is a schema object
named emp in the schema scott. This schema is located in a remote database and referenced by
database link test:
select ename , empno , sal from scott.emp@test where sal > 5000 ;
Refer the object in remote databases
Objects in Remote Databases: To refer to the objects in database other than local database,
follow the object name with the name of the database to link to that database. A database link is a
schema object that causes Oracle to connect to remote database to access an object there. For

3
CM/IT-306 Relational Data Base Management Systems UNIT II

example, we can query a remote table or view with the SELECT statement. The remote database need
not be an Oracle system.
Syntax:
Database*.domain*.domain+…+*@connect_descriptor+
Where:
Database should specify the name portion of the name of the remote database to which the
database link connects.
Domain should specify the domain portion of the name of the remote database to which the
database link connects.
Connect_descriptor using this, we can create multiple database links to the same database.

Explain literals, text and integers


Literals: literal is a fixed data value (or constant). There are four kinds of literals supported in SQL.
They are
➢ Numeric literals(integer / float) ➢ Date and Time literals
➢ Text or character literals ➢ Bit string literals
Numeric Literals: Numeric literals are used to construct exact numbers and approximate
numbers. A numeric literal can be written in signed integer form, signed real numbers without
exponents or real numbers with exponents.
Ex: 598, -12, 23.369, -456.3, 89.566e3, -665.535e-5
Text or Character literals: Character or text literals are written as sequence of strings enclosed in
single quotes.
Ex: ‘structured query language’, ‘polytechnic’ , ’13030-CM-047’
Date and Time Literals: These are used to construct date and time values. The syntax of date and
time literals are:
1) A date literal is written in the form of “DATE ‘yyyy-mm-dd’”.
2) A time literal is written in the form of “TIMESTAMP ‘yyyy-mm-dd hh:mi:ss’”.
Ex: 15-mar-90
Bit String Literals: A bit string is written as either as a sequence of 0’s and 1’s enclosed in single
quotes and preceded by the letter ‘B’ or a sequence of hexadecimal digits enclosed in single
quotes and preceded by letter ‘X’.
Ex: B`100111’ , B`1’ , X`A5D2’

List and explain the different data types like character, number, long, date, raw and longraw etc.
Data Types: Each literal/column has a data type. The data types are used to specify the type of
the data that will be stored in each column of the table. The following table lists the typical data
types used in Oracle 8i/9i.
Data type SIZE Description
Fixed length character data of length size bytes.
E.g. if the width of a character column is 8 and
Char(size) Up to 2000 bytes
the string stored it in is ‘RDBMS’, it will be stored
as ‘RDBMS_ _ _’
Where size is the number of characters to store.
It accepts variable length strings e.g. if the width
Varchar2(size) Up to 4000 bytes
of a varchar column is 8 and the string ‘RDBMS’
is stored as ‘RDBMS’
Maximum precision is 38 Where ‘p’ is the precision and ‘s’ is the scale. E.g.
Number(p,s)
digits number (7, 2) is a number that has 2 digits after

4
CM/IT-306 Relational Data Base Management Systems UNIT II

decimal and total of 7 digits.


Long Up to 2GB Character data of variable length
A date between jan-1-4712
Date e.g. ’18-jul-2012’
BC to dec-31-4712 AD
Raw binary data of maximum size 255 bytes is
Raw(size) Maximum size is 255 bytes
accepted
Long Raw Up to 2GB Raw binary data of variable length up to 2GB
Hexadecimal string representing the unique
address of a row in its table. This data type is
ROWID
primarily for values returned by the ROWID
pseudo column.
Integer represents a signed integer, decimal or
Integer
binary
Represents float point number p represents
Float(p)
number of precision for decimal point
The difference between char and varchar2 is
• Character specifies fixed length character string
• Varchar2 specifies variable length character string
• In char (n): if we give character string <n then blank spaced will be added.
• In Varchar2 (n) no blanks are added if the length is shorter than maximum length n.

Understand pseudo – columns


Nulls : Null is the absence of data, It is neither character nor numeric. Both character and numeric
elements set to null, which indicates that the element contains no value.
Null is not same as zero. In fact, any arithmetic operation involving a data element containing
NULL will evaluate to NULL. For example, if the current value of a is NULL, then the following
expression will evaluate to NULL: (a+10)*10
We can test the presence or absence of NULL in a data element. The condition IS NULL evaluates
to True if the expression evaluates to NULL and to FALSE if it does not.
Pseudo column : A pseudo column is a item of data which does not belong in any particular table
but which can be treated as if it did. Any SELECT list of columns can include these pseudo columns.
SYSDATE : Current date and time
ROWNUM : Sequence number assigned to retrieved rows
ROWID : Unique identifier for a row
UID : Number associated with a user
USER : User_id of current user
Queries based on pseudo columns:
1. select sysdate from dual; 4. select uid from dual;
2. select rownum from dual; 5. select user from dual;
3. select rowid from dual;

Understand comments within SQL statement


We can create comments with in SQL statements and for schema objects.
Comments with in SQL statements: Comments within SQL statements do not affect the
statement execution, but they may make your application easier for us to read and maintain. A
comment can appear between any keywords, parameters and punctuation marks in a statement. We
can include a comment into a SQL statement using either of these methods.
1. Begin the comment with / * proceed with the text of the comment .This text can span
multiple lines. End the comment with */.

5
CM/IT-306 Relational Data Base Management Systems UNIT II

2. Begin the comment with - - (two hyphens): Proceed with the text of the comment. This
text cannot extend to a new line. End the comment with a line break.
The following example shows how to include simple comments in a statement
CREATE TABLE STUDENT - - table name
(SNO NUMBER,SNAME VARCHAR2(30),MARKS NUMBER); - - number and name and marks
The following example shows how to include bracketed comments in a statement
CREATE TABLE STUDENT /*table name*/
(SNO NUMBER,SNAME VARCHAR2(30),MARKS NUMBER); /*number and name and marks*/
Comments on schema objects: We can also add comments to a table or columns using the
‘comment’ command. This is useful especially for large database where you want others to some
specific information about a table such as type of information stored in the table.
Ex: SQL> comment on table emp is
2 ‘this is a table containing employee details’;
The following example creates comments on table column on table column
SQL> comment on column emp. empno is
2 ‘Identifier for employee’ ;

List and explain the functions like single row, character, conversion and group functions Functions:
A function is a special type of predefined command set that performs some
operations. Functions serve the purpose of manipulating data items and returning results.
SQL supports many functions. All these functions can be generally categorized into the following
two Types:
1. Single row(scalar) functions
2. Multiple row(group or aggregate) functions
(1) Group Functions (Aggregate Functions) Functions that act on a set of values are called Group
functions. A group function returns a single result row for a group of queried rows.
(2) Scalar Functions (Single Row Functions) Functions that act on only one value at a time are
called scalar functions. A single row function returns one result for every row of the queried table.
Single row functions can be further classified as
i. String Functions : Work for string Data type.
ii. Numeric Functions : Work for Number Data type.
iii. Conversion Functions : Work for Conversion of one data type to another.
iv. Date Functions : Work for Date Data type.
v. Miscellaneous functions
NOTE: In the following query statements we used a dummy table DUAL. It contains one row and one
column of data. We can use dual in arithmetic expressions.
Aggregate or group Functions:
(a) AVG: It gives the average of the values in a field or column.
Syntax: AVG( field name)
Example: SELECT AVG(SAL) FROM EMP;
(b) MIN: This function used to find minimum value among the given values (i.e. field).
Syntax: MIN(field name)
Example: SELECT MIN(SAL) FROM EMP;
(c)COUNT(<column name>): It gives no. of non-NULL values in that column.
Syntax: COUNT(field name)
Example: SELECT COUNT(COMM) FROM EMP;
(d)COUNT(*): It gives the no. of columns in a table
Syntax: COUNT(*)
Example: SELECT COUNT(*) FROM EMP;

6
CM/IT-306 Relational Data Base Management Systems UNIT II

(e)MAX: This function used to find maximum value among the given values (i.e. field).
Syntax: MAX(field name)
Example: SELECT MAX(SAL) FROM EMP;
(f)SUM: it is used to sum the values in a column or field.
Syntax: SUM(field name)
Example: SELECT SUM(SAL) FROM EMP;
Numeric/Number/Arithmetic Functions:
(a) ABS: Returns the absolute value of a given number.
Syntax: ABS(number)
Example: SELECT ABS(-33) FROM DUAL;
(b) POWER: It returns value m raised n. N must be an integer, else an error is returned.
Syntax: POWER(m,n)
Example: SELECT POWER(9,2) FROM DUAL;
(c) CEIL: It returns the smallest integer greater than the given number.
Syntax: CEIL(number)
Example: SELECT CEIL(123.12) FROM DUAL;
(d) FLOOR: It returns the largest integer smaller than the given value.
Syntax: FLOOR(number)
Example: SELECT FLOOR(123.12) FROM DUAL;
(e) MOD: It returns remainder of “m” divided by “n”.
Syntax: MOD(m,n)
Example: SELECT MOD(5,2) FROM DUAL;
(f) SQRT: It returns the Square root value of the number.
Syntax: SQRT(number)
Example: SELECT SQRT(25) FROM DUAL;
(g) ROUND: It returns the given float number “m” to the “n” places after the decimal.
Syntax: ROUND(m,n)
Example: SELECT ROUND(2.34449,3) FROM DUAL;
(h) TRUNC: It truncates given float number “m” to “n” places after the decimal.
Syntax: TRUNC(m,n)
Example: SELECT TRUNC(2.34499,3) FROM DUAL;
(i) LN: It returns natural logarithm value of a given number.
Syntax: LN(number)
Example: SELECT LN(10) FROM DUAL;
(j) LOG: It returns logarithm of n with base m.
Syntax: LOG(m,n)
Example: SELECT LOG(10,100) FROM DUAL;
(k) SIGN: It returns the given number.
Syntax: SIGN(number)
Example: SELECT SIGN(10) FROM DUAL;
(l) EXP: It returns the exponential value to the power raised by m.
Syntax: EXP(number)
Example: SELECT EXP(10) FROM DUAL;
Character Functions (or) String Functions: The string functions accept character input and returns
either character or number values.
(a) LOWER: It converts all letters in the given string ‘‘str” into lower case.
Syntax: LOWER(STR)
Example: SELECT LOWER(ENAME) FROM EMP;
(b) UPPER: It converts all letters in the given string “str” into upper case.

7
CM/IT-306 Relational Data Base Management Systems UNIT II

Syntax: UPPER(STR)
Example: SELECT UPPER(JOB) FROM EMP;
(c) INITCAP: Returns a string with the first letter of each word in upper case.
Syntax: INIITCAP(STR)
Example: SELECT INITCAP(ENAME) FROM EMP;
(d) LENGTH: Returns the length of the word.
Syntax: LENGTH(STR)
Example: SELECT ENAME,LENGTH(ENAME) FROM EMP;
(e) INSTR: It displays the location of “str” in the given string “string”.
Syntax: INSTR(STRING,STR)
Example: SELECT INSTR('RELATIONAL DATABASE MANAGEMENT SYSTEMS','NAL')
FROM DUAL;
(f) INSTR: It displays “nth” occurrence of “str” in the string “string” starting from “m”.
Syntax: INSTR(STRING,STR,M,N)
Example: SELECT INSTR('TRY TO KEEP THINGS AS SIMPLE AS POSSIBLE','AS',1,2) FROM
DUAL;
(g) SUBSTR: It will returns extract “n” characters from the given string starting from “mth”
position.
Syntax: SUBSTR(STRING,M,N)
Example: SELECT SUBSTR('TRY TO KEEP THINGS AS SIMPLE AS POSSIBLE',4,2) FROM
DUAL;
(h) LTRIM: it removes characters from the left of char with initial characters removed up to the
first character not in set.
Syntax: LTRIM(char[,set])
Example: SELECT LTRIM('COMPUETRS','COM') FROM DUAL;
(i) RTRIM: It returns char, with final characters removed after the last character not in the set.
‘set’ is optional , it defaults to space.
Syntax: RTRIM(char[,set])
Example: SELECT RTRIM('COMPUETRS','RS') FROM DUAL
Date Functions:
(a) ADD_MONTHS: Returns date after adding the number of months specified in the function.
Syntax: ADD_MONTHS(date,n)
Example: SELECT ADD_MONTHS(SYSDATE,4) FROM DUAL;
(b) LAST_DAY: Returns the last date of the month specified with the function.
Syntax: LAST_DAY(date)
Example: SELECT LAST_DAY(SYSDATE) FROM DUAL;
(c) MONTHS_BETWEEN: Returns the number of months between date1 and date2.
Syntax: MONTHS_BETWEEN(date1,date2)
Example: SELECT MONTHS_BETWEEN('20-JUL-2012','20-JAN-2012') FROM DUAL;
(d) NEXT_DAY: Returns the date of the next occurrence of the specified day after the given
date.
Syntax: NEXT_DAY(date,day)
Example: SELECT NEXT_DAY(SYSDATE,'FRIDAY') FROM DUAL;
Conversion Functions:
(a) TO_NUMBER: Converts char, a CHARACTER value expressing a number, to a number data
type.
Syntax: TO_NUMBER(char)
Example: SELECT SAL,SAL+TO_NUMBER(SUBSTR('$100',2,3)) "NEW_SAL" FROM EMP;

8
CM/IT-306 Relational Data Base Management Systems UNIT II

(b) TO_CHAR(number conversion / date conversion): This function is used to convert a date or
number to character string.
Syntax: TO_CHAR( n [ , format ] )
Example: SELECT TO_CHAR(sysdate,’day DD month YYYY') FROM dual;
(c) TO_DATE: This function converts a string into an Oracle date.
Syntax: TO_DATE(STRING)
Example: SELECT TO_DATE('15 AUGUST 2012','DD MONTH YYYY') FROM DUAL;
Example: SELECT TO_DATE('AUG 12 15','MON YY DD') FROM DUAL;
Miscellaneous Functions:
a) NVL () function: This function is used to substitute any NULL value with a user defined value.
Ex: consider the following student table with 3 rows
SQL> select * from student;
SNO SNAME SMARKS GRADE
----- ---------- ------------ ----------
1 RAMESH 80 A
2 KAMAL 90 B
3 SURESH 95 A+
SQL> select sno,sname,marks,nvl(grade,’A+’) from student;
SNO SNAME SMARKS NVL(GRADE,’A+’)
----- ---------- ------------ -----------------------
1 RAMESH 80 A
2 KAMAL 90 B
3 SURESH 95 A+
b) Decode Function: used for substituting values in the query result
Ex: select empno,decode(deptno,10,’computer’,20,’ece’,30,’mech’,’none’) from emp;
If deptno has value 10 deptname is selected as computer
If deptno has value 20 deptname is selected as ece
If deptno has value 30 deptname is selected as mech and
If deptno has value 10 deptname is selected as none
c) Vsize: displays the oracle storage size in bytes
d) Dump: displays areas of oracle’s internal storage
e) Greatest: displays the highest of a list of expressions
f) Least: displays the lowest of a list of expressions

Give and explain the various date and number format models
VARIOUS DATE AND NUMBER FORMAT MODELS:
Format data are used to control the appearance of the displayed data. Oracle provides several
commands for displaying data in a variety of display formats, or format models.
The Various format models are
• Character format
• Numeric format
• Date format
Character Format: A character format consists of letter A followed by the width of the Columns.
Syntax: COLUMN COLUMN NAME FORMAT AWIDTH;
Example: COLUMN ENAME FORMAT A20;
If the above command is executed and query is written which will display the data of column ENAME
in width 20.

9
CM/IT-306 Relational Data Base Management Systems UNIT II

Numeric Format: A numeric format model decides how the numeric data will be printed in output.
You can globally change the way the SELECT command displays values with the SET NUMFORMAT
command.
Syntax: SET NUMFORMAT FORMATMODEL;
Example: SET NUMFORMAT 9999.99;
The above command affects all number columns selected, not just one. To affect just one column,
you have to use the COLUMN command with the following syntax:
Syntax: COLUMN <column_name> FORMAT <format_model>
Example Numeric Formats:
FORMAT INPUT DISPLAY DESCRIPTION
99999 12345 12345 Width set my number of nines.
09999 12 00012 Zero filled
$9999 123 $123 Prefix value with a Dollar sign
9,999 1234 1,234 Comma delimiter where indicated
9.99EEEE 123 1.23+3 Scientific notation, four E’s needed

Date format: The date format decides how the dates are printed on output. The date formats are
used in TO_CHAR and TO_DATE functions only.
FORMAT DESCRIPTION
MON The Current month Abbreviated.
DAY The current day of the week.
MM The number of the current month.
YY The last two numbers of the current year.
DD The current day of the month.
YYYY The current Year.
DDD The current day of the year since January 1
HH The current hour of the day
MI The current minute of the day
SS The current seconds of the minute
A.M. Displays a.m or p.m
Example: SELECT TO_DATE('FRIDAY 15 AUG 2008','DAY DD MON YYYY') FROM DUAL;
Example: SELECT TO_CHAR(SYSDATE,'DAY DD MON YYYY') FROM DUAL;
List and explain the various commands of SQL like data definition language commands, data
manipulation language commands, transaction control commands
VARIOUS COMMANDS OF SQL:
SQL commands can be grouped into the following types based on their purpose:
- Data Definition Language (DDL) commands
- Data Manipulation Language (DML) commands.
- Data Control Language (DCL) commands.
- Transaction Control Language (TCL) commands.
- System control commands
Data Definition Language (DDL): as the name DDL suggests, these commands allow you to perform
task related to data definition.
The DDL commands are CREATE, ALTER, DROP, TRUNCATE e.t.c.
COMMAND DESCRIPTION
CREATE Create schema objects like tables, views e.t.c
ALTER Alter or Change or modify the structure of existing schema

10
CM/IT-306 Relational Data Base Management Systems UNIT II

objects
DROP Completely Drop or remove objects from the system
Data Manipulation Language (DML): Once the database is established, DML statements are the most
frequently used SQL statements. SELECT statement is used to query the database. The UPDATE,
INSERT, and DELETE statements alter existing database rows, place new records, or remove one or
more records from the database.
COMMAND DESCRIPTION
DELETE Deletes one or more rows from a table or view
INSERT Adds a new row to a table or view
Performs query and selects rows and columns from one or
SELECT
more tables (or) views
UPDATE Changes the value of fields in a table or view.
DML Statements (Query Statements):
DML can be classified into two categories
1) Procedural DML
2) Non Procedural DML
1) Procedural DML: The procedural DML statements can be embedded into any programming
language like C, C++,Java e.t.c.
Ex: EXEC SQL
Declare emp_cur cursor for
Select ename,empno from emp;
END EXEC
We can run DML statements in programming languages with the help of cursors
The open statement usage in embedded SQL:
EXEC SQl
Open emp_cur
END EXEC
The fetch statement usage in embedded SQL:
EXEC SQl
fetch emp_cur into host language variables
END EXEC
The close statement usage in embedded SQL:
EXEC SQl
close emp_cur
END EXEC
2) Non Procedural DML: Non procedural DML specifies the DML queries select, insert, update, delete.
SELECT: The select statement is used to select data from a table.
Syntax: SELECT[ALL/DISTINCT]
Column name(s)
FROM table(s)
[WHERE conditional expression]
[GROUP BY column(s)]
[HAVING conditional expression]
[ORDER BY column(s)];
In the above table where, group by, having, order by are optional.
Example:
1. select * from emp; /* total rows retrieved from emp table*/
2. select ename,sal from emp; /*selected row values of columns data retrieved from emp table*/

11
CM/IT-306 Relational Data Base Management Systems UNIT II

3. select * from emp where ename like ‘K%’; /* retrieving rows from emp table where ename start
with K */
4. select ename,sal,sal*1.5 as newsal from emp; /* retrieve ename,sal,newsal(creating for sal
using sal*1.5) from emp table*/
Distinct: The distinct key word is used to return only distinct (different values).
Syntax: select distinct column name(s) from tablename;
Example: select distinct sal from emp;
WHERE: It is used to specify a selection criterion to conditionally select data from a table a where
clause can be added to the select statement.
Syntax: select column name fron table name where column name operator value
Example: select * from emp where sal=20000;
ORDER BY: order by clause displays the table data in proper order (i.e. Ascending or descending)
a. select * from emp order by sal;
b. select * from emp order by sal desc;
GROUP BY: The GROUP BY clause is used in a SELECT statement to collect data across multiple
records and group the results by one or more columns. Related rows can be grouped together by the
GROUP BY clause by specifying a column as a grouping column.
Example:
a. SELECT DEPTNO,SUM(SAL) FROM EMP GROUP BY DEPTNO;
b. SELECT JOB,COUNT(*) FROM EMP GROUP BY JOB;
HAVING: The HAVING is used along with the GROUP BY clause. HAVING imposes a condition on the
GROUP BY clause, which further filters the groups created by the GROUP BY clause.
Example:
a. SELECT JOB,COUNT(*) FROM EMP GROUP BY JOB HAVING COUNT(JOB)>2;
b. SELECT DEPTNO,COUNT(EMPNO) COUNT,SUM(SAL) SAL FROM EMP GROUP BY DEPTNO
HAVING COUNT(EMPNO)>4;
INSERT: The Insert statement is used to insert new rows into a table.
Insert a new row:
Syntax: insert into table name values(value1,value2. ... );
Example: insert into student values(1,’aaa’,90,’tvr’);
Insert values into specified columns:
Syntax: insert into table name(column1,column2….) values(literal,literal….);
Example: insert into student(sno,sname,marks,addess)values(2,’bbb’,95,’nzd’);
UPDATE: The update statement is used to modify the data in a table
Update one column in a row:
Syntax: Update table name set column name=new value where column name=some value;
Example: update student set marks=100 where sname=’aaa’;
Update several columns in a row:
Syntax: Update table name set column name1=new value, column name2=new value where
column name=some value;
Example: update student set marks=100,address=’mtm’ where sname=’aaa’;
Update all row values of one column in a table:
Syntax: Update table name set column name=new value;
Example: update student set marks=100;
DELETE: Delete statement deletes the rows in a table.
Delete selected rows from a table:
Syntax: delete from table name where conditional expression;
Example: delete from student where sname=’aaa’;
Delete all rows from a table:
Syntax: delete from tablename;

12
CM/IT-306 Relational Data Base Management Systems UNIT II

Example: delete from student;


Data Control Language (DCL): DCL commands are used to grant or revoke permissions to work upon
objects. Examples of DCL commands are GRANT and REVOKE.
COMMAND DESCRIPTION
GRANT Grants access on objects stored in database
Revokes database privileges or table access privileges from
REVOKE
user.
Ex: SQL> grant select on student to scott;
Grant succeseded
Grant student table display rights to username scott
Ex: SQL> revoke select on student from scott;
Revoke succeseded
revoke student table display rights from username scott
Transaction Control Language (TCL): A transaction is one complete unit of work. To manage and
control the transactions TCL commands are used. Some examples of TCL commands are COMMIT,
ROLLBACK and SAVEPOINT.
COMMAND DESCRIPTION
COMMIT Makes database transactions irreversible
ROLLBACK Cancels database transactions
SAVEPOINT Saves the current point in the processing of a transaction.
Ex: SQL>commit; -- save into database
Commit complete
Ex: SQL>rollback; -- cancel the transactions
rollback complete
Ex: SQL>savepoint spi -- savepoint which is like a check point
Savepoint created
Ex: SQL>rollback to spi -- rollback to the created save point
Rollback complete
Ones rollback to savepoint is completed the savepoint is destroyed.
System Control commands: These commands are used to analyze information on a table, index or
cluster to establish auditing options and to add comments to the data dictionary. Commands are
ANALYZE, AUDIT, NOAUDIT, COMMENT ETC.
Explain sub queries
Sub query: It is a form of SQL statement that appears inside another SQL statement. It is also
called as nested query. The SQL statement containing the sub query is called as parent statement.
The statement of parent uses the rows returned by the sub query.
Sub queries can be used to answer queries such as "who has a salary more than Tom's". The
first query finds Tom's salary and the second finds those whose salary is greater than Tom's.
Oracle executes the subquery first, making the result of the sub query available to the main
query and then executing the main query.
The syntax of sub query is
Syntax: SELECT <column, ...> FROM <table> WHERE expression operator( SELECT <column, ...>
FROM <table> WHERE <condition>)
Example: SELECT * FROM emp WHERE sal > (SELECT sal FROM emp WHERE name='TOM');
Rules followed by while writing sub query:
• A subquery must be enclosed in the parenthesis.
• A subquery must be put in the right hand of the comparison operator
• It cannot contain a ORDER-BY clause.

13
CM/IT-306 Relational Data Base Management Systems UNIT II

• A query contains more than one sub-queries.


Sub query can be used by the following commands:
1. To insert records in a target table
2. To create tables and insert records in the table created
3. To update records in a target table
4. To create views
In general, there are three types subqueries:
• single-row subquery, where the subquery returns only one row.
• multiple-row subquery, where the subquery returns multiple rows,.and
• multiple column subquery, where the subquery returns multiple columns.
Single-Row Subquery:
• The operators that can be used with single-row subqueires are =, >, >=, <, <=, and <>.
• Group functions can be used in the subquery. For example, the following statement retrieves
the details of the employee holding the highest salary.
SQL> SELECT * FROM emp WHERE sal = (SELECT MIN(sal) FROM emp);
• Having-clause can also be used with the single-row subquery. For example, the following
statement returns all departments in where the minimum salary is more than the minimum
salary in the department 5.
SQL> SELECT deptno,MIN(sal) FROM emp GROUP BY deptno HAVING MIN(sal) > ( SELECT
MIN(sal) FROM emp WHERE deptno=5);
Multiple-Row Subquery:
• Note the following statement is illegal, because the operator = cannot be used with subquery
returns multiple rows.
• SQL> SELECT name, sal FROM emp WHERE sal > (SELECT MIN(sal) FROM emp GROUP BY
deptno);
Some operators that can be used with multipe-row subqueries are:
1. IN, equal to any member in the list,
2. ANY, compare values to each value returned by the subquery.
• For example, the following statement finds the employees whose salary is the same as the
minimum salary of the employees in some department.
SQL> SELECT name, sal FROM emp WHERE sal IN (SELECT MIN(sal) FROM emp GROUP BY
deptno);
• For example, the following statement find the employees whose salary is more than the
minimum salary of the employees in any department.
SQL> SELECT name, sal FROM emp WHERE sal > ANY (SELECT MIN(sal) FROM emp GROUP BY
deptno);
Multiple-Column Subquery:
• In multiple-column subqueries, rows in the subquery results are evaluated in the main query
in pair-wise comparison. That is, column-to-column comparison and row-to-row comparison.
• For example, the following statement lists all items whose quantity and product id match to
an item of order id 200.
SQL> SELECT orderid,productid,quantity FROM item WHERE (productid,quantity) IN (SELECT
productid,quantity FROM item WHERE orderid = 200) AND orderid = 200;

Explain Joins – Types of Joins


Several different types of joins are supported by DB2 UDB for iSeries: inner join, left outer join,
right outer join, left exception join, right exception join, and cross join.

14
CM/IT-306 Relational Data Base Management Systems UNIT II

• An Inner Join returns only the rows from each table that have matching values in the join
columns. Any rows that do not have a match between the tables will not appear in the result
table.
• A Left Outer Join returns values for all of the rows from the first table (the table on the left)
and the values from the second table for the rows that match. Any rows that do not have a
match in the second table will return the null value for all columns from the second table.
• A Right Outer Join return values for all of the rows from the second table (the table on the
right) and the values from the first table for the rows that match. Any rows that do not have a
match in the first table will return the null value for all columns from the first table.
• A Cross Join returns a row in the result table for each combination of rows from the tables
being joined (a Cartesian Product).

SQL JOIN
The JOIN keyword is used in an SQL statement to query data from two or more tables, based
on a relationship between certain columns in these tables.
Tables in a database are often related to each other with keys.
A primary key is a column (or a combination of columns) with a unique value for each row.
Each primary key value must be unique within the table. The purpose is to bind data together, across
tables, without repeating all of the data in every table.

Look at the "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Note that the "P_Id" column is the primary key in the "Persons" table. This means that no two rows
can have the same P_Id. The P_Id distinguishes two persons even if they have the same name.

Next, we have the "Orders" table:

O_Id OrderNo P_Id


1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15

Note that the "O_Id" column is the primary key in the "Orders" table and that the "P_Id" column
refers to the persons in the "Persons" table without using their names.

Notice that the relationship between the two tables above is the "P_Id" column.

15
CM/IT-306 Relational Data Base Management Systems UNIT II

Different SQL JOINs


Before we continue with examples, we will list the types of JOIN you can use, and the
differences between them.

• JOIN: Return rows when there is at least one match in both tables
• LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
• RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
• FULL JOIN: Return rows when there is a match in one of the tables

SQL INNER JOIN Keyword


The INNER JOIN keyword return rows when there is at least one match in both tables.
SQL INNER JOIN Syntax
SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name

PS: INNER JOIN is the same as JOIN.

SQL INNER JOIN Example

The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

The "Orders" table:

O_Id OrderNo P_Id


1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
Now we want to list all the persons with any orders.
We use the following SELECT statement:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName

16
CM/IT-306 Relational Data Base Management Systems UNIT II

The result-set will look like this:

LastName FirstName OrderNo


Hansen Ola 22456
Hansen Ola 24562
Pettersen Kari 77895
Pettersen Kari 44678

The INNER JOIN keyword return rows when there is at least one match in both tables. If there are
rows in "Persons" that do not have matches in "Orders", those rows will NOT be listed.

SQL LEFT JOIN Keyword


The LEFT JOIN keyword returns all rows from the left table (table_name1), even if there are no
matches in the right table (table_name2).

SQL LEFT JOIN Syntax


SELECT column_name(s) FROM table_name1 LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name

PS: In some databases LEFT JOIN is called LEFT OUTER JOIN.\

SQL LEFT JOIN Example

The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

The "Orders" table:

O_Id OrderNo P_Id


1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15

Now we want to list all the persons and their orders - if any, from the tables above.

We use the following SELECT statement:

17
CM/IT-306 Relational Data Base Management Systems UNIT II

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons LEFT JOIN Orders


ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName

The result-set will look like this:

LastName FirstName OrderNo


Hansen Ola 22456
Hansen Ola 24562
Pettersen Kari 77895
Pettersen Kari 44678
Svendson Tove

The LEFT JOIN keyword returns all the rows from the left table (Persons), even if there are no
matches in the right table (Orders).

SQL RIGHT JOIN Keyword


The RIGHT JOIN keyword Return all rows from the right table (table_name2), even if there are
no matches in the left table (table_name1).

SQL RIGHT JOIN Syntax


SELECT column_name(s) FROM table_name1 RIGHT JOIN table_name2
ON table_name1.column_name=table_name2.column_name

PS: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

SQL RIGHT JOIN Example

The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

The "Orders" table:

O_Id OrderNo P_Id


1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15

18
CM/IT-306 Relational Data Base Management Systems UNIT II

Now we want to list all the orders with containing persons - if any, from the tables above.

We use the following SELECT statement:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons RIGHT JOIN Orders


ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName

The result-set will look like this:

LastName FirstName OrderNo


Hansen Ola 22456
Hansen Ola 24562
Pettersen Kari 77895
Pettersen Kari 44678
34764

The RIGHT JOIN keyword returns all the rows from the right table (Orders), even if there are no
matches in the left table (Persons).

SQL FULL JOIN Keyword


The FULL JOIN keyword return rows when there is a match in one of the tables.
SQL FULL JOIN Syntax
SELECT column_name(s) FROM table_name1 FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name

SQL FULL JOIN Example

The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

The "Orders" table:

O_Id OrderNo P_Id


1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15

19
CM/IT-306 Relational Data Base Management Systems UNIT II

Now we want to list all the persons and their orders, and all the orders with their persons.

We use the following SELECT statement:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons FULL JOIN Orders


ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName

The result-set will look like this:

LastName FirstName OrderNo


Hansen Ola 22456
Hansen Ola 24562
Pettersen Kari 77895
Pettersen Kari 44678
Svendson Tove
34764
The FULL JOIN keyword returns all the rows from the left table (Persons), and all the rows
from the right table (Orders). If there are rows in "Persons" that do not have matches in "Orders", or
if there are rows in "Orders" that do not have matches in "Persons", those rows will be listed as well.
SQL Equi Join
An equi-join is a specific type of comparator-based join, that uses only equality comparisons
in the join-predicate. Using other comparison operators (such as < ) disqualifies a join as an equi-
join. The query shown above has already provided an example of an equi-join:
Syntax
SELECT * FROM table_name1, table_name2 WHERE table_name1.column_name1 =
table_name2.column_name1;
Consider the Following Tables
Employee Table
LastName DepartmentID
Rafferty 31
Jones 33
Hesinberry 33
Robinson 34
Smith 34
Jhon NULL
Department table
DepartmentID DepartmentName
31 Sales
33 Engineering
34 Clerical
35 Marketing

20
CM/IT-306 Relational Data Base Management Systems UNIT II

Example
SELECT * FROM employee, department WHERE employee.DepartmentID =
department.DepartmentID;
Output:
Employee.LastNa Employee.Department Department.DepartmentNa Department.Department
me ID me ID
Robinson 34 Clerical 34
Jones 33 Engineering 33
Smith 34 Clerical 34
Heisenberg 33 Engineering 33
Rafferty 31 Sales 31

SQL Self Join


A self join is a join in which a table is joined with itself (which is also called Unary
relationships), specially when the table has a FOREIGN KEY which references its own PRIMARY KEY. To
join a table itself means that each row of the table is combined with itself and with every other row of
the table.
Consider the following Table
How the employees are related to themselves :
• An employee may report to another employee (supervisor).
• An employee may supervise himself (i.e. zero) to many employee (subordinates).
We have the following data into the table EMPLOYEE.

Example
SELECT a.emp_id AS "Emp_ID",a.emp_name AS "Employee Name",
b.emp_id AS "Supervisor ID",b.emp_name AS "Supervisor Name" FROM employee a, employee b
WHERE a.emp_supv = b.emp_id;

The Result is as shown Below

21
CM/IT-306 Relational Data Base Management Systems UNIT II

SQL Cross Join


The SQL CROSS JOIN produces a result set which is the number of rows in the first table
multiplied by the number of rows in the second table, if no WHERE clause is used along with CROSS
JOIN. This kind of result is called as Cartesian Product.
Syntax
SELECT * FROM table1 CROSS JOIN table2;
Pictorial Representation of the Cross Join Syntax

Consider the following tables

Example:
SELECT foods.item_name,foods.item_unit,
company.company_name,company.company_city FROM foods CROSS JOIN company;

22
CM/IT-306 Relational Data Base Management Systems UNIT II

OR
SELECT foods.item_name,foods.item_unit,company.company_name,company.company_city F
ROM foods,company;
The output is as shown below:

Pictorial Presentation of Output

SQL Semi Join


A semi-join returns rows from one table that would join with another table without
performing a complete join. An anti-semi-join returns rows from one table that would not join with
another table; these are the rows that would be NULL extended if we performed an outer join.

23
CM/IT-306 Relational Data Base Management Systems UNIT II

Customer Table
Cust_ID Cust_Name
1 Craig
2 John Doe
3 Jane Doe
Sales table
Cust_ID Item
2 Camera
3 Computer
3 Monitor
4 Printer

Unlike the other join operators, there is no explicit syntax to write “semi-join,” but SQL Server uses
semi-joins in a variety of circumstances. For example, we may use a semi-join to evaluate an EXISTS
sub-query:
select * from Customers C where exists ( select * from Sales S where S.Cust_Id = C.Cust_Id)

Cust_Id Cust_Name

2 John Doe
3 Jane Doe

We might similarly use an “anti-semi-join” to evaluate a NOT EXISTS sub-query.

2.14 Various operators in SQL


Operators in SQL can be classified into:
1. Arithmetic Operators or Mathematical Operators
2. Logical Operators
3. Comparison Operators
4. Set Operations
Arithmetic Operators: Oracle allows arithmetic operators to be used while viewing records from a
table (SELECT) or while performing Data Manipulation operations such as INSERT, UPDATE and
DELETE. These are

Operator Meaning Example


+ Addition SELECT SAL+COMM GROSS_SALARY FROM EMP WHERE
JOB='SALESMAN';
- Subtraction INSERT INTO EMPLOYEE SELECT EMPNO,ENAME,SAL-COMM FROM
EMP WHERE JOB='SALESMAN';
* Multiplication SELECT SAL,COMM,(SAL+COMM)*.20 "DA",(SAL+COMM+3) GROSS
FROM EMP WHERE JOB='SALESMAN';
/ Division SELECT SYSDATE,HIREDATE,FLOOR((SYSDATE-HIREDATE)/365) SERVICE
FROM EMP;

Comparison Operators: Oracle provides a variety of comparison operators to compare on expression


with another.

24
CM/IT-306 Relational Data Base Management Systems UNIT II

Operator Meaning Description Example


Tests for equality of two SELECT * FROM EMP WHERE
= Equal to
operands. SAL=5000;
!=, ^=, Tests for inequality of two SELECT * FROM EMP WHERE
Not Equal to
<> operands JOB!=’WORKER’;
Test for operand A is less SELECT ENAME,SAL FROM EMP
< Less than
than operand B WHERE SAL<5000;
Test that operand A is less
Less than or SELECT ENAME,SAL FROM EMP
<=(!>) than or equal to B. This the
equal to WHERE SAL<=5000;
same as !>
Test that operand A is greater SELECT ENAME,SAL FROM EMP
> Greater Than
than operand B WHERE SAL>5000;
Test that operand A is greater
Greater than or SELECT ENAME,SAL FROM EMP
>= (!<) than or equal to operand B.
equal to WHERE SAL>=5000;
This is same as !<
Tests that operand A matches
SELECT * FROM EMP WHERE SAL
IN A IN(b,c,..) at least one element of the
IN(2450,1600,400);
list provided (b,c,..)
Tests that operand A does
SELECT * FROM EMP WHERE SAL
NOT IN A NOT IN(b,c,..) not match any element of the
NOT IN(2450,1600,400);
list provided(b,c,..)
Tests that operand A is
A BETWEEN b greater than or equal to SELECT * FROM EMP WHERE SAL
BETWEEN
AND c operand B and less than or BETWEEN 400 AND 5000;
equal to operand C.
Tests that operand A is less
NOT A NOT BETWEEN SELECT * FROM EMP WHERE SAL
than operand b or greater
BETWEEN b AND c NOT BETWEEN 400 AND 5000;
than operand c.
Tests that operand A matches
pattern operand B. The
pattern may contain _, which SELECT * FROM EMP WHERE
LIKE A LIKE B
matches a single character in EMPNAME LIKE '%M’';
that position, or % which
matches all characters.
Tests that operand A does SELECT * FROM EMP WHERE
NOT LIKE A NOT LIKE B
not match pattern operand B. EMPNAME NOT LIKE 'M%’';
SELECT EMPNO,ENAME,SAL,JOB
IS NULL A IS NULL Tests that operand A is NULL FROM EMP WHERE COMM IS
NULL;
SELECT EMPNO,ENAME,SAL,JOB
IS NOT Tests that operand A is NOT
A IS NOT NULL FROM EMP WHERE COMM IS NOT
NULL NULL
NULL;
SELECT * FROM DEPT WHERE
Tests that query return at EXISTS(SELECT DEPTNO FROM EMP
EXISTS EXISTS (query)
least one row. WHERE
EMP.DEPTNO=DEPT.DEPTNO)

25
CM/IT-306 Relational Data Base Management Systems UNIT II

SELECT EMPNO,ENAME FROM EMP


NOT Tests that the query does not WHERE NOT EXISTS(SELECT ENAME
NOT EXISTS
EXISTS return a row FROM EMPLOYEE WHERE
EMP.ENAME=EMPLOYEE.ENAME)
Tests that the relationship
specified (ex =,<,>,<> etc) is
A=ANY(b,c,…)
true for at least one element
A<ANY(b,c,…) SELECT * FROM EMP WHERE SAL
ANY of the list provided (operand
A>ANY(b,c,…) =ANY(400,1600,2450);
b,c,…). When testing for
etc.,
equality this is equivalent to
IN.
Tests that the relationship
specified (ex =,<,>,<> etc) is
A=SOME(b,c,…)
true for at least one element
A<SOME(b,c,…) SELECT * FROM EMP WHERE SAL
SOME of the list provided (operand
A>SOME(b,c,…) =SOME (400,1600,2450);
b,c,…). When testing for
etc.,
equality this is equivalent to
IN.
Tests that the relational
A=ALL(b,c,..) specified (e.g =, <>, <, > etc) is SELECT * FROM EMP WHERE SAL
ALL
A<ALL(b,c,..) etc., true for every element of the >ALL(2000,2500)
list provided(operand b,c,..).

Logical Operators: A Logical operator is used to produce a single result from combining the two
separate conditions.
Operator Meaning Example
Returns TRUE if all the SELECT EMPNO,ENAME,SAL,HIREDATE FROM EMP
AND
conditions are TRUE WHERE HIREDATE<'1-JAN-1990' AND SAL<2000;
Returns TRUE if either of SELECT EMPNO,ENAME,SAL,JOB FROM EMP WHERE
OR
the condition is TRUE JOB='MANAGER' OR JOB='PRESIDENT';
Returns TRUE if the SELECT EMPNO,ENAME,SAL FROM EMP WHERE NOT
NOT
condition is FALSE SAL>2000;

Set Operators: Set operators combine the result of two separate queries into a single result.
Operator Meaning Example
Combines all rows retrieved by both SELECT DEPTNO FROM EMP UNION
UNION
queries and eliminates duplicate rows SELECT DEPTNO FROM DEPT;
Combines all rows retrieved by both SELECT DEPTNO FROM EMP UNION ALL
UNION ALL
queries and includes duplicate rows SELECT DEPTNO FROM DEPT;
Outputs only rows that are retrieved SELECT DEPTNO FROM EMP INTERSECT
INTERSECT
common to both the queries. SELECT DEPTNO FROM DEPT;
Outputs the rows produced by the first SELECT * FROM EMP MINUS SELECT
MINUS query after filtering the rows retrieved DEPTNO FROM DEPT;
by the second query.

26

You might also like