Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Dbms 1

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 28

INTRODUCTION TO SQL: SQL (Structured Query Language) is a database computer language designed for the retrieval and management

of data in relational database management systems (RDBMS), database schema creation and modification, and database object access control management. SQL is structure query language.SQL contains different data types those are 1. 2. 3. 4. char(size) varchar2(size) date number(p,s) long

5.

BASIC STRUCTURE OF SQL: SELECT <attribute list and function list> FROM <table list> [WHERE <condition>] [GROUP BY <grouping attributes>] [HAVING <grouping condition>] [ORDER BY <attribute list>]; ORDER OF EVALUATION: 1.FROM:I t will perform the cross product among the specified tables. 2.WHERE:The conditions which are specified in WHERE clause are applied on the cross product of the tables. 3.SELECT:It will select the required attributes from the result of the WHERE clause. 4.GROUP BY:It will group the rows from the result of SELECT clause based on specified attributes in the GROUP BY clause. 5.HAVING:It will apply the specified condition over the result of group by clause. 6.ORDER BY:IT will sort the result of having clause based on specified attribute in the ORDER BY clause. SELECT:retrieve data from the database FROM :it is used to specify the list of tables. WHERE:it is a optional statement and it is used to specify the condition. GROUP BY:the group by clause specifies the grouping attributes . HAVING:it is used to specify the conditions over the groups given by group by clause. ORDER BY: It is used to display the result in the sorted order

based on specified attribute in the order by clause. Different types of commands in SQL: DDL Data Definition Language (DDL) statements are used to define the database structure or schema. DDL Commands: Create , Alter ,Drop , Rename, Truncate CREATE - to create objects in the database Syntax: Create table <table name> (<col1> <datatype>(<size>),<col2> <datatype><size>)); ALTER - alters the structure of the database Modifying the structure of tables. a)add new columns Syntax: Alter table <tablename> add(<new col><datatype(size),<new col>datatype(size)); Ex: alter table emp add(sal number(7,2)); Modifying existing columns. Syntax: Alter table <tablename> modify(<col><newdatatype>(<newsize>)); Ex:alter table emp modify(ename varchar2(15)); DROP - delete objects from the database Syntax: Drop table <tablename>; Ex:drop table emp; TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed truncating the tables. Syntax: Truncate table <tablename>; Ex:trunc table emp1; RENAME - rename an object or table

Renaming the tables Syntax: Rename <oldtable> to <new table>; Ex:rename emp to emp1; DML Data Manipulation Language (DML) statements are used for managing data within schema objects. DML Commands: Insert ,Update, Delete, Select

SELECT - retrieve data from the a database SYNTAX: SELECT column_name(s) FROM table_names; INSERT - insert data into a table

SYNTAX:INSERT INTO table_nameVALUES (value1, value2, value3,...);


( OR ) INSERT INTO table_name (column1, column2, column3,...)VALUES (value1, value2, value3,...); UPDATE - updates existing data within a table SYNTAX: UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value; DELETE - deletes all records from a table, the space for the records remain DELETE FROM table_name WHERE some_column=some_value; DCL Data Control Language (DCL) statements is used to create roles, permissions, and referential integrity as well it is used to control access to database by securing it. DCL Commands: Grant, Revoke

GRANT - gives user's access privileges to database Syntax: GRANT <object privileges> ON <objectname> TO<username>

[WITH GRANT OPTION]; REVOKE - withdraw access privileges given with the GRANT command Syntax: REVOKE<object privilege> ON FROM<user name>; TCL Transaction Control (TCL) statements are used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions. TCL Commands: Commit, Rollback, Save point

COMMIT - save work done SAVEPOINT - identify a point in a transaction to which you can later roll back ROLLBACK - restore database to original since the last COMMIT SQL Constraints Constraints are used to limit the type of data that can go into a table. Constraints can be specified when a table is created (with the CREATE TABLE statement) or after the table is created (with the ALTER TABLE statement). We will focus on the following constraints:

NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY CHECK DEFAULT

