Dbms 2
Dbms 2
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.
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
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.
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
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
13
CM/IT-306 Relational Data Base Management Systems UNIT II
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.
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.
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
• 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
16
CM/IT-306 Relational Data Base Management Systems UNIT II
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.
Now we want to list all the persons and their orders - if any, from the tables above.
17
CM/IT-306 Relational Data Base Management Systems UNIT II
The LEFT JOIN keyword returns all the rows from the left table (Persons), even if there are no
matches in the right table (Orders).
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.
The RIGHT JOIN keyword returns all the rows from the right table (Orders), even if there are no
matches in the left table (Persons).
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.
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
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;
21
CM/IT-306 Relational Data Base Management Systems UNIT II
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:
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
24
CM/IT-306 Relational Data Base Management Systems UNIT II
25
CM/IT-306 Relational Data Base Management Systems UNIT II
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