0% found this document useful (0 votes)
2 views

DBMS 7

SQL (Structured Query Language) is a standardized programming language used for managing and manipulating relational databases. It includes various commands categorized into Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), and Transaction Control Language (TCL), allowing users to create, modify, and query data. SQL also supports aggregate functions and subqueries for advanced data retrieval and manipulation.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

DBMS 7

SQL (Structured Query Language) is a standardized programming language used for managing and manipulating relational databases. It includes various commands categorized into Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), and Transaction Control Language (TCL), allowing users to create, modify, and query data. SQL also supports aggregate functions and subqueries for advanced data retrieval and manipulation.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Q: Write a short note on SQL (Structured Query Language).

Ans: SQL stands for Structured Query Language. SQL is a database computer language designed for
managing data in relational database management systems (RDBMS), and originally based upon Relational Algebra.
SQL was one of the first languages for Edgar F. Codd's relational model in his influential 1970 paper, "A Relational
Model of Data for Large Shared Data Banks" and became the most widely used language for relational databases.
 IBM developed SQL in mid of 1970’s.
 Oracle incorporated in the year 1979.
 SQL used by IBM/DB2 and DS Database Systems.
 SQL adopted as standard language for RDBS by ASNI (American National Standards Institute) in 1989.
Q) WRITE SQL HISTORY
SQL BACKGROUND: SQL language is a “query language. It can define the structure of the data, modify data in the
database, and specify security constraints.IBM developed the original version of SQL at its San Jose Research
Laboratory. IBM implemented the language, originally called Sequel, in the early 1970s.
The SQL language has several parts:
• Data-definition language (DDL). The SQL DDL provides commands for defining relation schemas, deleting
relations, and modifying relation schemas.
• Data-manipulation language (DML). It includes commands to insert tuples into, delete tuples from, and modify
tuples in the database.
• View definition. The SQL DDL includes commands for defining views.
• Transaction control. SQL includes commands for specifying the beginning and ending of transactions.
• Embedded SQL and dynamic SQL. Embedded and dynamic SQL define how SQL statements can be embedded
within general-purpose programming languages, such as C, C++, Java, PL/I, Cobol, Pascal, and Fortran.
• Integrity. The SQL DDL includes commands for specifying integrity constraints that the data stored in the database
must satisfy.
• Authorization. The SQL DDL includes commands for specifying access rights to relations and views.

Q) EXPLAIN THE BASIC STRUCTURE OF SQL


The basic structure of an SQL expression consists of three clauses: select, from, and where.
• The select clause corresponds to the projection operation of the relational algebra. It is used to list the attributes
desired in the result of a query.
• The from clause corresponds to the Cartesian-product operation of the relational algebra. It lists the relations to be
scanned in the evaluation of the expression.
• The where clause corresponds to the selection predicate of the relational algebra. It consists of a predicate involving
attributes of the relations that appear in the from clause.
A typical SQL query has the form
select A1,A2,. . o Ai represents an attribute
.,Ai o rj represents a relation
from r1,r2. . . o P is a predicate
,rj
where P Select Clause examples:
1. Find the name of all students.
SQL>select SName from STUDENTS.
2. An asterisk * in the select clause denotes “all attributes”.
SQL>select * from STUDENTS;
3. Duplicates can be removed from query result using keyword distinct
SQL>select distinct SName from STUDENTS;
4. select clause can contain arithmetic expressions as well as functions on attributes including attributes and
constants.
SQL>select substr(SName,1,10) [as] "Name", m1+ 10 from orders;
5. The where clause consists of a predicate involving attributes of the relations that appear in the from clause.
List the first and last name of STUDENTS having a marks<35.
SQL>select FName, LName from STUDENTS where marks<35;
Where Clause
1. where clause uses logical connectives AND, OR, and NOT
2. operands of the logical connectives can be expressions involving the comparison operators <,
<=, >, >=, =, and < >.
1
3. BETWEEN can be used to simplify the comparisons
SQL> select loan-number from Loan where amount between 90000 and 100000

From Clause
1. The from clause by itself defines a Cartesian product of the relations in the clause.
2. When an attribute is present in more than one relation they can be referred as relation-
name.attribute-name to avoid the ambiguity.
3. For all customers who have loan from the bank, find their names and loan numbers
SQL> select distinct customer-name, Borrower.loan-number from Borrower, Loan where Borrower.loan-number
= Loan.loan-number