SQL NOT NULL Constraint The NOT NULL constraint enforces a column to NOT accept NULL values.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 following SQL enforces the "P_Id" column and the "LastName" column to not accept NULL values: CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) )

SQL UNIQUE Constraint The UNIQUE constraint uniquely identifies each record in a database table.The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it. Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table. CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), UNIQUE (P_Id) ) SQL PRIMARY KEY Constraint The PRIMARY KEY constraint uniquely identifies each record in a database table. Primary keys must contain unique values. A primary key column cannot contain NULL values. Each table should have a primary key, and each table can have only ONE primary key. CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), PRIMARY KEY (P_Id) ) SQL FOREIGN KEY Constraint A FOREIGN KEY in one table points to a PRIMARY KEY in another table. CREATE TABLE Orders ( O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int, PRIMARY KEY (O_Id), FOREIGN KEY (P_Id) REFERENCES Persons(P_Id) ) SQL CHECK Constraint The CHECK constraint is used to limit the value range that can be placed in a column. If you define a CHECK constraint on a single column it allows only certain values for this column.

If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row. CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CHECK (P_Id>0) ) SQL DEFAULT Constraint The DEFAULT constraint is used to insert a default value into a column. The default value will be added to all new records, if no other value is specified. CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) DEFAULT 'Sandnes' );

SQL Operators There are two type of Operators, namely Comparison Operators and Logical Operators. These operators are used mainly in the WHERE clause, HAVING clause to filter the data to be selected. Comparison Operators: Comparison operators are used to compare the column data with specific values in a condition. Comparison Operators are also used along with the SELECT statement to filter data based on specific conditions. The below table describes each comparison operator. Compariso n Description Operators = <>, != < > >= equal to is not equal to less than greater than greater than or equal to

<=

less than or equal to

SQL Logical Operators There are three Logical Operators namely, AND, OR, and NOT. These operators compare two conditions at a time to determine whether a row can be selected for the output. When retrieving data using a SELECT statement, you can use logical operators in the WHERE clause, which allows you to combine more than one condition. Logical Operators OR Description For the row to be selected at least one of the conditions must be true. For a row to be selected all the specified conditions must be true. For a row to be selected the specified condition must be false.

AND

NOT

"OR" Logical Operator: If you want to select rows that satisfy at least one of the given conditions, you can use the logical operator, OR. For example: if you want to find the names of students who are studying either Maths or Science, the query would be like, SELECT first_name, last_name, subject FROM student_details WHERE subject = 'Maths' OR subject = 'Science' The output would be something like, first_name last_name subject ------------Anajali Shekar Rahul Stephen ------------Bhagwat Gowda Sharma Fleming ---------Maths Maths Science Science

The following table describes how logical "OR" operator selects a row. Column1 Satisfied? YES YES NO Column2 Satisfied? YES NO YES Row Selected YES YES YES

NO

NO

NO

"AND" Logical Operator: If you want to select rows that must satisfy all the given conditions, you can use the logical operator, AND. For Example: To find the names of the students between the age 10 to 15 years, the query would be like: SELECT first_name, last_name, age FROM student_details WHERE age >= 10 AND age <= 15; The output would be something like, first_name last_name age ------------Rahul Anajali Shekar ------------Sharma Bhagwat Gowda -----10 12 15

The following table describes how logical "AND" operator selects a row. Column1 Satisfied? YES YES NO NO Column2 Satisfied? YES NO YES NO Row Selected YES NO NO NO

"NOT" Logical Operator: If you want to find rows that do not satisfy a condition, you can use the logical operator, NOT. NOT results in the reverse of a condition. That is, if a condition is satisfied, then the row is not returned. For example: If you want to find out the names of the students who do not play football, the query would be like: SELECT first_name, last_name, games FROM student_details WHERE NOT games = 'Football' The output would be something like, first_nam last_nam e e games

--------------- ------------------------Rahul Sharma Cricket

Stephen Shekar Priya

Fleming Gowda Chandra

Cricket Badminto n Chess

The following table describes how logical "NOT" operator selects a row. Column1 Satisfied? YES NO NOT Column1 Satisfied? NO YES Row Selected NO YES

