Vous êtes sur la page 1sur 46

Database Management System

Exp 1: Introduction to DBMS and SQL.


1.1 What is Database?
A database consists of an organized collection of data for one or more uses, typically in digital form. One way of classifying databases involves the type of their contents, for example: bibliographic, document-text, statistical. Digital databases are managed using database management systems, which store database contents, allowing data creation and maintenance, and search and other access.

1.2 What is DBMS?


A database management system (DBMS) consists of software that operates databases, providing storage, access, security, backup and other facilities. Database management systems can be categorized according to the database model that they support, such as relational or XML, the type(s) of computer they support, such as a server cluster or a mobile phone, the query language(s) that access the database, such as SQL or XQuery, performance trade-offs, such as maximum scale or maximum speed or others. Some DBMS cover more than one entry in these categories, e.g., supporting multiple query languages.

1.3 Benefits of DBMS


Most DBMS as of 2009 implement a relational model. A true DBMS offers several advantages over file processing. The principal advantages of a DBMS are the following: Flexibility: Because programs and data are independent, programs do not have to be modified when types of unrelated data are added to or deleted from the database, or when physical storage changes. Fast response to information requests: Because data are integrated into a single database, complex requests can be handled much more rapidly then if the data were located in separate, non-integrated files. In many businesses, faster response means better customer service. Multiple access: Database software allows data to be accessed in a variety of ways and often, by using several programming languages. Lower user training costs: Users often find it easier to learn such systems and training costs may be reduced. Also, the total time taken to process requests may be shorter, which would increase user productivity.

ISHA AGGARWAL (80805107023)

Database Management System

Less storage: Theoretically, all occurrences of data items need to be stored only once, thereby eliminating the storage of redundant data. System developers and database designers often use data normalization to minimize data redundancy.

1.4 Introduction to SQL


SQL stands for Structured Query Language. It lets you access and manipulate databases. It can execute queries against a database. It can retrieve data and delete records from a database. It can insert records and update records in a database. SQL can create new databases. It can create new tables in a database. It can create stored procedures in a database. It can create views in a database. SQL can set permissions on tables, procedures, and views. Although SQL is an ANSI (American National Standards Institute) standard, there are many different versions of the SQL language.

1.5 Features of SQL


SQL is both an easy-to-understand language and a comprehensive tool for managing data. Here are some of the major features of SQL and the market forces that have made it successful:

Vendor independence. Portability across computer systems. SQL standards. Relational foundation. High-level, English-like structure. Interactive, ad hoc queries. Programmatic database access. Multiple views of data. Complete database language. Dynamic data definition. Client/server architecture. Enterprise application support. Extensibility and object technology. Internet database access. Industry infrastructure.

1.6 Components of SQL


ISHA AGGARWAL (80805107023)

Database Management System


SQL consists of four components: 1. 2. 3. 4. Data Definition Language (DDL) Data Manipulation Language (DML) Data Control Language (DCL) Data Query Language (DQL)

The Data Definition Language (DDL): This component of the SQL language is used to create and modify tables and other objects in the database. The main commands are: CREATE TABLE tablename to create a table in the database. DROP TABLE tablename to remove a table from the database. ALTER TABLE tablename to add or remove columns from a table in the database. The Data Manipulation Language (DML): This component of the SQL language is used to manipulate data within a table. The main commands are: INSERT to insert rows of data into a table. UPDATE to change rows of data in a table. DELETE to remove rows of data from a table. The Data Control Language (DCL): This component of the SQL language is used to create privileges to allow users access to, and manipulation of, the database. The main commands are: GRANT to grant a privilege to a user. REVOKE to revoke (remove) a privilege from a user. The Data Query Language (DQL): This component of the SQL language is used to view the changes that have been made on the table in the database. The main commands are: SELECT to select rows of data from a table.

ISHA AGGARWAL (80805107023)

Database Management System