Q) Describe briefly about SQL Commands (OR) Explain the components of SQL.
ANS: SQL commands are instructions used to communicate with the database to perform specific task that work with
data. SQL commands are grouped into four major categories depending on their functionality:
 Data Definition Language (DDL) - These SQL commands are used for creating, modifying, and dropping
the structure of database objects. The commands are CREATE, ALTER, DROP, RENAME, and TRUNCATE.
 Data Manipulation Language (DML) - These SQL commands are used for storing, retrieving, modifying,
and deleting data. These commands are SELECT, INSERT, UPDATE, and DELETE.
 Transaction Control Language (TCL) - These SQL commands are used for managing changes affecting the
data. These commands are COMMIT, ROLLBACK, and SAVEPOINT.
 Data Control Language (DCL) - These SQL commands are used for providing security to database objects.
These commands are GRANT and REVOKE.

Q) WHAT ARE THE VARIOUS DATA TYPES AVAILABLE IN SQL


1. Character Datatypes:
• Char – fixed length character string that can varies between 1-2000 bytes
• Varchar / Varchar2 – variable length character string, size ranges from 1-4000 bytes.it saves the disk
space(only length of the entered value will be assigned as the size of column)
• Long - variable length character string, maximum size is 2 GB
2. Number Datatypes: Can store +ve,-ve,zero,fixed point,floating point with 38 precission.
• Number – {p=38,s=0}
• Number(p) - fixed point
• Number(p,s) –floating point (p=1 to 38,s= -84 to 127)
3. Date Datatype: used to store date and time in the table.
 DB uses its own format of storing in fixed length of 7 bytes for
century,date,month,year,hour,minutes,seconds.
 Default data type is “dd-mon-yy”
4. Raw Datatype: used to store byte oriented data like binary data and byte string.
5. Other:
 CLOB – stores character object with single byte character.
 BLOB – stores large binary objects such as graphics,video,sounds.
 BFILE – stores file pointers to the LOB’s.

Q) Explain briefly about DDL Commands (or) Data Definition Language Commands
DDL Commands are as follows
1. CREATE
2. ALTER
3. DROP
4. RENAME and
5. TRUNCATE.

1. CREATE TABLE Statement: The CREATE TABLE Statement is used to create tables to store data.
The Syntax for the CREATE TABLE Statement is:

2
CREATE TABLE table_name (column_name1 datatype, column_name2 datatype,
... column_nameN datatype );

Example: CREATE TABLE employee ( id number(5), name char(20), dept char(10), age number(2),
salary number(10), location char(10) );

2. ALTER TABLE Statement: The SQL ALTER TABLE command is used to modify the definition (structure) of a
table by modifying the definition of its columns. The ALTER command is used to perform the following functions.
a. Add table columns
b. Drop table columns
c. modify table columns
d. Rename table columns

a) To add a column:

ALTER TABLE table_name ADD column_name datatype;

For Example: ALTER TABLE employee ADD experience number(3);

b) To drop a column:

ALTER TABLE table_name DROP column_name;

For Example: ALTER TABLE employee DROP location;

c) To modify a column:

ALTER TABLE table_name MODIFY column_name datatype;

For Example: ALTER TABLE employee MODIFY salary number(15,2);


d) To rename a column:

ALTER TABLE table_name RENAME COLUMN old_name to new_name;

For Example: ALTER TABLE employee RENAME Column Salary to sal;

3. DROP Statement: The SQL DROP command is used to remove an object from the database. If you
drop a table, all the rows in the table is deleted and the table structure is removed from the
database.

DROP TABLE table_name;

For Example: DROP TABLE employee;

4. RENAME Command: The SQL RENAME command is used to change the name of the table or a
database object.
RENAME old_table_name To new_table_name;

For Example: RENAME employee TO my_emloyee;

5. TRUNCATE statement: This command is used to delete all the rows from the table and free the
space containing the table.

TRUNCATE TABLE table_name;

For Example: TRUNCATE TABLE employee;