SQL Aggregate Functions SQL aggregate functions return a single value, calculated from values in a column. Useful aggregate functions:

AVG() - Returns the average value COUNT() - Returns the number of rows FIRST() - Returns the first value LAST() - Returns the last value MAX() - Returns the largest value MIN() - Returns the smallest value SUM() - Returns the sum

The AVG() Function The AVG() function returns the average value of a numeric column. SQL AVG() Syntax SELECT AVG(column_name) FROM table_name

SQL COUNT() Function SQL COUNT(column_name) Syntax The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column: SELECT COUNT(column_name) FROM table_name SQL COUNT(*) Syntax The COUNT(*) function returns the number of records in a table: SELECT COUNT(*) FROM table_name

name SQL COUNT(DISTINCT column_name) Syntax The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified column: SELECT COUNT(DISTINCT column_name) FROM table_name SQL COUNT(DISTINCT column_name) S The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified column: SELECT COUNT(DISTINCT column_n ame) FROM table_name

SQL MAX() Function The MAX() Function The MAX() function returns the largest value of the selected column. SQL MAX() Syntax SELECT MAX(column_name) FROM table_name

SQL MIN() Function The MIN() Function The MIN() function returns the smallest value of the selected column. SQL MIN() Syntax SELECT MIN(column_name) FROM table_name

SQL SUM() Function The SUM() Function The SUM() function returns the total sum of a numeric column. SQL SUM() Syntax SELECT SUM(column_name) FROM table_name

1.BASIC QUERIES ON DDL AND DML STATEMENT customer(customerid,fname,lname,area,phno) movie(mvno,title,type,actor,price)

invoice(invno,mvno,customerid,issuedate,returndate);
SQL>create table customer(customeridint,fnamevarchar(20),lnamevarchar(20),area varchar(20),phnoint,primary key(customerid));

SQL>insert into customer values(1,KP,RAO,TNL,8885370453); SQL>insert into customer values(2,MN,BABU,GNT,9849754961); SQL>insert into customer values(3,IVHY,VARMA,GNT,9949674717); SQL>insert into customer values(4,MP,KUMAR,NRKDR,7207207070); SQL>insert into customer values(5,PR,NAYAK,GNT,7777777777); SQL> select * from customer; CUSTOMERID FNAME LNAME AREA PHNO

---------------------------------------------------------------------------------------------1 2 3 4 5 KP MN IVHY MP PR RAO BABU VARMA KUMAR NAYAK TNL GNT GNT NRKDR GNT 8885370453 9849754961 9959674717 7207207070 7777777777

SQL>create table movie(mvnoint,titlevarchar(20),type varchar(20),actor varchar(20),price int,primary key(mvno)); SQL>insert into movie values(001,3IDOTS,INSPIRE,AMRKHAN,500); SQL>insert into movie values(002,DHOOM-2,ACTION,HRITIK,500); SQL>insert into movie values(003,DABAANG,COMEDY,SALMAN,600); SQL>insert into movie values(004,ROCKSTAR,DARK,RANBEER,400); SQL>insert into movie values(005,RA-ONE,ACTION,SHARUK,500); SQL> select * from movie; MVNO ----1 2 3 4 5 TITLE TYPE ACTOR PRICE

--------------- --------------- ------------------- -------------------3IDIOTS DHOOM-2 DABAANG ROCKSTAR RA-ONE INSPIRE ACTION COMEDY DARK ACTION AMRKHAN HRITIK SALMAN RANBEER SHARUK 500 500 600 400 500