Exp 2: To implement DDL, DML, DCL, and DQL statements in SQL server 2005.
1. DDL (Data Definition Language) 2. DML (Data Manipulation Language) 3. DCL (Data Control Language) 4. DQL (Data Query Language) 1. DDL (Data Definition Language):- It is a set of SQL commands used to
create, modify and delete database structures but not data. They are normally used by the DBA not by user to a limited extent, a database designer or application developer. These statements are immediate i.e. they are not susceptible to ROLLBACK commands. It should also be noted that if several DML statements for example UPDATES are executed then issuing any DDL command would COMMIT all the updates as every DDL command implicitly issues a COMMIT command to the database. Anybody using DDL must have the CREATE object privilege and a table space area in which to create objects. For example: - CREATE, ALTER, DROP, TRUNCATE, COMMENT etc. THE CREATE TABLE COMMAND: - The CREATE TABLE command defines each column of the table uniquely. Each column has a minimum of three attributes, a name, data type and size (i.e. column width). Syntax :- create table<table name>(<column Name 1><data type>(<size>), <columnname2><data type>(<size>)) Example:create table student ( name varchar(23), roll_no number(12), class varchar2(12), address varchar(23) );
ISHA AGGARWAL (80805107023)

Database Management System

2. DML (Data Manipulation Language):- The Data Manipulation Language


(DML) is used to retrieve, insert and modify database information. These commands will be used by all database users during the routine operation of the database. The various commands under this are: INSERT INTO, UPDATE TABLE, DELETE FROM, DROP, ALTER TABLE, etc.

THE INSERTION OF DATA INTO TABLE: - The INSERT command in SQL is used to add records to an existing table. Returning to the personal_info example from the previous section, let's imagine that our HR department needs to add a new employee to their database.

Syntax: - INSERT INTO <table name > (<columnname1>,<columnname2>) VALUES (<expression1>, <expression 2>) OR INSERT INTO <tablename>VALUES (<expression1 >,<expression2> )