3
Q) Explain DML Command (OR) Data Manipulation Langage Command.
Ans: DML Stands for Data Manipulation Commands and hence work with data in the table or tables rather than the
objects. The commands that are part of DML are
1. Insert
2. Update and
3. Delete.
1. Insert Command: The INSERT Statement is used to add new rows of data to a table.

INSERT INTO TABLE_NAME [ (col1, col2, col3,...colN)] VALUES (value1, value2, value3,...valueN);

Example: INSERT INTO employee (id, name, dept, age, salary location) VALUES (105, 'Srinath', 'Aeronautics', 27,
33000);

2. UPDATE Command: The UPDATE Statement is used to modify the existing rows in a table.

UPDATE table_name SET column_name1 = value1,


column_name2 = value2, ... [WHERE condition]

Example: UPDATE employee SET location ='Mysore' WHERE id = 101;

3. DELETE Command: The DELETE Statement is used to delete rows from a table.

DELETE FROM table_name [WHERE condition];

Example: DELETE FROM employee WHERE id = 100;

Q) Explain briefly about DCL Commands (OR) Data Control Language Commands
DCL commands are used to enforce database security in a multiple user database environment. Two types of DCL
commands are
1) GRANT and 2) REVOTE.

1) GRANT Command: SQL GRANT is a command used to provide access or privileges on the database
objects to the users.

GRANT privilege_name ON object_name TO {user_name }

privilege_name is the access right or privilege granted to the user. Some of the access rights are ALL, EXECUTE,
and SELECT.
object_name is the name of an database object like TABLE, VIEW, STORED PROC and SEQUENCE.
user_name is the name of the user to whom an access right is being granted.
Example: GRANT SELECT ON employee TO user1;
This command grants a SELECT permission on employee table to user1.You should use the WITH GRANT option
carefully because for example if you GRANT SELECT privilege on employee table to user1 using the WITH GRANT
option, then user1 can GRANT SELECT privilege on employee table to another user, such as user2 etc. Later, if you
REVOKE the SELECT privilege on employee from user1, still user2 will have SELECT privilege on employee table.

2) SQL REVOKE Command: The REVOKE command removes user access rights or privileges to the database
objects.

REVOKE privilege_name ON object_name FROM {user_name |PUBLIC |role_name}

For Example: REVOKE SELECT ON employee FROM user1;


This command will REVOKE a SELECT privilege on employee table from user1.When you REVOKE SELECT
privilege on a table from a user, the user will not be able to SELECT data from that table anymore. However, if the
user has received SELECT privileges on that table from more than one users, he/she can SELECT from that table until
everyone who granted the permission revokes it. You cannot REVOKE privileges if they were not initially granted by
you.
4
Q) What are the aggregate functions in SQL?
Aggregate functions are functions that take a collection (a set or multi-set) of values as input and return a single value.
SQL offers five built-in aggregate functions:

1. SUM(): This function is used to get the sum of a numeric column


2. MIN: This function is used to get the minimum value from a column.
3. MAX: This function is used to get the maximum value from a column
4. AVG: This function is used to get the average value of a numeric column
5. COUNT: This function returns number of rows in a table.
Example: EMP –TABLE

ENAME SALARY
RAJU 5000
JOHN 2000
ROSE 6000
ABHI 8000

SQL Command Output


SQL> select SUM(salary) from emp; SUM(salary)
21000
SQL> select MIN(salary) from emp; MIN(salary)
2000
SQL> select MAX(salary) from emp; MAX(salary)
8000
SQL> select AVG(salary) from emp; AVG(salary)
5240
SQL> select COUNT(salary) from emp; COUNT(salary)
4

Q) WRITE A SHORT NOTE ON NULL IN SQL

SQL allows the use of null values to indicate absence of information about the value of an attribute. We can use the
special keyword null in a predicate to test for a null value.
Thus, to find all loan numbers that appear in the loan relation with null values for amount, we write

select loan-number
from loan
where amount is null

The predicate is not null tests for the absence of a null value. The use of a null value in arithmetic and comparison
operations causes several complications.

SQL treats as unknown the result of any comparison involving a null value (other than is null and is not null).
Since the predicate in a where clause can involve Boolean operations such as and, or, and not on the results of
comparisons, the definitions of the Boolean operations are extended to deal with the value unknown,