SQL>create table invoice( invoice(invnoint,mvnoint,cutomeridint,issuedatevarchar(20),returndatevarchar(20),primar y key(invno,mvno,customerid)); SQL>insert into invoice values(01,001,1,5-JAN-2010,15-JAN-2010); SQL>insert into invoice values(02,002,2,15-JAN-2010,25-JAN-2010);

SQL>insert into invoice values(03,003,3,1-FEB-2011,10-FEB-2011); SQL>insert into invoice values(04,004,4,10-FEB-2011,20-FEB-2011); SQL>insert into invoice values(05,005,5,1-JAN-2012,10-JAN-2012); SQL> select * from invoice; INVNO MVNO CUSTOMERID ISSUEDATE RETURNDATE

------ ---------- -----------------1 2 3 4 5 1 2 3 4 5 1 2 3 4 5

--------------- -----------------5-JAN-2010 15-JAN-2010 1-FEB-2011 10-FEB-2011 1-JAN-2012 15-JAN-2010

25-JAN-2010 10-FEB-2011 20-FEB-2011 10-JAN-2012

1.TO DISPLAY THE INFORMATION ABOUT THE CUSTOMER? SQL> select * from customer; CUSTOMERID FNAME LNAME AREA PHNO

--------------------------------------------- ---------------------------------------------1 2 3 4 5 KP MN IVHY MP PR RAO BABU VARMA KUMAR NAYAK TNL GNT GNT NRKDR GNT 7171717171 6363636363 8282828282 7207207070 7777777777

2.TO DISPLAY THE FNAME,AREA OF THE CUSTOMER? SQL> select fname,area from customer; FNAME ----------KP MN IVHY MP PR AREA -----------TNL GNT GNT NRKDR GNT

3.FIND THE NAMES OF ALL CUSTOMERS HAVING 'A' AS THE SECOND LETTER IN THEIR FNAME? SQL> select fname from customer where fname like '_A%';

no rows selected

4.FIND LNAME OF CUSTOMER THAT END WITH 'I'? SQL> select lname from customer where lname like '%I'; no rows selected

5.FIND OUT THE CUSTOMERS WHO STAY IN GUNTUR OR TENALI? SQL> select fname,lname from customer where area='GNT' or area='TNL'; FNAME LNAME

------------------------KP MN IVHY PR RAO BABU VARMA NAYAK

7.DISPLAY THE DIFFERENT TYPES OF MOVIES AVALIBLE IN MOVIES TABLE? SQL> select distinct type from movie; TYPE --------------ACTION COMEDY INSPIRE DARK

6.DISPLAY THE INFORMATION OF MOVIES? SQL> select * from movie; MVNO TITLE TYPE ACTOR PRICE

------------------------------------------------------------------------------------1 2 3 4 5 3IDIOTS DHOOM-2 DABAANG ROCKSTAR RA-ONE INSPIRE ACTION COMEDY DARK ACTION AMRKHAN HRITIK SALMAN RANBEER SHARUK 500 500 600 400 500

8.DISPLAY THE NAMES OF THE CUSTOMERS WHO HAVE BEEN TAKES THE MOVIES IN FEBRUARY? SQL> select fname,lname from customer c,invoice i where c.customerid=i.customerid and i.issuedate like '%FEB%'; FNAME LNAME

--------------- --------------IVHY MP VARMA KUMAR

9.DISPLAY THE INVOICE INFORMATION FOR CUSTOMERID '1' AND '2'? SQL> select * from invoice where customerid=1 or customerid=2; INVNO MVNO CUSTOMERID ISSUEDATE RETURNDATE

---------- -------------------- ---------------------------1 2 1 2 1 5-JAN-2010 2 15-JAN-2010 15-JAN-2010 25-JAN-2010

10.DISPLAY THE MOVIE OF THE TYPE COMEDY AND ACTION? SQL> select title from movie where (type='ACTION' or type='COMEDY'); TITLE --------------DHOOM-2 DABAANG RA-ONE

11.FIND THE MOVIES WHOSE PRICE IS GREATER THAN 150 AND LESS THAN OR EQUAL TO 200? SQL> select title from movie where price>150 and price<=200; no rows selected

12.FIND THE MOVIES WHOSE PRICE IS GREATER THAN 150 AND ALSO FIND THE NEWCOST AS ORIGINALCOST*15? SQL> select title,(price*15) as newcost from movie where price>150; TITLE NEWCOST

--------------- ---------3IDIOTS DHOOM-2 7500 7500

DABAANG 9000

ROCKSTAR RA-ONE

6000 7500

13.LIST THE MOVIES IN SORTED ORDER? SQL> select title from movie order by title; TITLE --------------3IDIOTS DABAANG DHOOM-2 RA-ONE ROCKSTAR

14.DISPLAY THE MOVIES NAMES EXCEPT HORROR MOVIES? SQL> select title from movie where type<>'HORROR'; TITLE --------------3IDIOTS DHOOM-2 DABAANG ROCKSTAR RA-ONE

15.COUNT THE TOTAL NUMBERS OF CUSTOMERS? SQL> select count(customerid) from customer; COUNT(CUSTOMERID) ----------------5

16.CALCULATE TOTAL PRICE OF ALL MOVIES? SQL> select sum(price) from movie; SUM(PRICE) ---------2500

17.FIND THE AVERAGE PRICE OF ALL CUSTOMERS? SQL> select avg(price) from customer c,movie m,invoice i where c.customerid=i.customerid and i.mvno=m.mvno; AVG(PRICE) ---------500

18.DETERMINE THA MAXIMUM AND MINIMUM PRICE OF THE MOVIES AND RENAME THEM AS MAXIMUM AND MINIMUM? SQL> select max(price) as maximum,min(price) minimum from movie; MAXIMUM MINIMUM

---------- ---------600 400

19.COUNT THE NUMBER OF MOVIES WHOSE PRICE GREATER THAN OR EQUAL TO150? SQL> select count(title) from movie where price>=150; COUNT(TITLE) -----------5

20.LIST THE NAME OF ALL CUSTOMERS WITH OUT LNAME? SQL> select lname from customer where lname is null; no rows selected

QUERIES ON SQL STRUCTURE(select,from,where,group by,having,order by) NESTED QUERIES sailors(sid,sname,rating,age) boats(bid,bname,color) reserves(sid,bid,day) SQL>Create table sailors(sid int,sname varchar(20),rating int,age int,primary key(sid)); SQL>insert into sailors values(101,KPR,10,19); SQL>insert into sailors values(102,MNB,7,19); SQL>insert into sailors values(103,IVHYV,8,20); SQL>insert into sailors values(104,PS,8,20); SQL>insert into sailors values(105,AVS,9,17);

1.DISPLAY INFORMATION ABOUT THE SAILORS? SQL> select * from sailors; SID SNAME RATING AGE

-------- -------------------- ---------- -------------------101 102 103 104 105 KPR MNB IVHYV PS AVS 10 7 8 8 9 19 19 20 20 17

SQL>create table boats(bid int,bname varchar(20),colour varchar(20),primary key(bid)); SQL>insert into boats values(201,KP,RED); SQL>insert into boats values(202,MN,PINK); SQL>insert into boats values(203,IVHYV,GRAY); SQL>insert into boats values(204,SOWSEEL,PURPLE); SQL>insert into boats values(205,CHARI,YELLOW);

2.DISPLAY THE INFORMATION ABOUT THE BOATS? SQL> select * from boats; BID BNAME COLOUR

---------- ---------------------------------201 202 203 204 205 KP MN IVHY SOWSEEL CHARI red pink GRAY PURPLE YELLOW

SQL>create table resrves(sid int,bid int,day varchar(20),primary key(sid,bid,day),foreign key(sid) references sailors(sid),foreign key(bid) references boats(bid)); SQL>insert into resrves values(101,201,SUNDAY); SQL>insert into resrves values(102,202,MONDAY); SQL>insert into resrves values(103,203,TUESDAY); SQL>insert into resrves values(104,204,WEDNESDAY); SQL>insert into resrves values(105,205,THURSDAY);

3. DISPLAY INFORMATION ABOUT THE RESERVES? SQL> select * from resrves; SID BID DAY

---------- ---------- -------------------101 102 103 104 201 SUNDAY 202 MONDAY 203 TUESDAY 204 WEDNESDAY

105 205 THURSDAY

4.FIND NAME AND AGE OF ALL SAILORS? SQL> select sname,age from sailors; SNAME AGE

-------------------- ---------KPR MNB IVHYV PS AVS 19 19 20 20 17

5.FIND ALL SAILORS WITH RATING IS GREATER THAN '7'? SQL> select sname from sailors where rating>7; SNAME -------------------KPR IVHYV PS AVS

6.FIND NUMBER OF SAILORS WHO HAS RESERVED BOAT NO.203? SQL> select count(*) from sailors s,resrves r where s.sid=r.sid and r.bid=203; COUNT(*) ---------1

(OR) SQL> select count(*) from resrves where bid=203; COUNT(*) --------1

7.FIND SID'S OF SAILORS WHO HAVE RESERVED A RED BOAT? SQL> select sid from resrves r,boats b where r.bid=b.bid and colour='red'; SID ---------101

8.FIND COLORS OF BOATS RESERVED BY 'RAMESH'? SQL> select colour from boats b,resrves r,sailors s where r.sid=s.sid and b.bid=r.bid and sname='RAMESH'; no rows selected

9.FIND SNAMES OF SAILORS WHO RESERVED ATLEAST ONE BOAT? SQL> select sname from sailors s,resrves r where s.sid=r.sid; SNAME -------------------KPR MNB IVHYV PS AVS

10.FIND THE NAME OF SAILORS WHO HAVE RESERVED RED BOAT OR GREEN BOAT? SQL> select sname from sailors s,resrves r,boats b where s.sid=r.sid and r.bid=b.bid and (b.colour='red' or b.colour='GREEN'); SNAME -------------------KPR

11.FIND THE NAME OF SAILORS WHO HAVE RESERVSED RED BOAT AND GREEN BOAT? SQL> select sname from sailors s,resrves r,boats b where s.sid=r.sid and r.bid=b.bid and (b.colour='red' and b.colour='GREEN'); no rows selected

12.FIND THE NAME OF SAILORS WHO HAVE RESERVSED RED BOAT BUT NOT GREEN BOAT? SQL> select sname from sailors s,resrves r,boats b where s.sid=r.sid and r.bid=b.bid and (b.colour='red' and b.colour<>'GREEN'); SNAME -------------------KPR

13.FIND THE AGES OF ALL SAILORS WHOSE NAMES BEGIN AND ENDS WITH 'B' AND HAS ATLEAST THREE CHARACTERS? SQL> select age from sailors where sname like 'B_%B'; no rows selected

14.FIND ALL SID'S OF SAILORS WHO HAVE RATING OF 10 OR RESERVES AS BOAT NO:204?

SQL> select s.sid from sailors s,resrves r where s.rating=10 and r.bid=204; SID ---------101

15.FIND THE NAMES OF SAILORS WHO HAVE RESERVED A RED BOAT? SQL> select sname from sailors s,resrves r,boats b where s.sid=r.sid and r.bid=b.bid and b.colour='red'; SNAME -------------------KPR

16.FIND THE SAILORS WHOSE RATING IS BETTER THAN SOME SAILOR CALLED 'RAMESH'? SQL> select sname from sailors s where s.rating > any (select s1.rating from sailors s1 where s1.sname='RAMESH'); no rows selected SQL> select sname from sailors s where s.rating > any (select s1.rating from sailors s1 where s1.sname='IVHYV'); SNAME -------------------KPR AVS

17.FIND THE SAILORS WHOSE RATING IS BETTER THAN EVERY SAILOR CALLED 'RAMESH'? SQL> select sname from sailors s where s.rating > all(select s1.rating from sailors s1 where s1.sname='RAMESH'); SNAME -------------------KPR MNB IVHYV PS AVS

18.FIND SAILORS WITH HIGHEST RATING? SQL> select sname from sailors s where rating in(select max(rating) from sailors); SNAME -------------------KPR

19.FIND AVERAGE AGE OF ALL SAILORS? SQL> select avg(age) from sailors; AVG(AGE) ---------19

20.FIND THE AVERAGE AGE OF SAILORS WITH RATING 10? SQL> select avg(age) from sailors where rating=10; AVG(AGE) ---------19

21.FIND SNAME,AGE OF OLDEST SAILORS? SQL> select sname,age from sailors where age in(select max(age) from sailors); SNAME AGE

-------------------- ---------IVHYV 20

PS

20

22.COUNT THE NUMBER OF SAILORS? SQL> select count(*) from sailors; COUNT(*) ---------5

23.COUNT THE NUMBER OF DIFFERENT SAILORS NAMES? SQL> select count(distinct sname) from sailors; COUNT(DISTINCTSNAME) -------------------5

24.FIND THE NAMES OF SAILORS WHO ARE OLDER THAN THE OLDEST SAILORS WITH RATING OF 10? SQL> select sname from sailors where age >(select max(age) from sailors where rating=10); SNAME -------------------IVHYV PS

25.COUNT THE DIFFERENT COLORS OF BOATS? SQL> select count(distinct colour) from boats; COUNT(DISTINCTCOLOUR) --------------------5

26.COUNT THE NUMBER OF BOATS RESERVED PER DAY? SQL> select day,count(*) from resrves group by day; DAY COUNT(*)

-------------------- ---------TUESDAY THURSDAY SUNDAY MONDAY WEDNESDAY 1 1 1 1

27.COUNT THE NUMBER OF RESERVATIONS FOR EACH BOATS? SQL> select r.bid,count(*) from resrves r group by r.bid; BID COUNT(*) ------205 201 202 203 204 ---------1 1 1 1 1

28.FIND AVERAGE AGE OF SAILORS FOR EACH RATING LEVEL? SQL> select s.rating,avg(age) from sailors s group by s.rating; RATING AVG(AGE) ---------- ---------8 7 10 9 20 19 19 17

29.FIND AVERAGE AGE OF SAILORS FOR EACH RATING LEVEL THAT HAS TWO SAILORS ATLEAST 2 SAILORS? SQL> select s.rating,avg(age) from sailors s group by s.rating having count(*)>=2; RATING AVG(AGE) ---------- ---------8 20

30.FOR EACH RED BOAT FIND THE NUMBER RESERVATIONS FOR THIS BOAT? SQL> select count(*) from resrves r,boats b where r.bid=b.bid and colour='RED'; COUNT(*) ---------1

31.DISPLAY THE NAMES OF THE DAY IN THAT DAY TWO BOATS ARE RESERVED? SQL> select r.day,count(*) from resrves r group by r.day having count(*)>=2; no rows selected

32.FIND THE AGE OF YOUNGEST SAILOR WHO IS ELIGIBLE TO VOTE FOR EACH RATING LEVEL WITH ATLEAST TWO SUCH SAILORS? SQL> select s.rating,min(age) from sailors s where age>18 group by s.rating having count(*)>2; no rows selected

Views A view may be thought of as a virtual table, that is, a table that does not really exist in its own right but is instead derived from one or more underlying base table. In other words, there is no stored file that direct represents the view instead a definition of view is stored in data dictionary. Growth and restructuring of base tables is not reflected in views. Thus the view can insulate users from the effects of restructuring and growth in the database. Hence accounts for logical data independence. SQL CREATE VIEW Statement In SQL, a view is a virtual table based on the result-set of an SQL statement. A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database. You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from one single table. SQL CREATE VIEW Syntax CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition SQL Updating a View You can update a view by using the following syntax: SQL CREATE OR REPLACE VIEW Syntax CREATE OR REPLACE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition SQL Dropping a View You can delete a view with the DROP VIEW command. SQL DROP VIEW Syntax DROP VIEW view_name;

QUERIES ON VIEWS student(sid,sname,login,gpa)

SQL>create table student(sid number,sname varchar(20),login varchar(20),age number,gpa number); SQL>insert into student values(11,KPR,KPR@gmail.com,19,8); SQL> insert into student values(12,MNB,MNB@gmail.com,19,8); SQL> insert into student values(13,AVS,AVS@gmail.com,18,8); SQL> insert into student values(14,MPK,MPK@gmail.com,19,7); SQL> insert into student values(15,IVHYV,IVHYV@gmail.com,20,6); SQL> select * from student; SID SNAME LOGIN AGE GPA

---------- ---------------------------------------- ---------- ------11 KPR 12 MNB 13AVS 14MPK 15 IVHYV KPR@gmail.com MNB@gmail.com AVS@gmail.com MPK@gmail.com IVHYV@gmail.com 19 19 18 19 20 9 8 8 7 6

1.CREATE A VIEW OF GOODSTUDENTS WITH ATTRIBUTES SID,GPA WHOSE GPA(GREAT POINT AVERAGE) IS >7. SQL> create view goodstudents as select sid,gpa from student where gpa>7; View created.

2.DISPLAY INFORMATION ABOUT GOODSTUDENTS? SQL> select * from goodstudents; SID GPA

---------- ---------11 12 13 9 8 8

3.DISPLAY AVERAGE GPA OF GOODSTUDENTS? SQL> select avg(gpa) from goodstudents;

AVG(GPA) --------------8.33333333

4.INSERT A ROW INTO THE VIEW GOODSTUDENTS? SQL> insert into goodstudents values(16,8.5); 1 row created.

5.DISPLAY INFORMATION ABOUT GOODSTUDENTS AFTER INSERTING? SQL> select * from goodstudents order by sid;

SID

GPA

---------- ---------11 12 13 16 9 8 8 8.5

6.DISPLAY INFORMATION ABOUT STUDENT TABLE AFTER INSERTING? SQL>select * from student; SID SNAME ---------- -------------11 KPR 12 MNB 13 AVS 14 MPK 15 IVHYV 16 LOGIN AGE GPA

-------------------------- --------- ---------KPR@gmail.com MNB@gmail.com AVS@gmail.com MPK@gmail.com IVHYV@gmail.com 8.5 19 19 18 19 20 9 8 8 7 6

7.UPDATE THE VIEW GOODSTUDENTS? SQL> update goodstudents set gpa=8 where sid=16; 1 row updated.

8.DISPLAY INFORMATION ABOUT GOODSTUDENTS AFTER UPDATING? SQL> select * from goodstudents; SID GPA

---------- ---------11 9

12 13 16

8 8 8

9.DISPLAY INFORMATION ABOUT STUDENT TABLE AFTER UPDATING?

SQL> select * from student ; SID SNAME LOGIN AGE GPA

---------- -------------------- -------------------- ---------- ---------11 KPR 12 MNB 13 AVS 14 MPK 15 IVHYV 16 KPR@gmail.com MNB@gmail.com AVS@gmail.com MPK@gmail.com IVHYV@gmail.com 19 19 18 19 20 8 9 8 8 7 6

10.DELETE THE ELEMENTS OF THE VIEW? SQL> delete student where gpa=8; 3 rows deleted.

11.DISPLAY THE INFORMATION ABOUT GOODSTUDENTS AFTER DELETING? SQL> select * from goodstudents;

SID

GPA

---------- ---------11 9

12.DISPLAY THE INFORMATION ABOUT STUDENT AFTER DELETING? SQL> select * from student; SID SNAME LOGIN AGE GPA

---------- -------------------- -------------------- ---------- ---------11 KPR 14 MPK 15 IVHYV KPR@gmail.com MPK@gmail.com IVHYV@gmail.com 19 19 20 9 7 6

13.CREATE THE VIEW OF STUDENT1 WITH ATTRIBUTES (STUDENTID,LOGINNAME,AGEOF THESTUDENT) FOR STUDENTS WHOSE AGE>17? SQL> create view student1(studentid,loginname,ageofstudent) as select sid,login,age from student where age>17; View created.

14.DISPLAY INFORMATION ABOUT VIEW STUDENT1? SQL> select * from student1;

STUDENTID LOGINNAME

AGEOFSTUDENT

----------------- ------------------------------------------------11 KPR@gmail.com 14 15 MPK@gmail.com IVHYV@gmail.com 19 19 20

15.DROP THE VIEW STUDENT1? SQL> drop view student1; View dropped.

You might also like