Example:Insert into student(name,roll_no,class,address)values('Prabhat',06,'BCA',Hatlimore');

UPDATING THE CONTENTS OF THE TABLE: - The update command is used to change or modify data values in a table. The verb UPDATE in SQL is used to either all the rows from a table or a select set of rows from a table.

Syntax:-UPDATE < Table name> SET <column name1>=<expression1>, <columnname2>=<expression2> WHERE <condition>

ISHA AGGARWAL (80805107023)

Database Management System


Example:update employee set employee=Roy where employee=Sam

DROP COMMAND: - By using the DROP TABLE statement with the table name we can destroy a specific table.

Syntax: - DROP TABLE <table name>;

Example: - Drop table student;

ALTER TABLE COMMAND: - The structure of a table can be modified by

using the ALTER TABLE command. ALTER TABLE allows changing the structure of an existing table. With ALTER TABLE it is possible to add or delete columns, create or destroy indexes, changes the data type of existing columns, or rename columns or the table itself.

Syntax: - ALTER TABLE <Table name>ADD(<New column Name><data type> (<size>),<new column name><data type>(<size>))

Example: - alter table prabhu drop column name

DELETE COMMAND: - This command is used to delete rows or records in a

table.

ISHA AGGARWAL (80805107023)

Database Management System


Syntax: - delete from "tablename" where columnname OPERATOR value [and|or columnnamex OPERATOR valuex];

Example: - delete from citylist where name = 'Argos' and state = 'Indiana';

3. DCL (Data Control Language):- A Data Control Language or DCL is a


part Structured Query Language (SQL) used to control the access to data in a database. For any in-house or outsource software development process, Data Control Language plays the critical role of setting authorization mechanism of the database.Data Control Language primarily includes the following commands: GRANT, REVOKE, etc.

GRANT COMMAND: - GRANT is a command used to provide access or privileges on the database objects to the users.

Syntax: - GRANT privilege-type ON [TABLE] <table-Name / viewName > TO grantees

Example: - grant insert into to user1 on employee

REVOKE COMMAND: - Use the REVOKE statement to remove privileges from a specific user or role, or from all users, to perform actions on database objects. You can also use the REVOKE statement to revoke a role from a user, from PUBLIC, or from another role.
ISHA AGGARWAL (80805107023)

Database Management System

Syntax: - REVOKE privilege-type ON [ TABLE ] < table-Name | viewName> FROM grantees

Example: - revoke insert into from user1 on employee

4. DQL (Data Query Language) :- The language used to query data which is a
content management system used to create, manage, deliver, and archive all types of content from text documents and spreadsheets to digital images, HTML, and XML components. DQL (Data Query Language) is a query language which allows you to do very complex queries involving: Example: SELECT

SELECT COMMAND: - SELECT statement returns a result set of records from

one or more tables.

Syntax: - select * from <table name> Or select <column name> from <table name>

Example: - select * from employee

ISHA AGGARWAL (80805107023)

Database Management System Exercise 1: Create the following tables:


client_master client_no name address city pincode state productMaster product_no description price quantity 1. Find out the names of all the clients. 2. Retrieve the entire contents of client_master table. 3. Retrieve the list of names and adddress of all the clients who are located in mumbai. 4. Change the city of client_no 5 to bangalore. 5. Change the price of first product in the productMaster table to 2000. 6. Delete all the products where the quantity=100. 7. Destroy the client_master table along with its data. 8. Make the table productMaster empty.

Solutions:
create table client_master ( client_no int primary key, name char(30), address varchar(30), city varchar(30), pincode int, state char(30) ); select * from client_master;

insert into client_master values(1,'ram','ashok vihar','delhi',1200,'delhi'); insert into client_master values(2,'sham','vasant vihar','ludhiana',1209,'punjab'); insert into client_master values(3,'amy','ghumar mandi','patiala',1304,'punjab'); insert into client_master values(4,'mary','preet vihar','sirhind',1809,'punjab'); insert into client_master values(5,'sita','karol bagh','delhi',1289,'delhi');

ISHA AGGARWAL (80805107023)

Database Management System


insert into client_master values(6,'gita','kashi nagar','lucknow',1804,'uttar pradesh'); insert into client_master values(7,'sam','ashok vihar','vellore',1767,'mumbai'); select * from client_master;

10

create table productMaster ( product_no int primary key, description varchar(30), price int, quantity int ); select * from productMaster;

insert into productMaster values(1001,'bottle',50,2); insert into productMaster values(1002,'pencil box',100,6); insert into productMaster values(1003,'note book',10,3); insert into productMaster values(1004,'pen',70,8); insert into productMaster values(1005,'eraser',35,100); insert into productMaster values(1006,'bag',500,7); select * from productMaster;

Query 1: Find out the names of all the clients.


ISHA AGGARWAL (80805107023)

Database Management System


Solution:
select name from client_master; select * from client_master;

11

Output:

Query 2: Retrieve the entire contents of client_master table. Solution:


select * from client_master;

Output:

Query 3: Retrieve the list of names and adddress of all the clients who are located in
ISHA AGGARWAL (80805107023)

Database Management System


mumbai. Solution:
select name,address from client_master where state='mumbai'; select * from client_master;

12

Output:

Query 4: Change the city of client_no 5 to bangalore. Solution:


update client_master set city='bangalore' where client_no='5'; select * from client_master;

Output:

Query 5: Change the price of first product in the productMaster table to 2000. Solution:
ISHA AGGARWAL (80805107023)

Database Management System


update productMaster set price=2000 where product_no=1001; select * from productMaster;

13

Output:

Query 6: Delete all the products where the quantity=100. Solution:


delete from productMaster where quantity=100; select * from productMaster;

Output:

Query 7: Destroy the client_master table along with its data. Solution:
drop table client_master; select * from client_master;

Output:

Query 8: Make the table productMaster empty. Solution:


delete from productMaster;

ISHA AGGARWAL (80805107023)

Database Management System


select * from productMaster;

14

Output:

Exercise 2: 1. Create the following tables:


student_info
ISHA AGGARWAL (80805107023)

Database Management System


s_rollno s_name course_no course_info course_id course_name 2. Insert 6 records in both tables. 3. Show the different courses taken by the students. 4. Change the name of table student_info to student. 5. Change the name of column s_rollno to rollno. 6. Add a column contact of datatype int to student table. 7. Delete a column contact from student table. 8. Increase the size of column course_name. 9. Implement the concept of foreign key.

15

Solutions:
Query 1: Create the following tables: student_info s_rollno s_name course_no course_info course_id course_name Solution:
create table student_info ( s_rollno int primary key, s_name char(20), course_no int references course_info(course_id) on delete cascade ); select * from student_info;

Output:

ISHA AGGARWAL (80805107023)

Database Management System


Solution:
create table course_info ( course_id int primary key, course_name char(20) ); select * from course_info;

16

Output:

Query 2: Insert 6 records in both tables. Solution:


insert into student_info values(1,'ram',1); insert into student_info values(2,'sham',2); insert into student_info values(3,'karam',5); insert into student_info values(4,'param',2); insert into student_info values(5,'angel',3); insert into student_info values(6,'rusty',4); select * from student_info;

Output:

Solution:
insert into course_info values(1,'CSE'); insert into course_info values(2,'ECE'); insert into course_info values(3,'MECH'); insert into course_info values(4,'CIVIL'); insert into course_info values(5,'EE'); insert into course_info values(6,'IT'); select * from course_info;

Output:
ISHA AGGARWAL (80805107023)

Database Management System

17

Query 3: Show the different courses taken by the students. Solution:


select distinct(course_no) from student_info;

Output:

Query 4: Change the name of table student_info to student. Solution:


sp_rename 'student_info', 'student'; select * from student;

Output:

ISHA AGGARWAL (80805107023)

Database Management System

18

Query 5: Change the name of column s_rollno to rollno. Solution:


sp_rename 'student.s_rollno','rollno'; select * from student;

Output:

Query 6: Add a column contact of datatype int to student table. Solution:


alter table student add contact int; select * from student;

Output:

Query 7: Delete a column s_name from student table.


ISHA AGGARWAL (80805107023)

Database Management System


Solution:
alter table student drop column s_name; select * from student;

19

Output:

Query 8: Increase the size of column course_name. Solution: Output: Query 9: Implement the concept of foreign key. Solution: Output:

ISHA AGGARWAL (80805107023)

Database Management System

20

Exp 3: To use constraints on the created database.


1. PRIMARY KEY 2. FOREIGN KEY 3. CHECK 4. NOT NULL

1. PRIMARY KEY: - The primary key of a relational table uniquely identifies each

record in the table. It can either be a normal attribute that is guaranteed to be unique or it can be generated by the DBMS. Primary keys may consist of a single attribute or multiple attributes in combination.

Syntax: - CREATE TABLE table_name (column1 datatype null/not null, column2 datatype null/not null, ... CONSTRAINT constraint_name PRIMARY KEY (column1, ..));

Example: - CREATE TABLE supplier ( supplier_id numeric(10) not null,

supplier_name varchar2(50) not null, contact_name varchar2(50), CONSTRAINT supplier_pk PRIMARY KEY (supplier_id) );

ISHA AGGARWAL (80805107023)

Database Management System

21

2. FOREIGN KEY: - A foreign key means that values in one table must also

appear in another table. The referenced table is called the parent table while the table with the foreign key is called the child table. The foreign key in the child table will generally reference a primary key in the parent table. A foreign key can be defined in either a CREATE TABLE statement or an ALTER TABLE statement

Syntax: - CREATE TABLE table_name (column1 datatype null/not null, column2 datatype null/not null, ... CONSTRAINT fk_column FOREIGN KEY (column1, column2, ... column_n) REFERENCES parent_table (column1, column2, ... column_n) );

Example: - CREATE TABLE supplier ( supplier_id numeric(10) not null,

supplier_name varchar2(50) not null, contact_name varchar2(50), CONSTRAINT supplier_pk PRIMARY KEY (supplier_id) );

3. CHECK: - A check constraint allows you to specify a condition on each row in a

table.
ISHA AGGARWAL (80805107023)

Database Management System

22

Syntax: - CREATE TABLE table_name (column1 datatype null/not null, CONSTRAINT constraint_name CHECK (column_name condition) ); Example: - CREATE TABLE suppliers ( supplier_id numeric(4), supplier_name varchar2(50), CONSTRAINT check_supplier_id CHECK (supplier_id BETWEEN 100 and 9999));
4. NOT NULL: - The NOT NULL constraint enforces a field to always contain a

value. This means that you cannot insert a new record, or update a record without adding a value to this field. The NOT NULL column constraint ensures that a table column cannot beeft empty.

Syntax: - <columnname><datatype>(<size>) NOT NULL;

Example: - st_id int NOT NULL;

ISHA AGGARWAL (80805107023)

Database Management System Exercise 3:1. Create the following tables: student_info
sid(primary key) sname course_no(foreign key)

23

city

Course__Info
course_id (primary key) cname

2. Insert records in Course__Info with course_id=10,20,30,40. 3. Insert records in student_info with course_no=10,20,50. 4. Make the city column values unique, NULL can be entered into city column. 5. Drop the constraint foreign key from student_info table. 6. Show all the student ids in descending order. 7. Display all the records of course_info table according to the increasing values of course_id. 8. Drop the constraint primary key from student info. 9. Delete all the data from the sname column and also delete all the data from student_info table. 10. Make the sid column as primary key and course_no column as foreign key using alter table command.
ISHA AGGARWAL (80805107023)

Database Management System

24

Solutions:

Query 1:- Create the following tables: student_info sid(primary key) sname course_no(foreign key) city

Course__Info course_id (primary key) cname

Solution:
create table "student_info" ( sid int primary key, sname char(20), "course no" int references "course__Info"("course id") on delete cascade, city char(20) ); select * from "student_info";

Output:

Solution:
create table "Course__Info" ( "course id" int primary key, cname char(20) );

ISHA AGGARWAL (80805107023)

Database Management System


select * from "Course__Info";

25

Output:

Query 2:- Insert records in Course__Info with course_id=10,20,30,40. Solution:


insert into "course__Info" values(10,'cse'); insert into "course__Info" values(20,'ee'); insert into "course__Info" values(30,'ece'); insert into "course__Info" values(40,'it'); select * from "course__Info";

Output:

Query 3:- Insert records in student_info with course_no=10,20,50. Solution:


insert into "student_info" values(1,'ajay',10,'noida'); insert into "student_info" values(2,'vijay',20,'patiala'); insert into "student_info" values(3,'pronoy',50,'amritsar'); select * from "student_info";

Output:
Msg 547, Level 16, State 0, Line 3 The INSERT statement conflicted with the FOREIGN KEY constraint "FK__student_i__cours__60083D91". The conflict occurred in database "master", table "PC-1-500\student.course_info", column 'course id'. The statement has been terminated.

Query 4:- Make the city column values unique, NULL can be entered into city column.
ISHA AGGARWAL (80805107023)

Database Management System


Solution:
create table "student_info" ( sid int primary key, sname char(20), "course no" int references "course__Info"("course id") on delete cascade, city char(20) unique ); insert into "student_info" values(1,'ajay',10,'noida'); insert into "student_info"(sid,sname,"course no") values(2,'vijay',20); insert into "student_info" values(3,'pronoy',30,'amritsar'); select * from "student_info";

26

Output:

Query 5:- Drop the constraint foreign key from student_info table. Solution:
create table "student_info" ( sid int primary key, sname char(20), courseno int, constraint fkey foreign key (courseno) references "course__Info"("course id"), city char(20) unique ); alter table "student_info" drop constraint fkey; insert into "student_info" values(1,'ajay',10,'noida'); insert into "student_info"(sid,sname,courseno) values(2,'vijay',20); insert into "student_info" values(3,'pronoy',50,'amritsar'); select * from "student_info";

Output:

ISHA AGGARWAL (80805107023)

Database Management System

27

Query 6:- Show all the student ids in descending order. Solution:
select * from student_info order by sid desc;

Output:

Query 7:- Display all the records of course_info table according to the increasing values of course_id. Solution:
select * from course__Info order by "course id";

Output:

Query 8:- Drop the constraint primary key from student info. Solution:
create table "student_info" ( sid int, sname char(20),

ISHA AGGARWAL (80805107023)

Database Management System


courseno int references "course__Info"("course id") on delete cascade, constraint pkey primary key (sid), city char(20) ); alter table "student_info" drop constraint pkey; insert into "student_info" values(1,'ajay',10,'noida'); insert into "student_info" values(1,'vijay',20,'patiala'); insert into "student_info" values(3,'pronoy',30,'amritsar'); select * from "student_info";

28

Output:

Query 9:- Delete all the data from the sname column and also delete all the data from student_info table. Solution:
delete from student_info; select * from student_info;

Output:

Query 10:- Make the sid column as primary key and course_no column as foreign key using alter table command. Solution: Output:

ISHA AGGARWAL (80805107023)

Database Management System

29

Exp 4: To explore select statement using where clause with various operators and order by clause.
SQL Operators: SQL operators are found in just every SQL query. Operators are the
mathematical and equality symbols used to compare, evaluate, or calculate values. When SQL come across these operators, they help tell SQL how to evaluate an expression or conditional statement in the WHERE clause of SQL commands. There are various types of operators: 1. 2. 3. 4. 5. Arithmetic operators. Logical operators. Comparison operators. Range searching operators. Pattern matching operators.

Arithmetic operators:- These are mathematical operators used to perform addition(+), subtraction(-), multiplication(*), division(/). We can use SQL like a calculator to get a feel for how these operators work. Logical operators:- These operators provide you with a way to specify exactly what you want SQL to go and fetch, and you may be as specific as youd like. AND, OR and NOT are the logical operators. Comparison operators: - These operators are used to compare various set of values. > (greater than), < (less than), = (equals to), <> or != (not equals to), <= (less than equals to), >= (greater than equals to), is NULL, is NT NULL.
ISHA AGGARWAL (80805107023)

Database Management System

30

Range searching operators:- These operators are used to specify the range of values. BETWEEN and NOT BETWEEN keywords are used to specify range. Pattern matching operators:- These operators are used to find some specified string pattern in the given string. LIKE, NOT LIKE, IN, NOT IN are the operators used along with some predicates like %,_,[] to find the desired string pattern.

Order by clause:-

SQL allows data to be viewed in a sorted order. The rows retrieved from the table will be sorted in either ascending or descending order depending on the condition specified in the SELECT statement. Syntax: - select * from <tablename> order by<columnname1>, <columnname2> <[sort order]>; Example: - select * from master order by name;

Exercise 4:-Create the following tables:


Client_master
cid(primary key) cname

city

product_master pcode pname price

1. List the names of all clients having a as the second letter in their names.
2. List all the clients who stay in city whose first letter and second letter should lie

between a tos and a to n and last letter should be a. 3. List all the clients who stay in Bangalore or Chandigarh. 4. List all the clients of Bangalore whose names start with either a or b or c.
ISHA AGGARWAL (80805107023)

Database Management System


5. List the names of all the products with price having any one of the following values 1000, 2000, 5000, 6000, 4000. 6. Display the names of all the products whose price is not 1000.

31

7. List all products whose price should not be between 5000 and 10,000 and having name consist of 3 characters. The products should be arranged in decreasing order according to the price. 8. Display the following data. Price per day Price per month Annual price

Solutions:-

create table"client_master" ( cid int, cname char(90), city char(10), ); insert into client_master values(1,'sarab','patiala'); insert into client_master values(2,'aman','bangalore'); insert into client_master values(3,'nidhi','delhi'); insert into client_master values(4,'shivangi','chandigarh'); insert into client_master values(5,'isha','kerala'); insert into client_master values(6,'siddharth','assam'); select * from client_master;

ISHA AGGARWAL (80805107023)

Database Management System

32

create table product_master (pcode int, pname char(20), price int, ); insert into product_master values(001,'oil',1000); insert into product_master values(002,'copy',500); insert into product_master values(003,'pen',100); insert into product_master values(004,'heater',5000); insert into product_master values(005,'fan',3000); insert into product_master values(006,'pencil',50); select * from product_master;

Query 1:- List the names of all clients having a as the second letter in their names. Solution:
select cname from client_master where cname like '_a%';

ISHA AGGARWAL (80805107023)

Database Management System


Output:

33

Query 2:- List all the clients who stay in city whose first letter and second letter should lie between a tos and a to n and last letter should be a.

Solution:
select * from client_master where city like '[a-s][a-n]%a';

Output:

Query 3:- List all the clients who stay in Bangalore or Chandigarh. Solution:
select * from client_master where city like 'bangalore' or city like 'chandigarh';

Output:

Query 4:- List all the clients of Bangalore whose names start with either a or b or c. Solution:
ISHA AGGARWAL (80805107023)

Database Management System


select * from client_master where cname like 'a%' or cname like 'b%' or cname like 'c%' and city='bangalore';

34

Output:

Query 5:- List the names of all the products with price having any one of the following values 1000, 2000, 5000, 6000, 4000. Solution:
select pname from product_master where price in(1000,2000,100,3000,500);

Output:

Query 6:- Display the names of all the products whose price is not 1000. Solution:
select pname from product_master where price!=1000 ;

Output:

Query 7:- List all products whose price should not be between 5000 and 10,000 and
ISHA AGGARWAL (80805107023)

Database Management System


having name consist of 3 characters. The products should be arranged in decreasing order according to the price. Solution:

35

select * from product_master where price not in (5000-10000) and pname like '___' order by price desc;

Output:

Query 8:- Display the following data.

Price per day

Price per month

Annual price

Solution:
select price/30 "price per day", price "price per month", price*12 "annual price" from product_master;

Output:

ISHA AGGARWAL (80805107023)

Database Management System

36

Exp 5: To study SQL functions, group by and having clause.


SQL functions serve the purpose of manipulating data items and returning a result. Functions are also capable of accepting user-supplied variables or constants and operating on them. Such variables or constants are arguments. Any number of arguments can be passed to a function: Syntax: - function_name (argument1, argument2, ..) SQL functions are mainly of 3 types: 1. Group functions/ Aggregate functions. 2. Scalar functions. 3. String functions.

Group functions: - Functions that act on a set of values are known as group functions. A group function returns a single result row for a group of queried rows. We can use following functions: AVG- To calculate average. MIN- To find minimum value. MAX- To find maximum value. COUNT- To count total number of records. SUM- To find the sum of vlues on a row or column. Scalar functions:- These functions act on only one vaue at a time. A single row function return one result for every row of a queried table or view. We can use following funtions: ABS- To find absolute value. POWER(m,n)- To find the power of a number, where m is raised to the power of n. ROUND(m,n)-To find the round of value of a decimal value, where m is the value and n is the precison value. SQRT- To find the square root of a number. String functions:- These functions act on string values. We can use the following functions: LOWER- To convert the given sring into lowercase. UPPER- To convert the given string into uppercase. ASCII- To find the ascii code of a given character. SUBSTRING(string, start_position, length)- To find the substring from a given string. Exercise 4:- Create a table and find the result for all the functions.
ISHA AGGARWAL (80805107023)

Database Management System

37

Solutions:create table product_master ( product_no int primary key, description varchar(30), price varchar(20), quantity int ); insert insert insert insert insert insert into into into into into into product_master product_master product_master product_master product_master product_master values(1,'abc',500,2); values(2,'abc',300,2); values(3,'abc',400,2); values(4,'abc',700,2); values(5,'tools,Rs 400/-,2); values(6,'bags',Rs 500/-,3);

select * from product_master;

Output:

Group functions: -

1. AVG
Solution:
select avg(quantity) from product_master;

Output:

2. MIN
ISHA AGGARWAL (80805107023)

Database Management System


Solution:
select min(product_no) from product_master;

38

Output:

3. MAX
Solution:
select max(product_no) from product_master;

Output:

4. COUNT
Solution:
select count(*) from product_master;

Output:

5. SUM
Solution:
select sum(quantity) from product_master;

Output:

Scalar functions:ISHA AGGARWAL (80805107023)

Database Management System 1. ABS


Solution:
select abs(-10);

39

Output:

2. POWER (m,n)
Solution:
select power(10,2);

Output:

3. ROUND (m,n)
Solution:
select round(10.127,2);

Output:

4. SQRT
Solution:
ISHA AGGARWAL (80805107023)

Database Management System


select sqrt(2);

40

Output:

String functions:-

select * from product_master;

1. LOWER Solution:
select lower('HELLO HOW ARE YOU?');

Output:

2. UPPER Solution:
select upper(description) from product_master;

ISHA AGGARWAL (80805107023)

Database Management System


Output:

41

3. ASCII Solution:
select ASCII('a');

Output:

4. SUBSTRING(string, start_position, length) Solution:


select substring('HELLO HOW ARE YOU?',2,6);

Output:

Exp 6: To implement various types of joins and sub queries.


In relational database management system, data stored in different tables is related. We can use the SQL to relate the information and query data. The SELECT statement has
ISHA AGGARWAL (80805107023)

Database Management System

42

mandatory SELECT clause and FROM clause. The SELECT clause can have a list of columns, expressions, functions, and so on. The FROM clause tells us which table(s) to look in for the required information. With the help of joins we can retrieve data from more than one table and relate various tables with each other. Rows in one table can be joined to rows in another table according to common values existing in corresponding columns. There are various types of joins: Cross join Inner join Left outer join Right outer join Full outer join

Cross join: - It is also known as Cartesian join. In cross join there is no


condition specified in WHERE clause and data is selected from two or more tables

Query 1:Solution:
ISHA AGGARWAL (80805107023)

Database Management System


Output: Query 1:Solution: Output: Query 1:Solution: Output: Query 1:Solution: Output: Query 1:Solution: Output: Query 1:Solution: Output: Query 1:Solution: Output:

43

create table customer ( c_id int primary key, c_name varchar(30), loan_id int references loan_(l_id) on delete cascade );

ISHA AGGARWAL (80805107023)

Database Management System


insert insert insert insert into into into into customer customer customer customer values(1,'ram',101); values(2,'sham',102); values(3,'amar',103); values(4,'amy',101);

44

select * from customer;

create table loan_ ( l_id int primary key, l_type varchar(30) ); insert into loan_ values(101,'car'); insert into loan_ values(102,'home'); insert into loan_ values(103,'education'); select * from loan_;

create table bank ( b_id int primary key, loaction varchar(30), c_id int references customer(c_id) on delete cascade ); insert insert insert insert into into into into bank bank bank bank values(1,'patiala',1); values(2,'sirhind',2); values(3,'amritsar',3); values(4,'ludhiana',1);

select * from bank;

ISHA AGGARWAL (80805107023)

Database Management System

45

select * from customer cross join loan_;

select * from customer inner join loan_ on loan_id=l_id;

select * from customer inner join loan_ on loan_id=l_id and c_name='sham';

select * from customer c left outer join bank b on c.c_id=b.c_id;

select * from customer c right outer join loan_ l on c.loan_id=l.l_id;

ISHA AGGARWAL (80805107023)

Database Management System

46

ISHA AGGARWAL (80805107023)

Vous aimerez peut-être aussi