• and: The result of true and unknown is unknown, false and unknown is false,
while unknown and unknown is unknown.
• or: The result of true or unknown is true, false or unknown is unknown, while
unknown or unknown is unknown.
• not: The result of not unknown is unknown.

5
Q) WHAT ARE THE SET OPERATORS IN SQL?
Set operators are mainly used to combine the same type of data from two or more tables. The four set operations
union, union all intersect and except allow us to combine two or more SELECT Statements.
Students2003 -Table Students2004 -Table
Name Marks Name Marks
Raju 900 Raju 900
John 1070 Boss 1086
Rose 1032 Rose 1032
Abhi 1002 Marry 1034

Union Operation: The SQL Union is used to combine two tables having same number of columns into a single set.
It will automatically eliminate duplicates.
SQL> (select name, marks from Students2003 ) Name Marks
union Abhi 1002
(select name, marks from Students2004 )
Boss 1086
John 1070
Marry 1034
Raju 900
Rose 1032

Union all: The SQL Union all is used to combine two tables having same number of columns into a single set,
including all duplicates.
SQL> (select name, marks from Students2003 ) Name Marks
Union all Abhi 1002
(select name, marks from Students2004 )
Boss 1086
John 1070
Marry 1034
Raju 900
Raju 900
Rose 1032
Rose 1032

Intersect Operation : The SQL intersect takes the data from both, result sets which are in common.
SQL> (select name, marks from Students2003 )
intersect Name Marks
(select name, marks from Students2004 ) Abhi 1002
Rose 1032

Except Operation: The SQL intersect takes the data from first set, but not the second.
SQL> (select name, marks from Students2003 ) Name Marks
except John 1070
(select name, marks from Students2004 ) Rose 1032

6
Q explain briefly about SUBQUERY

A subquery is a SELECT statement inside the WHERE clause of another SELECT statement. Subqueries can be
used with SELECT, INSERT, UPDATE, DELETE SQL statements along with the comparision operators like =, <,
>, >=, <= etc.
The basic syntax for a subquery is:
SELECT [DISTINCT] select_list FROM table_list WHERE {expression { [NOT] IN | comparison
operator } } ( SELECT [DISTINCT] subquery_select_list FROM table_list WHERE search_conditions

Subqueries are evaluated from the inside out. That is the outer queries action is based on the evaluation of the inner
query

SUBQUERIES WITH THE SELECT STATEMENT:

Example: CUSTOMERS table:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
SQL> SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY >
4500) ;
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
SUBQUERIES WITH THE INSERT STATEMENT:
Example: Consider a table CUSTOMERS_1 with similar structure as CUSTOMERS table. Now to copy
complete CUSTOMERS table into CUSTOMERS_BKP, following is the syntax:

SQL> INSERT INTO CUSTOMERS_1 SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM
CUSTOMERS) ;
SUBQUERIES WITH THE UPDATE STATEMENT:
Example: Following example updates SALARY by 0.25 times in CUSTOMERS table for all the
customers whose AGE is greater than or equal to 27:
SQL> UPDATE CUSTOMERS SET SALARY = SALARY * 0.25 WHERE AGE IN (SELECT AGE FROM
CUSTOMERS1 WHERE AGE >= 27 );
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 125.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 2125.00 |
| 6 | Komal | 22 | MP | 4500.00 |
7
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Subqueries with the DELETE Statement:
Example:Assuming, we have CUSTOMERS1 table available which is backup of CUSTOMERS
table.Following example deletes records from CUSTOMERS table for all the customers whose AGE is
greater than or equal to 27:
SQL> DELETE FROM CUSTOMERS WHERE AGE IN (SELECT AGE FROM CUSTOMERS1 WHERE AGE > 27
);
This would impact two rows and finally CUSTOMERS table would have the following records:
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+

Q) Define a view with an example. Explain the different operators on a view

View: A definition of a restricted portion of the database. Views are useful for maintaining confidentiality and restricts
access to selected parts of the database and for simplifying frequently used query types.
The formats of create view command is

Create view V As
select statement

Create view stud-view as


(Select stud-no, stud-name
From student Where percentage<=35)

A view is a database object that represents one or more database tables. It doesn’t occupy any table Space. Views are
mechanism of data independence. They provide automatic security of hidden data. A view is window to a specific use
of the database. Usage of views:
 Views are used to secure attributes that contain private information.
 Views can be used for creating short cuts for complex queries involving multiple tables.
 Views can be created with a Check option that prevents the updating of rows and attributes that are not part of
the view but are part of complete database

Creating a View: For creating a view following command is used: Syntax:


CREATE or REPLACE VIEW <view name> AS <query>;

Example: CREATE VIEW emp_view AS


SELECT e_code, e_name FROM employee;
Please note that while defining a view an ORDER BY clause cannot be used.
Displaying the view
For displaying all the attributes of the View give the following command:
SELECT * FROM emp_view;
For displaying the attributes of the view use the following command:
DESC emp_view;
Deleting a View
For deleting a View please use the following command:

DROP VIEW emp_view;

8
Q) Describe briefly about SQL Joins

The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN is a means for
combining fields from two tables by using values common to each.

Consider following two tables, (a) CUSTOMERS table is as follows:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

(b) Another table is ORDERS as follows:

+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+

SQL> SELECT ID, NAME, AGE, AMOUNT


FROM CUSTOMERS, ORDERS
WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

This would produce following result:


+----+----------+-----+--------+
| ID | NAME | AGE | AMOUNT |
+----+----------+-----+--------+
| 3 | kaushik | 23 | 3000 |
| 3 | kaushik | 23 | 1500 |
| 2 | Khilan | 25 | 1560 |
| 4 | Chaitali | 25 | 2060 |
+----+----------+-----+--------+
Here it is note able that the join is performed in the WHERE clause. Several operators can be used to join tables, such
as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can all be used to join tables. However, the most
common operator is the equal symbol.

SQL Join Types:


There are different type of joins available in SQL:
returns rows when there is a match in both tables.
returns all rows from the left table, even if there are no matches in the right table.
returns all rows from the right table, even if there are no matches in the left table.
returns rows when there is a match in one of the tables.
is used to join a table to itself, as if the table were two tables, temporarily renaming at least one table
in the SQL statement.
returns the cartesian product of the sets of records from the two or more joined tables.

9
INNER JOIN:
The most frequently used and important of the joins is the INNER JOIN. They are also referred to as an EQUIJOIN.
The INNER JOIN creates a new result table by combining column values of two tables (table1 and table2) based upon
the join-predicate. The query compares each row of table1 with each row of table2 to find all pairs of rows which
satisfy the join-predicate. When the join-predicate is satisfied, column values for each matched pair of rows of A and B
are combined into a result row.

Syntax:

SELECT table1.column1, table2.column2... FROM table1


INNER JOIN table2 ON table1.common_filed = table2.common_field;

Example: Consider following two tables, (a) CUSTOMERS table is as follows:


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
(b) Another table is ORDERS as follows:
+-----+---------------------+-------------+--------+
| OID | DATE | ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+

Now let us join these two tables using INNER JOIN as follows:

SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS


INNER JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce following result:
+----+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+----+----------+--------+---------------------+
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
+----+----------+--------+---------------------+
LEFT JOIN
The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table.

SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS


LEFT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

This would produce following result:


+----+----------+--------+---------------------+

10
| ID | NAME | AMOUNT | DATE |
+----+----------+--------+---------------------+
| 1 | Ramesh | NULL | NULL |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | NULL | NULL |
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
+----+----------+--------+---------------------+

RIGHT JOIN
The SQL RIGHT JOIN returns all rows from the right table, even if there are no matches in the left table.
Now let us join these two tables using RIGHT JOIN as follows:

SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS


RIGHT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

This would produce following result:


+------+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+------+----------+--------+---------------------+
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
+------+----------+--------+---------------------+

FULL JOIN
The SQL FULL JOIN combines the results of both left and right outer joins.
The joined table will contain all records from both tables, and fill in NULLs for missing matches on either side.
SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS
FULL JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

This would produce following result:


+------+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+------+----------+--------+---------------------+
| 1 | Ramesh | NULL | NULL |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | NULL | NULL |
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
+------+----------+--------+---------------------+
SELF JOIN
The SQL SELF JOIN is used to join a table to itself, as if the table were two tables, temporarily renaming at least one
table in the SQL statement.

11
SQL> SELECT a.ID, b.NAME, a.SALARY FROM CUSTOMERS a, CUSTOMERS b
WHERE a.SALARY < b.SALARY;

This would produce following result:


+----+----------+---------+
| ID | NAME | SALARY |
+----+----------+---------+
| 2 | Ramesh | 1500.00 |
| 2 | kaushik | 1500.00 |
| 1 | Chaitali | 2000.00 |
| 2 | Chaitali | 1500.00 |
| 3 | Chaitali | 2000.00 |
| 6 | Chaitali | 4500.00 |
| 1 | Hardik | 2000.00 |
| 2 | Hardik | 1500.00 |
| 3 | Hardik | 2000.00 |
| 4 | Hardik | 6500.00 |
| 6 | Hardik | 4500.00 |
| 1 | Komal | 2000.00 |
| 2 | Komal | 1500.00 |
| 3 | Komal | 2000.00 |
| 1 | Muffy | 2000.00 |
| 2 | Muffy | 1500.00 |
| 3 | Muffy | 2000.00 |
| 4 | Muffy | 6500.00 |
| 5 | Muffy | 8500.00 |
| 6 | Muffy | 4500.00 |
+----+----------+---------+

CARTESIAN JOIN
The CARTESIAN JOIN or CROSS JOIN returns the cartesian product of the sets of records from the two or more
joined tables. Thus, it equates to an inner join where the join-condition always evaluates to True or where the join-
condition is absent from the statement.

Syntax:

SELECT table1.column1, table2.column2...


FROM table1, table2 [, table3 ]

Now let us join these two tables using INNER JOIN as follows:

SQL> SELECT ID, NAME, AMOUNT, DATE


FROM CUSTOMERS, ORDERS;

This would produce following result:


+----+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+----+----------+--------+---------------------+
| 1 | Ramesh | 3000 | 2009-10-08 00:00:00 |
| 1 | Ramesh | 1500 | 2009-10-08 00:00:00 |
| 1 | Ramesh | 1560 | 2009-11-20 00:00:00 |
| 1 | Ramesh | 2060 | 2008-05-20 00:00:00 |
| 2 | Khilan | 3000 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 2 | Khilan | 2060 | 2008-05-20 00:00:00 |

12
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 2060 | 2008-05-20 00:00:00 |
| 4 | Chaitali | 3000 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | 3000 | 2009-10-08 00:00:00 |
| 5 | Hardik | 1500 | 2009-10-08 00:00:00 |
| 5 | Hardik | 1560 | 2009-11-20 00:00:00 |
| 5 | Hardik | 2060 | 2008-05-20 00:00:00 |
| 6 | Komal | 3000 | 2009-10-08 00:00:00 |
| 6 | Komal | 1500 | 2009-10-08 00:00:00 |
| 6 | Komal | 1560 | 2009-11-20 00:00:00 |
| 6 | Komal | 2060 | 2008-05-20 00:00:00 |
| 7 | Muffy | 3000 | 2009-10-08 00:00:00 |
| 7 | Muffy | 1500 | 2009-10-08 00:00:00 |
| 7 | Muffy | 1560 | 2009-11-20 00:00:00 |
| 7 | Muffy | 2060 | 2008-05-20 00:00:00 |
+----+----------+--------+---------------------+

Q) Explain briefly about the structure of tuple relational calculus or formal definition of
tuple relational calculs.

1. The tuple relational calculus is a nonprocedural language.


2. A query in the tuple relational calculus is expressed as

i.e. the set of tuples for which predicate is true.

3. We also use the notation


o to indicate the value of tuple on attribute .
o to show that tuple is in relation .

Formal Definitions

1. A tuple relational calculus expression is of the form

where is a formula.

Several tuple variables may appear in a formula.

2. A tuple variable is said to be a free variable unless it is quantified by a or a . Then it is said to be a bound
variable.
3. A formula is built of atoms. An atom is one of the following forms:
o , where is a tuple variable, and r is a relation ( is not allowed).
o , where and are tuple variables, and and are attributes, and is a comparison operator
( ).
o , where is a constant in the domain of attribute .
4. Formulae are built up from atoms using the following rules:
o An atom is a formula.

13
o If is a formula, then so are and .
o If and are formulae, then so are , and .
o If is a formula containing a free tuple variable , then

are formulae also.

5. Note some equivalences:


o
o
o

Example Queries

1. For example, to find the branch-name, loan number, customer name and amount for loans over $1200:

This gives us all attributes, but suppose we only want the customer names.

We need to write an expression for a relation on scheme (cname).

In English, we may read this equation as ``the set of all tuples such that there exists a tuple in the relation
borrow for which the values of and for the cname attribute are equal, and the value of for the amount attribute
is greater than 1200.''

The notation means ``there exists a tuple in relation such that predicate is true''.

How did we get the above expression? We needed tuples on scheme cname such that there were tuples in
borrow pertaining to that customer name with amount attribute .

The tuples get the scheme cname implicitly as that is the only attribute is mentioned with.

Let's look at a more complex example.

Find all customers having a loan from the SFU branch, and the the cities in which they live:

In English, we might read this as ``the set of all (cname,ccity) tuples for which cname is a borrower at the SFU
branch, and ccity is the city of cname''.

Tuple variable ensures that the customer is a borrower at the SFU branch.

Tuple variable is restricted to pertain to the same customer as , and also ensures that ccity is the city of the
customer.

The logical connectives (AND) and (OR) are allowed, as well as (negation).

We also use the existential quantifier and the universal quantifier .

Some more examples:


14
1. Find all customers having a loan, an account, or both at the SFU branch:

Note the use of the connective.


As usual, set operations remove all duplicates.

2. Find all customers who have both a loan and an account at the SFU branch.

Solution: simply change the connective in 1 to a .

3. Find customers who have an account, but not a loan at the SFU branch.

4. Find all customers who have an account at all branches located in Brooklyn. (We used division in
relational algebra.)

For this example we will use implication, denoted by a pointing finger in the text, but by here.

The formula means implies , or, if is true, then must be true.

In English: the set of all cname tuples such that for all tuples in the branch relation, if the value of on attribute
bcity is Brooklyn, then the customer has an account at the branch whose name appears in the bname attribute of

Q) Explain briefly about the structure of Domain relational calculus.


The Domain Relational Calculus
1. Domain variables take on values from an attribute's domain, rather than values for an entire tuple.

Formal Definitions

1. An expression is of the form

where the represent domain variables, and is a formula.


2. An atom in the domain relational calculus is of the following forms
o where is a relation on attributes, and , are domain variables or
constants.
o , where and are domain variables, and is a comparison operator.
o , where c is a constant.
3. Formulae are built up from atoms using the following rules:
o An atom is a formula.
o If is a formula, then so are and .
o If and are formulae, then so are , and .
o If is a formula where x is a domain variable, then so are and .

Example Queries

1. Find branch name, loan number, customer name and amount for loans of over $1200.

15
2. Find all customers who have a loan for an amount > than $1200.

3. Find all customers having a loan from the SFU branch, and the city in which they live.

4. Find all customers having a loan, an account or both at the SFU branch.

5. Find all customers who have an account at all branches located in Brooklyn.

If you find this example difficult to understand, try rewriting this expression using implication, as in the tuple
relational calculus example. Here's my attempt:

I've used two letter variable names to get away from the problem of having to remember what stands for.

Q) How to Modifying the Database in Domain Relational Calculus.

1. Up until now, we have looked at extracting information from the database. We also need to add, remove and
change information. Modifications are expressed using the assignment operator.

Deletion

1. Deletion is expressed in much the same way as a query. Instead of displaying, the selected tuples are removed
from the database. We can only delete whole tuples.
In relational algebra, a deletion is of the form

where is a relation and is a relational algebra query.


Tuples in for which is true are deleted.
2. Some examples:
1. Delete all of Smith's account records.

2. Delete all loans with loan numbers between 1300 and 1500.

3. Delete all accounts at Branches located in Needham.

Insertions

1. To insert data into a relation, we either specify a tuple, or write a query whose result is the set of tuples to be
inserted. Attribute values for inserted tuples must be members of the attribute's domain.
2. An insertion is expressed by

where is a relation and is a relational algebra expression.


3. Some examples:
1. To insert a tuple for Smith who has $1200 in account 9372 at the SFU branch.

2. To provide all loan customers in the SFU branch with a $200 savings account.

16
Updating

1. Updating allows us to change some values in a tuple without necessarily changing all.
We use the update operator, , with the form

where is a relation with attribute , which is assigned the value of expression .


The expression is any arithmetic expression involving constants and attributes in relation .
Some examples:
1. To increase all balances by 5 percent.

This statement is applied to every tuple in deposit.


2. To make two different rates of interest payment, depending on balance amount:

Q) Explain the Basic Structure of QBE.

1. QBE has ``two-dimensional'' syntax.


2. Queries are expressed by example.
3. Close correspondence with domain relational calculus
4. Non-procedural.
5. Queries are expressed using skeleton tables.
6. User selects the skeletons needed.
7. User fills in skeletons with example rows.
8. An example row consists of constants and example elements which are really domain variables.
9. Domain variables are preceded by an underscore character.
10. Constants appear without any qualification.

Simple Queries

1. For example, to find all customers having an account at the SFU branch:

o A P. before the variable causes printing.


o A P.ALL. prefix suppresses duplicate elimination.
o A P. in front of the row prints all attributes.
o The domain variable may be omitted if it is not used elsewhere.
o Arithmetic expressions are allowed.
o Comparison operators are allowed, space on left hand side is left blank.
2. To find the names of all branches not located in Burnaby:

3. To find all customers having an account at both the SFU and the MetroTown branch:

4. To find all customers having an account at either branch or both:

17
5. Find all customers having an account at the same branch as Jones:

Queries on Several Relations

1. Queries on several relations require several skeleton tables.


2. To find the name and city of all customers having a loan at the SFU branch:

3. Find the name of all customers having an account at the SFU branch, but no loan from that branch.

Queries involving negation can be expressed by putting a sign under the relation name beside an example
row:

4. To find all customers who have accounts at two different branches:

The Condition Box

1. When it is difficult or impossible to express all constraints on the domain variables within the skeleton tables,
the condition box may be used.
2. To add the constraint that we are only interested in customers other than Jones to the above query, we include
the condition box:

3. To find all account numbers with balances between $1,300 and $1,500:

18
4. Logical expressions and and or may appear in the condition box.
5. To find all account numbers where the balance is between $1,300 and $2,000, but is not $1,500:

6. An unconventional use of the or construct allows comparison with several constant values:

The Result Relation

1. If the result of a query includes attributes from several relation schemes, we need a way of displaying the result
in a single table.
2. We can declare a temporary result relation including the attributes to be displayed. We put the print command
only in that table.
3. To find the customer names and cities and account numbers for all customers having an account at the SFU
branch:

Ordering the Display of Tuples

1. The order in which tuples are displayed can be controlled by adding the command AO. (ascending order) or
DO. (descending order) to the print command:

2. To sort first by name, and then by balance for those with multiple accounts:

Aggregate Operations

1. QBE includes the aggregate operators AVG, MAX, MIN, SUM and CNT. As QBE eliminates duplicates by
default, they must have ALL. appended to them.

19
2. To find the total balance of all accounts belonging to Jones:

3. All aggregate operators must have ALL. appended, so to override the ALL.\ we must add UNQ. (unique).
(NOTE: a number of examples in the text incorrectly show UNQ. replacing ALL.)

4. To compute functions on groups, we use the G. operator. To find the average balance at each branch:

5. To find the average balances at only branches where the average is more than $1,200, we add the condition
box:

6. To find all customers who have an account at all branches located in Burnaby, we can do:

Modifying the Database

1. QBE has facilities for modifying the database.

1. We simply use D. instead of the P. operator. Whole tuples may be deleted, or only some columns.
2. Delete all of Smith's account records:

3. Delete the branch-city value for the SFU branch:

4. Delete all loans with loan numbers between 1300 and 1500:

20
5. Delete all accounts at branches located in Burnaby:

Insertion

1. Insertion uses the I. operator.


2. To insert an account tuple for Smith:

3. If values are missing, nulls are inserted.


4. To provide all loan customers in the SFU branch with a $200 savings account:

Updates

1. We can update individual attributes with the U. operator. Fields left blank are not changed.
2. To update the assets of the SFU branch to $10,000,000:

3. To make interest payments of 5% on all balances:

21

You might also like