Advertisement
Guest User

Untitled

a guest
Dec 3rd, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 90.91 KB | None | 0 0
  1.  
  2. SCHOOL OF COMPUTING AND INFORMATION
  3. TECHNOLOGY
  4. DATABASE APPLICATIONS LABORATORY
  5. BTCS14F5700
  6. for
  7. Fifth Semester
  8. B.Tech in Computer Science and Engineering
  9. (Prepared in May-2016)
  10. Name
  11. SRN
  12. Branch
  13. Semester
  14. Section
  15. Academic Year
  16. Database Applications Lab REVA University
  17. School of Computing and Information Technology Page 2
  18. INDEX
  19. SL. No Contents Page. no
  20. 1 Lab Objectives
  21. 3
  22. 2 Lab Outcomes
  23. 3
  24. 3 Lab Requirements
  25. 4
  26. 4 Guidelines to Students
  27. 5
  28. 5 Introduction to Database, oracle & SQL
  29. 6
  30. 6 List of Lab Exercises 20
  31. 7 Solutions for Lab Exercises 23
  32. 8 Lab Assignment Exercises
  33. 59
  34. 9 Solutions for Lab Assignment Exercise I: 60
  35. 10 Viva Voce Questions
  36. 66
  37. Learning Resources and References 67
  38. Database Applications Lab REVA University
  39. School of Computing and Information Technology Page 3
  40. 1. Lab Objectives:
  41. The objectives of this course are to:
  42. 1. Provide hands on skills on creating a database.
  43. 2. Demonstrate different operations on database using SQL DML/DDL commands.
  44. 3. Identify and illustrate various clauses for different queries.
  45. 4. Generate reports as per user requirements
  46. 5. Develop industry standard database applications for various domains.
  47. 2. Lab Outcomes:
  48. On successful completion of this course; student shall be able to:
  49. 1. Design and implement a database schema.
  50. 2. Use appropriate SQL commands for designing queries
  51. 3. Design and build a GUI application using a front end tool
  52. 4. Design and develop applications like banking, reservation system, etc
  53. Database Applications Lab REVA University
  54. School of Computing and Information Technology Page 4
  55. 3. Lab Requirements
  56. Following are the required hardware and software for this lab, which is available in the
  57. laboratory.
  58. • Hardware: Desktop system or Virtual machine in a cloud with OS installed. Presently
  59. in the Lab, Pentium IV Processor having 1 GB RAM and 250 GB Hard Disk is available.
  60. Desktop systems are dual boot having Windows as well as Linux OS installed on them.
  61. • Software: The DBMS packages that fall in this category are as follows:
  62. o Oracle ( follows 7 rules )
  63. o DB2 ( follows 9 rules )
  64. o Ingress ( follows 10 rules )
  65. o Sybase ( follows 9 rules )
  66. Log Into Oracle
  67. Microsoft Windows
  68. Under Windows environment, the Oracle client is called SQL*Plus.The following are Steps for
  69. logging into the SQL.
  70. Steps: 1. Click Start, and then click Run.
  71. 2. Type sqlplus, and fill in the username, password, and database name
  72. 3. After you log in to SQL*Plus, you see the following message:
  73. Connected to: Oracle10g Enterprise Edition Release 9.1.7.0.0 - Production
  74. JServer Release 9.1.7.0.0 – Production and you should receive the prompt:
  75. Creating user: Create user <yourName> identified by <Password>;
  76. Where <yourName> is again your login name, and <Password> is the password you would like
  77. to use in the future. This command, like all other SQL commands, should be terminated with a
  78. semicolon.
  79. Changing Your Password : In response to the SQL> prompt, type
  80. Alter user <username> identified by <Password>;
  81. where <username> is again your login name, and <Password> is the password you would like
  82. to use in the future. This command, like all other SQL commands, should be terminated with a
  83. semicolon.
  84. Database Applications Lab REVA University
  85. School of Computing and Information Technology Page 5
  86. 4. Guidelines to Students
  87.  Equipment in the lab for the use of student community. Students need to
  88. maintain a proper decorum in the computer lab. Students must use the
  89. equipment with care. Any damage is caused is punishable.
  90.  Students are required to carry their observation / programs book with
  91. completed exercises while entering the lab.
  92.  Students are supposed to occupy the machines allotted to them and are not
  93. supposed to talk or make noise in the lab. The allocation is put up on the lab
  94. notice board.
  95.  Lab can be used in free time / lunch hours by the students who need to use
  96. the systems should take prior permission from the lab in-charge.
  97.  Lab records need to be submitted on or before date of submission.
  98.  Students are not supposed to use flash drives.
  99.  In C3 exam one Data base application will be asked and the set of some
  100. queries will be given in the final exam and evaluated for 50 marks and scale
  101. down to 25 marks.
  102. Database Applications Lab REVA University
  103. School of Computing and Information Technology Page 6
  104. 5. INTRODUCTION TO DATABASE, ORACLE AND SQL
  105. Database: -
  106. A group of tables with related data in them are called database.
  107. Database Management System: -
  108. DBMS consists of a collection of interrelated data and a set of programs to manage
  109. these data.
  110. Data Model:-
  111. Structure of database is defined by data model.
  112. Different data models are as follows:
  113. • Object Oriented model
  114. • Relational model
  115. • Network model
  116. • Hierarchical model
  117. Relational model:-
  118. • Relational model uses a collection of tables to represent both data and relationship
  119. among those tables.
  120. • Most database management systems are based on the relational model.
  121. • RDBMS follows codd’s rules.
  122. • There are 12 rules specified by E.F. Codd that must be satisfied by adatabase
  123. package for being an RDBMS.
  124. SQL * Plus
  125. SQL *Plus enables you to manipulate SQL commands and PL/SQL blocks, and to perform
  126. many additional tasks as well. Through SQL *Plus, you can
  127. • Enter, edit, store, retrieve, and SQL commands and PL/SQL blocks
  128. • Format, perform calculations on, store, and print query results in the form of reports
  129. • List column definitions for any table
  130. • Access and copy data between SQL databases
  131. • Send messages to and accept responses from an end user
  132. Database Applications Lab REVA University
  133. School of Computing and Information Technology Page 7
  134. Oracle Overview
  135. Oracle is one the most popular Relational Database Management System (RDBMS).
  136. Some other famous RDBMS includes Microsoft SQL Server, Sybase, MySQL, PostgreSQL, etc.
  137. Essentially, all the aforementioned RDBMS employs Structural Query Language (SQL) as
  138. their query interface. Users usually issue their queries by SQL through a "client". Different
  139. RDBMS offer different forms of clients. For example, MS SQL Server offers a GUI interface
  140. for user to type in their SQL language, and their queries would be executed after pressing
  141. the "Execute" button on the client. Oracle provides both GUI client and command-line
  142. client. In this lesson, we will study the command-line client, SQL*Plus. In addition, Oracle
  143. extends the standard SQL (e.g. select * from table) with its application-specific commands
  144. (e.g. checking how many table you have been created in your Oracle account) into a Oracle
  145. specific language called PL/SQL. In this tutorial, you will interact with Oracle database, thru
  146. SQL*Plus, by issuing a number of PL/SQL queries.
  147. SQL Basics
  148. Structured Query Language (SQL), which is an ANSI standard language for interacting with
  149. relational databases, is the main tool for extracting the information.
  150. A database is a representation of a real-world thing called an Entity. Examples of entities
  151. are vehicles, employees, customers, fish, buildings, and even things such as baseball teams.
  152. The database stores facts about the entity in an organized framework, model, or schema.
  153. These facts are called attributes.
  154. An Instance is one occurrence of an entity.
  155. Each entity must have an identifier, which is one or more attributes that make each entity
  156. instance unique from any other instance. The identifier should contain a value that does not
  157. change.
  158. Examples of identifiers are student IDs, payroll numbers, or social security numbers.
  159. Primary key :- If the entity does not have an attribute that can be used as an identifier, an
  160. artificial identifier can be created. The identifier on an entity is often called a primary key.
  161. Foreign key :- A foreign key is a set of attributes of the considered table that exists as a
  162. primary key attributes in another table. Database records are matched (joined) through the
  163. use of primary and foreign keys.
  164. Database Applications Lab REVA University
  165. School of Computing and Information Technology Page 8
  166. Normalization:- Normalization is a process consisting of series of steps, which is used to
  167. group the database attributes. The purpose of this design is to ensure that the tables within
  168. the database are space efficient and performance efficient.
  169. • Zero Normal Form: Each of the relations (tables) has a unique identifier (primary
  170. key).
  171. • First Normal Form: Separate the repeating groups of attributes or multi valued
  172. attributes into a relation of their own. Be sure to form composite keys.
  173. • Second Normal Form: Establish full functional dependency by separating out
  174. attributes that are not fully dependent on the full primary keys.
  175. • Third Normal Form: Remove transitive dependencies by separating attributes that
  176. are dependent on a non key attribute.
  177. How SQL works
  178. The purpose of SQL is to interface to a relational database such as Oracle, and all SQL
  179. statements are instructions to the databases.
  180. SQL provides commands for a variety of tasks including:
  181. • Querying data
  182. • Inserting, updating, and deleting rows in a table
  183. • Creating, replacing, altering, and dropping objects
  184. • Controlling access to the database and its objects
  185. • Guaranteeing database consistency and integrity
  186. Data Types
  187. Each literal or column value manipulated by Oracle has a data type. A value’s data
  188. type associates a fixed set of properties with the value. These properties cause Oracle to
  189. treat values of one data types differently values of another.
  190. Character Data types:- Character data types are used to manipulate words and freeform
  191. text. These data types are used to store character. These data types are used for character
  192. data:
  193. • CHAR:- The CHAR data type specifies a fixed length character is 1 character and
  194. maximum allowed is 2000 character.
  195. • NCHAR:- The NCHAR data types specifies a fixed-length national character set
  196. character string. The maximum column size allowed is 2000 bytes.
  197. • NVARCHAR2:- The NVARCHAR2 data type specifies variable-length national
  198. character string. The maximum column size allowed is 4000 bytes.
  199. • VARCHAR2:- The VARCHAR2 data type specifies a variable length character string.
  200. The maximum length of VARCHAR2 data is 4000 bytes.
  201. Database Applications Lab REVA University
  202. School of Computing and Information Technology Page 9
  203. Number Datatypes:- The NUMBER data type is used to store zero, positive and negative
  204. fixed and floating point numbers with magnitudes
  205. Floating Point Numbers:- A floating point value either can have a decimal point anywhere
  206. from the first to the last digit or can omit the decimal point altogether.
  207. Long Datatype:- LONG columns store variable length variable length character strings
  208. containing up to 2 gigabytes, or 231 -1 bytes. LONG data type is subject to some restrictions
  209. which are:
  210. • A table cannot contain more than one LONG column.
  211. • LONG columns cannot appear in integrity constraints
  212. • LONG columns cannot be indexed.
  213. Also, LONG columns cannot appear in certain parts of SQL statements:
  214. • WHERE, GROUP BY, or CONNECT BY clause or with the DISTINCT operator in SELECT
  215. statements
  216. • UNIQUE clause of a SELECT statement
  217. • Select list of queries containing GROUP BY clauses
  218. • Select list of sub queries or queries combined by set operators
  219. DATE Data type:- The DATE data types is used to store date and time information.
  220. Operators:- All the normal Arithmetic, Relational, Logical operators are used in SQL.
  221. SQL Commands:- In order to define schemas, store data, retrieve data and to make
  222. amendments in schema and data stored in the database different types of commands are
  223. used which are:
  224. • Data Definition Language Commands.(DDL)
  225. • Data Manipulation Language Commands(DML)
  226. • Transaction Control Commands(TCL)
  227. • Session Control Commands(SCL)
  228. • System Control Commands(SCC)
  229. Data Definition Language (DDL) commands allow you to perform these tasks:
  230. • Create, Alter, and Drop schema objects(CAD)
  231. • Grant and Revoke privileges and roles
  232. • Analyses information on a table, index, or cluster
  233. • Establish auditing options
  234. • Add comments to the data dictionary
  235. Database Applications Lab REVA University
  236. School of Computing and Information Technology Page 10
  237. Create Table Command: - It defines each column of the table uniquely. Each column has
  238. minimum of three attributes, a name , data type and size.
  239. Syntax: Create table <table name> (<col1> <datatype>(<size>),<col2> <datatype><size>));
  240. Ex: Create table emp(empno number(4) primary key, ename char(10));
  241. Modifying the structure of tables
  242. a) Add new columns
  243. Syntax: Alter table <tablename> add(<new col><datatype(size),<new
  244. col>datatype(size));
  245. Ex: Alter table emp add(sal number(7,2));
  246. b) Dropping a column from a table.
  247. Syntax: Alter table <tablename> drop column <col>;
  248. Ex: alter table emp drop column sal;
  249. c) Modifying existing columns.
  250. Syntax: Alter table <tablename> modify(<col><newdatatype>(<newsize>));
  251. Ex: Alter table emp modify(ename varchar2(15));
  252. d)Renaming the tables
  253. Syntax: Rename <oldtable> to <new table>;
  254. Ex: rename emp to emp1;
  255. Truncating the tables
  256. Syntax: Truncate table <tablename>;
  257. Ex: trunc table emp1;
  258. Destroying tables.
  259. Syntax: Drop table <tablename>;
  260. Ex: drop table emp;
  261. Data Manipulation Language (DML) commands query and manipulate data in existing
  262. schema objects. These commands do not implicitly commit the current transaction.
  263. Database Applications Lab REVA University
  264. School of Computing and Information Technology Page 11
  265. Following are the commands:
  266. 1. Select
  267. 2. Insert
  268. 3. Delete
  269. 4. Update
  270. 5. Lock table
  271. 6. Explain Plan
  272. Inserting Data into Tables: - once a table is created the most natural thing to do is load this
  273. table with data to be manipulated later.
  274. Syntax: insert into <tablename> (<col1>,<col2>) values(<exp>,<exp>);
  275. Delete operations:-
  276. a) remove all rows
  277. Syntax: delete from <tablename>;
  278. b) removal of a specified row/s
  279. Syntax: delete from <tablename> where <condition>;
  280. Updating the contents of a table.
  281. a) updating all rows
  282. Syntax: Update <tablename> set <col>=<exp>,<col>=<exp>;
  283. b) updating selected records.
  284. Syntax: Update <tablename> set <col>=<exp>,<col>=<exp> where
  285. <condition>;
  286. Types of data constrains.
  287. a) not null constraint at column level.
  288. Syntax:<col><datatype>(size)not null
  289. b) unique constraint
  290. Syntax: Unique constraint at column level.<col><datatype>(size)unique;
  291. Database Applications Lab REVA University
  292. School of Computing and Information Technology Page 12
  293. c) unique constraint at table level:
  294. Syntax:Create table
  295. tablename(col=format,col=format,unique(<col1>,<col2>);
  296. d) primary key constraint at column level
  297. Syntax:<col><datatype>(size)primary key;
  298. e) primary key constraint at table level.
  299. Syntax:Create table tablename(col=format,col=format primary
  300. key(col1>,<col2>);
  301. f) foreign key constraint at column level.
  302. Syntax:<col><datatype>(size>) references <tablename>[<col>];
  303. g) foreign key constraint at table level.
  304. Syntax:foreign key(<col>[,<col>])references <tablename>[(<col>,<col>)
  305. h) check constraint
  306. i)check constraint constraint at column level.
  307. Syntax: <col><datatype>(size) check(<logical expression>)
  308. ii) check constraint constraint at table level.
  309. Syntax: check(<logical expression>)
  310. Transaction Control Commands manages change made by Data Manipulation Language
  311. commands. Following are the commands:
  312. 1. Commit
  313. 2. Rollback
  314. 3. Save point
  315. 4. Set Transaction
  316. Oracle provides extensive feature in order to safeguard information stored in its tables from
  317. unauthorized viewing and damage. The rights that allow the user of some or all oracle
  318. resources on the server are called privileges.
  319. Database Applications Lab REVA University
  320. School of Computing and Information Technology Page 13
  321. Grant privileges using the GRANT statement
  322. The grant statement provides various types of access to database objects such as tables,
  323. views and sequences and so on.
  324. Syntax: GRANT <object privileges> ON <objectname> TO <username>[WITH GRANT
  325. OPTION];
  326. Revoke permissions using the REVOKE statement:
  327. The REVOKE statement is used to deny the Grant given on an object.
  328. Syntax: REVOKE<object privilege> ON FROM<user name>;
  329. Aggregate Function
  330. Aggregate functions return a single value based upon a set of other values. If used among
  331. many other expressions in the item list of a SELECT statement, the SELECT must have a
  332. GROUP BY clause. No GROUP BY clause is required if the aggregate function is the only value
  333. retrieved by the SELECT statement. The supported aggregate functions and their syntax are
  334. shown in following table.
  335. Usage of Aggregate Functions Function Name
  336. Computes the average value of a column by
  337. the expression
  338. Avg()
  339. Counts the rows defined by the expression Count()
  340. Counts all rows in the specified table or view Count all()
  341. Finds the minimum value in a column by the
  342. expression
  343. Min()
  344. Finds the maximum value in a column by the
  345. expression
  346. Max()
  347. Computes the sum of column values by the
  348. expression
  349. Sum()
  350. Syntax: Aggregate function name ( [ALL | DISTINCT] expression )
  351. The aggregate function name may be AVG, COUNT, MAX, MIN, or SUM. The ALL
  352. clause, which is the default behavior and does not actually need to be specified, evaluates
  353. all rows when aggregating the value of the function. The DISTINCT clause uses only distinct
  354. values when evaluating the function.
  355. Database Applications Lab REVA University
  356. School of Computing and Information Technology Page 14
  357. AVG and SUM
  358. The AVG function computes the average of values in a column or an expression. SUM
  359. computes the sum. Both functions work with numeric values and ignore NULL values. They
  360. also can be used to compute the average or sum of all distinct values of a column or
  361. expression.
  362. AVG and SUM are supported by Microsoft SQL Server, MySQL, Oracle, and
  363. PostgreSQL.
  364. Explanation:- The following query computes average year-to-date sales for each type of
  365. book:
  366. SQL> SELECT type, AVG( ytd_sales ) AS "average_ytd_sales"
  367. FROM titles GROUP BY type;
  368. This query returns the sum of year-to-date sales for each type of book:
  369. SQL> SELECT type, SUM ( ytd_sales )
  370. FROM titles GROUP BY type;
  371. COUNT
  372. The COUNT function has three variations. COUNT (*) counts all the rows in the target
  373. table whether they include nulls or not. COUNT (expression) computes the number of rows
  374. with non-NULL values in a specific column or expression. COUNT (DISTINCT expression)
  375. computes the number of distinct non-NULL values in a column or expression.
  376. Explanation :- This query counts all rows in a table:
  377. SQL>SELECT COUNT (*) FROM publishers;
  378. The following query finds the number of different countries where publishers are located:
  379. SQL>SELECT COUNT (DISTINCT country) "Count of Countries" FROM publishers
  380. MIN and MAX
  381. MIN (expression) and MAX (expression) find the minimum and maximum value
  382. (string, date time, or numeric) in a set of rows. DISTINCT or ALL may be used with these
  383. functions, but they do not affect the result.
  384. Database Applications Lab REVA University
  385. School of Computing and Information Technology Page 15
  386. Explanation : The following query finds the best and worst sales for any title on record:
  387. SELECT 'MIN' = MIN(ytd_sales), 'MAX' = MAX(ytd_sales) FROM titles;
  388. Aggregate functions are used often in the having clause of queries with GROUP BY.
  389. The following query selects all categories (types) of books that have an average price for all
  390. books in the category higher than $15.00:
  391. SQL>SELECT type 'Category', AVG( price ) 'Average Price'
  392. FROM titles
  393. GROUP BY type
  394. HAVING AVG(price) > 15
  395. CONCATENATE
  396. SQL99 defines a concatenation operator ( || ), which joins two distinct strings into
  397. one string value. The CONCATENATE function appends two or more strings together,
  398. producing a single output string. Oracle support the double-pipe concatenation operator.
  399. Microsoft SQL Server uses the plus sign (+) concatenation operator.
  400. SQL> CONCATENATE ('string1' || 'string2')
  401. Practicing SQL Commands with examples:
  402. Creating Tables
  403. In SQL*Plus we can execute any SQL command. One simple type of command creates a
  404. table (relation). The form is
  405. CREATE TABLE <table Name> ( <list of attributes and their types> );
  406. You may enter text on one line or on several lines. If your command runs over several lines,
  407. you will be prompted with line numbers until you type the semicolon that ends any
  408. command. (Warning: An empty line terminates the command but does not execute it; see
  409. editing commands in the buffer.) An example table-creation command is:
  410. CREATE TABLE test ( i int, s char(10) );
  411. Note that SQL is case insensitive, so CREATE TABLE TEST and create table test are the same.
  412. This command creates a table named test with two attributes. The first attribute, named i, is
  413. an integer, and the second, named s, is a character string of length (up to) 10.
  414. Database Applications Lab REVA University
  415. School of Computing and Information Technology Page 16
  416. Exercise 1 : Create a relation Student that suitable for the following instance:
  417. SID NAME JOB SALARY STREAM START_AT
  418. 1 Ben Kao Associate Professor 7000 E 01-Sep-1995
  419. 2 Eric Lo Teaching Assistant 1000 E 01-Oct-2003
  420. 3 Hammer Lecturer 7000 E 11-Feb-2000
  421. 4 Angela
  422. Castro
  423. Program Manager 6000 I 12-Dec-1999
  424. 5 Steven Chu Project Assistant 7000 I 13-Dec-2002
  425. Note: No need to insert the data yet!
  426. Inserting Tuples
  427. Having created a table, we can insert tuples into it. The simplest way to insert is with the
  428. INSERT command:
  429. INSERT INTO <tableName> VALUES( <list of values for attributes, in order> );
  430. For instance, we can insert the tuple (10, 'hi world') into relation test by
  431. INSERT INTO test VALUES(10, 'hi world');
  432. Exercise 2: Insert the records as stated into Exercise 1 into the student table.
  433. Trick: Try to insert a record into test with the following SQL:
  434. INSERT INTO test VALUES (11, 'ha 'world');
  435. Updating Tuples
  436. Tuples can be updated by the UPDATE command:
  437. UPDATE <table Name> SET <Attribute>=<Expression/Value>
  438. WHERE <Predicate>;
  439. For example, we can update the tuple (10, 'hi world') in relation test by
  440. UPDATE test SET s='bye world' WHERE i=10;
  441. Database Applications Lab REVA University
  442. School of Computing and Information Technology Page 17
  443. Exercise 3: Update the record of 'Eric Lo' in relation Student such that his salary change to
  444. 1234
  445. Deleting Tuples
  446. Having insert / update a tuple, we can delete it as well. The simplest way to delete is with
  447. the DELETE command:
  448. DELETE FROM <table Name> [WHERE <condition>];
  449. <condition> is an optional statement and is used to identify a single record when necessary.
  450. For example, you can delete the record with i=10 in table test with the the following SQL:
  451. DELETE FROM test WHERE i=10;
  452. Exercise 4: Delete the record of 'Eric Lo' in relation Student.
  453. Trick: Does that record really deleted successfully? Let's check it out by using SELECT
  454. command (we will cover it in next section).
  455. Retrieving Tuples
  456. We can see the tuples in a relation with the command:
  457. SELECT <attributes-separated-by-comma> FROM <tableName>;
  458. For instance, after the above CREATE, INSERT DELETE and UPDATE statements, the
  459. command
  460. SELECT * FROM test;
  461. produces the result
  462. I S
  463. 11 ha 'world
  464. Exercise 5: Select ALL records from relation Student.
  465. Question: Do data values also case insensitive? i.e., can a student with name "Hammer" be
  466. retrieved by the following SQL or not?
  467. SeLec T name from StudenT where name ='hammer';
  468. Commit and Rollback
  469. Database Applications Lab REVA University
  470. School of Computing and Information Technology Page 18
  471. An automatic commit occurs under the following circumstance:
  472. • DDL statement is issued
  473. • Normal exit from SQL*Plus, without explicitly issuing COMMIT or ROLLBACK
  474. An automatic rollback occurs under an abnormal termination of SQL*Plus or a system
  475. failure.
  476. It provides a good back-door for you to revert the changes you have done on the data.
  477. Therefore, unless you have issued COMMIT, the changed data would not be visible to any
  478. other session except your own. Conversely, you can rollback all the changes by issuing the
  479. ROLLBACK command.
  480. Exercise 6: Issue the COMMIT command in the SQL*Plus that you have done
  481. insert/delete/update before, and see if the effect is now visible by the new SQL*Plus?
  482. Dropping Tables
  483. To remove a table from your database, execute
  484. DROP TABLE <table Name>;
  485. We suggest you execute
  486. DROP TABLE test;
  487. Caution: Table dropping is a DML statement, which is an action that you cannot rollback.
  488. Since dropping a table will also delete all data in that table, issue the DROP TABLE command
  489. with cares.
  490. Getting Information about Your Database
  491. The system keeps information about your own database in certain system tables. The most
  492. important for now is USER_TABLES. You can recall the names of your tables by issuing the
  493. query:
  494. SELECT TABLE_NAME
  495. FROM USER_TABLES;
  496. More information about your tables is available from USER_TABLES. To see all the attributes
  497. of USER_TABLES, try:
  498. SELECT * FROM USER_TABLES;
  499. It is also possible to recall the attributes of a table once you know its name. Issue the
  500. command:
  501. Database Applications Lab REVA University
  502. School of Computing and Information Technology Page 19
  503. DESCRIBE <tableName>;
  504. to view the schema of <tableName>;
  505. Data Types
  506. Here is part of the data types that are supported by Oracle.
  507. Data Type Description
  508. VARCHAR2
  509. (size)
  510. Variable-length character data (a maximum size must be specified: Minimum
  511. size is 1; maximum size is 4000)
  512. CHAR
  513. [(size)]
  514. Fixed-length character data of length size bytes (default and minimum size is 1;
  515. maximum size is 2000)
  516. NUMBER
  517. [(p,s)]
  518. Number having precision p and scale s (The precision is the total number of
  519. decimal digits, and the scale is the number of digits to the right of the decimal
  520. point; the precision can range from 1 to 38 and the scale can range from -84 to
  521. 127)
  522. DATE
  523. Date and time values to the nearest second between January 1, 4712 B.C., and
  524. December 31, 9999 A.D.
  525. Creating Tables with Keys
  526. To create a table that declares attribute a to be a primary key:
  527. CREATE TABLE <tableName> (..., a <type> PRIMARY KEY, b, ...);
  528. To create a table that declares the set of attributes (a,b,c) to be a primary key:
  529. CREATE TABLE <tableName> (<attrs and their types>, PRIMARY KEY (a,b,c));
  530. Database Applications Lab REVA University
  531. School of Computing and Information Technology Page 20
  532. 6. List of Lab Exercises
  533. SL.
  534. NO
  535. Name of the Program PAGE
  536. NO.
  537. I Product - Order System
  538. In recent years, most of the grocery items are available online; hence
  539. people are doing online transactions for purchase. There are lot of
  540. discounts and benefits through the online orders. Since everyone in the
  541. life is busy with one or other works, such applications will save their
  542. time.
  543. These online transaction based applications require many databases to
  544. be built for storage and transaction management. Design a productorder
  545. database which can store the details of customers, agents and the
  546. products. All the details of sold products along with commission from
  547. different agents across different cities will get stored in this database
  548. and utilized for transactions.
  549. Customer (cid, cname, city, discount)
  550. Agent (aid, aname, city, commission)
  551. Product (pid, pname, city, quantity, price)
  552. Orders (ordno, month, cid, aid, pid, qty, amount)
  553. Queries
  554. a. Retrieve the customer ids of any product which has been ordered by agent
  555. "a06".
  556. b. Retrieve cities in which customers or agents located.
  557. c. List product ids which have been ordered by agents from the cities
  558. “Dargeling” or “Srinagar”.
  559. d. Retrieve customer ids whose discounts are less than the maximum
  560. discount.
  561. e. Retrieve product ids ordered by at least two customers.
  562. f. For each (aid, pid) pair get the sum of the orders aid has placed for pid.
  563. g. Retrieve product ids and total quantity ordered for each product when the
  564. total exceeds 1000.
  565. h. List the names of the customers and agent who placed an order through
  566. that agent.
  567. i. Retrieve order numbers placed by customers in "Dargeling" through
  568. agents in "New Delhi".
  569. j. Retrieve names of the customers who have the same discount as that of
  570. any (one) of the customers in "Dargeling" or "Bangalore".
  571. k. Retrieve customer ids with smaller discounts than every customer from "
  572. Srinagar”
  573. l. Retrieve names of the customers who have placed an order through agent
  574. "a05". (using exists )
  575. m. Retrieve names of the customers who do not place orders through agent
  576. "a05". (using not exists)
  577. n. Retrieve customer ids whose orders placed through all the agents in "New
  578. Delhi".
  579. o. Retrieve agent ids either from "New Delhi" or "Srinagar" who place orders
  580. 24
  581. Database Applications Lab REVA University
  582. School of Computing and Information Technology Page 21
  583. for ALL products priced over one dollar.
  584. p. Retrieve names and ids of the customers and agents along with total dollar
  585. sales for that pair. Order the result from largest to smallest total sales. Also
  586. retain only those pairs for which total dollar sales is at least 9000.00.
  587. q. Increase the percent commission by 50% for all agents in "New York".
  588. r. Retrieve the total quantity that has been placed for each product.
  589. II Employee Database System
  590. The storage of digital data is increasing day by day. Every big / small
  591. organization started storing their employee details like name, salary, address,
  592. department under which they are working in their own database. Design a
  593. company database which can store the details of departments, projects, their
  594. employee and his / her dependent details of a particular organization
  595. Employee (ssn, name, salary, sex, super_ssn, address, dno)
  596. Department (dname, dnumber,mgr_ssn)
  597. Dept_Loc ( dnumber, dloc)
  598. Project (pname, pnumber, plocation, dnum)
  599. Works_On (essn, pno, hours)
  600. Dependent (essn, depen_name, address, relationship, sex)
  601. Queries
  602. a. Retrieve the names of the employees who works on all the projects
  603. controlled by dept no 3.
  604. b. Retrieve the names of the employees who gets second highest salary.
  605. c. Retrieve the names of the employees who have no dependents in
  606. alphabetical order.
  607. d. List the names of all employees with at least two dependents.
  608. e. Retrieve the number of employees and their average salary working in
  609. each department.
  610. f. Retrieve the highest salary paid in each department in descending order.
  611. g. Retrieve the SSN of all employees who work on atleast one of the project
  612. numbers 1, 2, 3.
  613. h. Retrieve the number of dependents for an employee named RAM.
  614. i. Retrieve the names of the managers working in location named xyz who
  615. has no female dependents.
  616. j. Retrieve the names of the employees who works in the same department
  617. as that of RAM.
  618. k. Retrieve the names of the employees whose salary is greater than the
  619. salary of all the employees working in department no 3.
  620. l. Retrieve the names of the employees who work for dept no 3 and have a
  621. daughter as dependent.
  622. m. Retrieve the names of the employees who paid highest salary from each
  623. department.
  624. n. Retrieve the names of the employees who are paid the same salary as that
  625. of Anil.
  626. 37
  627. Database Applications Lab REVA University
  628. School of Computing and Information Technology Page 22
  629. o. Retrieve the total the number of employees in the ‘Research’ department.
  630. p. For each project, retrieve the project number, the project name, and the
  631. number of employees who work on that project.
  632. III Car rental agency database systems
  633. The application that can be used for booking a vehicle online from
  634. his / her place is very much needed in mobile devices. The main aim of
  635. this system is to illustrate a database application for booking vehicles
  636. online. Design a car rental agency database which can store customer
  637. details, vehicle details like vehicle id, size, transmission and reservation
  638. details like who had booked from one date to other.
  639. Customers(cid, firstname, lastname, address)
  640. Vehicle(vid, mileage, location, vsize, transmission)
  641. Reservations(cid,vid, start_date, end_date)
  642. Note :
  643. ->Vehicle.transmission can have two values ‘manual’ and ‘automatic’.
  644. ->Vehicle.vsize can have following values. ‘compact’, ‘mid-size’, ‘fullsize’,
  645. ‘premium’ and ‘luxury’. The default size is compact.
  646. Queries
  647. a. Display both the first name and last name in uppercase as “Name of the
  648. customer “ as column name.
  649. b. Display vehicles size which is having maximum mileage.
  650. c. Find location and total mileage of all vehicles specific to each respective
  651. location.
  652. d. Find average mileage of vehicles for each location, which has at least
  653. five vehicles.
  654. e. Display the customer names whose reservation start date is before Feb
  655. 18th 2016.
  656. f. Display the vehicles which has been reserved between the dates Nov 5th
  657. 2015 and Jan 16th 2016.
  658. g. Display the names of the customers whose lastname starts with ‘D’ and
  659. who has reserved more vehicles than the customer with cid as '101'.
  660. h. Retrieve the customers who have reserved vehicles from all the locations.
  661. i. Retrieve the locations that have at least one vehicle with manual
  662. transmission that has lower mileage than any luxury vehicle at that
  663. location.
  664. j. Delete all the reservations for customer whose last name starts with ‘S’.
  665. 52
  666. Database Applications Lab REVA University
  667. School of Computing and Information Technology Page 23
  668. 7. Solutions for Exercises
  669. I. Product - order Database
  670. Customer (cid, cname, city, discount)
  671. Agent (aid, aname, city, commission)
  672. Product (pid, pname, city, quantity, price)
  673. Orders (ordno, month, cid, aid, pid, qty, amount)
  674. Aim: Create the tables with the appropriate integrity constraints and Insert around 10
  675. records
  676. in each of the tables
  677. SQL> Create table Customer ( cid char(4) ,cname varchar(13) not null,city varchar(20),
  678. discount real check(discount >= 0.0 and discount <= 15.0),
  679. primary key (cid));
  680. Table created.
  681. Explanation: The above command will create a new table Customer in database system
  682. with 4 columns, namely cid, cname, city and discount using not null constraint for cname
  683. and primary key constraint for cid, discount checking with constraint as discount range+
  684. greater than zero and less than 15 percent.
  685. SQL> desc customer;
  686. OUTPUT:
  687. Name Null? Type
  688. CID NOT NULL CHAR(4)
  689. CNAME NOT NULL VARCHAR2(13)
  690. CITY VARCHAR2(20)
  691. DISCOUNT FLOAT(63)
  692. SQL>Create table agent (aid char(3) ,aname varchar(13) not null, city varchar(20), percent
  693. number(6) check(percent >= 0 and percent <= 100),primary key
  694. (aid));
  695. Table created.
  696. Explanation: The above command will create a new table agent in database system with 4
  697. columns, namely aid, aname, city and percent using not null constraint for aname and
  698. primary key constraint for aid, percent checking with constraint as percent range greater
  699. than or equal to zero and less than equal to 100 percent.
  700. Database Applications Lab REVA University
  701. School of Computing and Information Technology Page 24
  702. SQL> desc agent;
  703. OUTPUT:
  704. Name Null? Type
  705. AID NOT NULL CHAR(3)
  706. ANAME NOT NULL VARCHAR2(13)
  707. CITY VARCHAR2(20)
  708. PERCENT NUMBER(6)
  709. SQL>Create table product ( pid char(3),pname varchar(13) unique not null,city varchar(20),
  710. quantity number(10) check(quantity > 0),price real check(price >
  711. 0.0),primary key (pid));
  712. Table created.
  713. Explanation: The above command will create a new table Product in database system with 5
  714. columns, namely pid, pname, city , Quantity and price using not null constraint for pname
  715. and primary key constraint for pid , price checking with constraint as range greater than
  716. zero.
  717. SQL> desc product;
  718. OUTPUT:
  719. Name Null? Type
  720. PID NOT NULL CHAR(3)
  721. PNAME NOT NULL VARCHAR2(13)
  722. CITY VARCHAR2(20)
  723. QUANTITY NUMBER(10)
  724. PRICE FLOAT(63)
  725. SQL>Create table orders ( ordno number(6),month char(3),cid char(4) not null,aid char(3)
  726. not null,pid char(3) not null,qty number(6) not null check(qty > 0),
  727. ordamount float default 0.0 check(ordamount >= 0.0),primary
  728. key
  729. (ordno),foreign key (cid) references customer, foreign key (aid)
  730. references agent,foreign key (pid) references product);
  731. Table created.
  732. Explanation: The above command will create a new table orders in database system with 7
  733. columns, namely ordno, month, cid ,aid, pid, Qty and ordamount and with foreign key
  734. create table order (
  735. *
  736. ERROR at line 1:
  737. ORA-00903: invalid table name
  738. As order is a reserved word in oracle we cant create a table with name “order” so used orders
  739. Database Applications Lab REVA University
  740. School of Computing and Information Technology Page 25
  741. constraint of cid referring to customer and aid referring agent, pid referring product, ordno
  742. as primary key and quantity with check constraint with range greater than zero .
  743. SQL> desc order;
  744. OUTPUT:
  745. Name Null? Type
  746. ORDNO NOT NULL NUMBER(6)
  747. MONTH CHAR(3)
  748. CID NOT NULL CHAR(4)
  749. AID NOT NULL CHAR(3)
  750. PID NOT NULL CHAR(3)
  751. QTY NOT NULL NUMBER(6)
  752. DOLLARS FLOAT(126)
  753. Insert the data into the table customer, agent , product, orders
  754. SQL> insert into customer values (’c001’,’Sobhit’,’Darjeling’,10.00);
  755. 1 row created.
  756. SQL>insert into customer values (’c002’,’Bhanu’,’Srinagar’,12.00);
  757. 1 row created.
  758. SQL>insert into customer values (’c003’,’Amar’,’ Srinagar’,8.00);
  759. 1 row created.
  760. SQL>insert into customer values (’c004’,’Anand’,’Darjeling’,8.00);
  761. 1 row created.
  762. SQL>insert into customer values (’c005’,’Anand’,’Mumbai’,0.00);
  763. 1 row created.
  764. NOTE: If an attempt is made to insert the same cid , as it is having primary constraint it
  765. shows an error.
  766. SQL> insert into customer values ('c001','Sachin','Darjeling',10.00);
  767. 1 row created.
  768. SQL>insert into customer values ('c001','Sachin','Darjeling',10.00)*
  769. ERROR at line 1:
  770. ORA-00001: unique constraint (DBMS.SYS_C005054) violated
  771. Database Applications Lab REVA University
  772. School of Computing and Information Technology Page 26
  773. SQL> select * from customer;
  774. OUTPUT:
  775. CID CNAME CITY DISCOUNT
  776. c001 Sobhit Darjeling 10
  777. c002 Bhanu Srinagar 12
  778. c003 Amar Srinagar 8
  779. c004 Anand Darjeling 8
  780. c005 Anand Mumbai 0
  781. SQL>insert into agent values('a01','Sonu','NewDelhi',6.00);
  782. 1 row created.
  783. SQL>insert into agent values('a02','John','Agra',6.00);
  784. 1 row created.
  785. SQL>insert into agent values('a03','Bhargav','Jaipur',7.00);
  786. 1 row created.
  787. SQL>insert into agent values('a04','Gaurav','NewDelhi',6.00);
  788. 1 row created.
  789. SQL>insert into agent values('a05','Omkar','Srinagar',5.00);
  790. 1 row created.
  791. SQL>insert into agent values('a06','Sonu','Darjeling',5.00);
  792. 1 row created.
  793. SQL> select * from agent;
  794. OUTPUT:
  795. AID ANAME CITY PERCENT
  796. a01 Sonu NewDelhi 6
  797. a02 John Agra 6
  798. a03 Bhargav Jaipur 7
  799. a04 Gaurav NewDelhi 6
  800. a05 Omkar Srinagar 5
  801. a06 Sonu Darjeling 5
  802. 6 rows selected.
  803. Database Applications Lab REVA University
  804. School of Computing and Information Technology Page 27
  805. SQL>insert into product values('&PID','&PNAME','&CITY',’&QUANTITY’,’&PRICE’);
  806. OUTPUT:
  807. PID PNAME CITY QUANTITY PRICE
  808. --- ------------- -------------------- ---------- --------------------------
  809. p01 comb Darjeling 100000 10
  810. p02 brush Agra 200000 20
  811. p03 eraser Srinagar 150000 2
  812. p04 pen Srinagar 100000 15
  813. p05 pencil Darjeling 170000 3
  814. p06 folder Darjeling 180000 15
  815. p07 Highlighter Agra 180000 20
  816. SQL> insert into orders values ('&ordno','&month','&cid','&aid','&pid',&qty,&ordamount);
  817. Enter value for ordno: 1011
  818. Enter value for month: jan
  819. Enter value for cid: c001
  820. Enter value for aid: a01
  821. Enter value for pid: p01
  822. Enter value for qty: 1000
  823. Enter value for ordamount: 9400
  824. old 1: insert into orders values ('&ordno','&month','&cid','&aid','&pid',&qty,&ordamount)
  825. new 1: insert into orders values ('1011','jan','c001','a01','p01',1000,9400)
  826. 1 row created.
  827. SQL> /
  828. Enter value for ordno: 1012
  829. Enter value for month: jan
  830. Enter value for cid: c001
  831. Enter value for aid: a01
  832. Enter value for pid: p01
  833. Enter value for qty: 1000
  834. Enter value for ordamount: 9400
  835. SQL> select * from orders;
  836. OUTPUT:
  837. ORDNO MON CID AID PID QTY ORDAMOUNT
  838. Database Applications Lab REVA University
  839. School of Computing and Information Technology Page 28
  840. 1011 jan c001 a01 p01 1000 9400
  841. 1012 jan c001 a01 p01 1000 9400
  842. 1013 jan c002 a03 p03 1000 1860
  843. 1014 jan c003 a03 p05 1200 3348
  844. 1015 jan c003 a03 p05 1200 3348
  845. 1016 jan c005 a01 p01 1000 9400
  846. 1017 feb c001 a02 p02 400 7520
  847. 1018 feb c001 a03 p04 600 2232
  848. 1019 feb c001 a02 p02 400 7520
  849. 1020 feb c005 a03 p07 600 11160
  850. 1021 feb c004 a06 p01 1000 9500
  851. 1022 mar c001 a05 p06 400 5700
  852. 1023 mar c001 a04 p05 500 1410
  853. 1024 mar c005 a06 p01 800 7600
  854. 1025 Apr c001 a05 p07 800 15200
  855. 15 ows selected.
  856. a. Retrieve the customer ids of any product which has been ordered by agent "a06".
  857. SQL> select distinct p.cid from orders o, orders p where p.pid=o.pid and o.aid='a06'
  858. Explanation: Distinct keyword gives the different values of attribute cid from table Orders
  859. and product with the join ,pid attribute from product table and pid attribute from order
  860. table ,whose agent id is ao6.
  861. OUTPUT:
  862. CID
  863. c001
  864. c004
  865. c005
  866. b. Retrieve cities in which customers or agents located.
  867. SQL> select city from customer
  868. union
  869. select city from agent;
  870. Explanation: This query retrieves the city names as the union operator helps to combine
  871. both the tables customer and agent containing column name city and it won’t allow
  872. duplicate values.
  873. OUTPUT:
  874. CITY
  875. Agra
  876. Database Applications Lab REVA University
  877. School of Computing and Information Technology Page 29
  878. Darjeling
  879. Jaipur
  880. Mumbai
  881. NewDelhi
  882. Srinagar
  883. 6 rows selected.
  884. c. List product ids which have been ordered by agents from the cities “Dargeling” or
  885. “Srinagar”.
  886. SQL> select distinct(o.pid) from orders o ,agent a where o.aid=a.aid and
  887. a.city in( ’Darjeling’,’Srinagar’);
  888. Explanation: Distict helps to select the distinct values of pid attribute from order table and
  889. agent table, and the columns aid from tables order and agents with city ‘Darjeeling’ and
  890. Srinagar using in operator.
  891. or
  892. SQL> select distinct(pid) from orders where aid in (select aid from agent where
  893. city in( ’Darjeling’,’Srinagar’));
  894. Explanation: Distinct selects the distinct values of pid from orders table and using in
  895. operator to select the aid attribute from agent table with city names darjeling and Srinagar.
  896. OUTPUT:
  897. PID
  898. p01
  899. p06
  900. p07
  901. d. Retrieve customer ids whose discounts are less than the maximum discount.
  902. SQL> select cid from customer
  903. where discount < (select max(discount)
  904. from customer);
  905. Explanation: This query gives the customer ids from customer table with condition whose
  906. discount is less than max discount as max(discount) gives the maximum discount from
  907. customer table.
  908. Database Applications Lab REVA University
  909. School of Computing and Information Technology Page 30
  910. OUTPUT:
  911. CID
  912. c001
  913. c003
  914. c004
  915. c005
  916. e. Retrieve product ids ordered by at least two customers.
  917. SQL> select p.pid from product p
  918. where 2 < = (select count(distinct cid) from orders
  919. where pid = p.pid);
  920. Explanation: This Query gives the pids from prouct table ,with condition 2<= count(distinct
  921. cid) as count gives the no.of distinct cids from orders table and pid column from product
  922. table .
  923. OUTPUT:
  924. PID
  925. p01
  926. p05
  927. p07
  928. f. For each (aid,pid) pair get the sum of the orders aid has placed for pid
  929. SQL> select pid, aid, sum(qty) TOTAL
  930. from orders
  931. group by pid, aid;
  932. Explanation: To retrieve pid and aid attribute and the sum operator is used to return the
  933. total sum of the qty column from orders table using group by function is used to get the
  934. result in a set of pid and aid attributes.
  935. OUTPUT:
  936. PID AID TOTAL
  937. p01 a01 3000
  938. p01 a06 1800
  939. p02 a02 800
  940. p03 a03 1000
  941. p04 a03 600
  942. p05 a03 2400
  943. p05 a04 500
  944. p06 a05 400
  945. p07 a03 600
  946. p07 a05 800
  947. 10 rows selected.
  948. Database Applications Lab REVA University
  949. School of Computing and Information Technology Page 31
  950. g. Retrieve product ids and total quantity ordered for each product when the total
  951. exceeds 1000.
  952. SQL> select pid, aid, sum(qty) TOTAL
  953. from orders
  954. group by pid, aid
  955. having sum(qty) > 1000;
  956. Explanation: To retrieve pid and aid attributes and the sum operator is used to return the
  957. total sum of the qty from orders table using group by function is used to get the result in a
  958. set of pid and aid attributes and having clause is used instead of where as condition whose
  959. sum(qty) is greater than 1000.
  960. OUTPUT:
  961. PID AID TOTAL
  962. p01 a01 3000
  963. p01 a06 1800
  964. p05 a03 2400
  965. h. List the names of the customers and agent who placed an order through that agent.
  966. SQL> select distinct cname, aname
  967. from customer, orders, agent
  968. where customer.cid = orders.cid and
  969. orders.aid = agent.aid;
  970. Explanation: This query gives distinct values from attributes v=cname,aname from
  971. customer, orders and agent tables with condition cid from customer table and orders and
  972. also from aid attribute from orders and agent table.
  973. OUTPUT:
  974. CNAME ANAME
  975. Amar Bhargav
  976. Anand Bhargav
  977. Anand Sonu
  978. Bhanu Bhargav
  979. Sobhit Bhargav
  980. Sobhit Gaurav
  981. Sobhit John
  982. Sobhit Omkar
  983. Sobhit Sonu
  984. 6 rows selected.
  985. Database Applications Lab REVA University
  986. School of Computing and Information Technology Page 32
  987. i. Retrieve the order numbers placed by customers in "Dargeling" through agents in
  988. "NewDelhi".
  989. SQL>select ordno from orders where cid in (select cid from customer where city =
  990. ’Darjeling’) and aid in (select aid from agent where city = ’NewDelhi’);
  991.  
  992. Explanation: To get ordno from orders table with condition using in operator for
  993. attribute cid from customer table whose city is darjeling and aid from agent table whose city
  994. is newdelhi.
  995. OUTPUT:
  996. ORDNO
  997. 1011
  998. 1012
  999. 1023
  1000. j. Retrieve names of the customers who have the same discount as that of any (one) of
  1001. the
  1002. customers in "Dargeling" or "Bangalore".
  1003. SQL>select cname from customer where discount =any (select discount from customer
  1004. where city = ’Darjeling’ or city = ’Bangalore’);
  1005. Explanation: To get the cname from customer table with condition where any value of
  1006. discount from customer table whose city is Darjeeling or Bangalore.
  1007. OUTPUT:
  1008. CNAME
  1009. Sobhit
  1010. Anand
  1011. Amar
  1012. k. Retrieve customer ids with smaller discounts than every customer from " Srinagar”
  1013. SQL>select cid from customer where discount < all (select discount from customer
  1014. where city = ’Srinagar’);
  1015. Explanation: To get cid from customer table, with condition whose all discount values is
  1016. less than the discount of every customer whose city is Srinagar.
  1017. OUTPUT:
  1018. CID
  1019. c005
  1020. l. Retrieve names of the customers who have placed an order through agent "a05"
  1021. (using exists )
  1022. SQL>select c.cname from customer c where exists (select * from orders o
  1023. where c.cid = o.cid and o.aid = ’a05’);
  1024. Database Applications Lab REVA University
  1025. School of Computing and Information Technology Page 33
  1026. Explanation: To get the cname from customer table as exist helps to check the existence of
  1027. query and selects the complete table from orders with condition cid attribute from
  1028. customer table and order table whose aid column from order table is a05.
  1029. or
  1030. SQL>select cname from customer where cid in (select cid from orders where aid='a05');
  1031. OUTPUT:
  1032. CNAME
  1033. Sobhit
  1034. m. Retrieve names of the customers who do not place orders through agent "a05".
  1035. (using
  1036. not exists)
  1037. SQL>select cname from customer where cid not in (select cid from orders
  1038. where orders.aid = 'a05');
  1039. Explanation: To retrieve cname from customer table with condition cid from orders table is
  1040. not in cid of order table where aid from order table is a05
  1041. or
  1042. SQL>select cname from customer where cid <>any (select cid from orders where
  1043. orders.aid = 'a05');
  1044. OUTPUT:
  1045. CNAME
  1046. Bhanu
  1047. Amar
  1048. Anand
  1049. Anand
  1050. n. Retrieve customer ids whose orders placed through all the agents in "New Delhi".
  1051. Get cid values of customers such that (the set of agents from " NewDelhi " through
  1052. whom the customer has NOT placed an order) is EMPTY.
  1053. SQL> select c.cid from customer c
  1054. where not exists (select * from agent a where a.city = ’NewDelhi’
  1055. and
  1056. not exists (select * from orders o
  1057. where o.cid = c.cid and o.aid = a.aid));
  1058. Explanation: To retrieve cid from customer table ,with condition not exists,as this helps to
  1059. get the values which are not existed in the agent table whose city is new delhi and also from
  1060. orders table that do not exist with condition cid column from order table equal to cid
  1061. column from customer table and also aid columns from order and agent tables.
  1062. OUTPUT:
  1063. CID
  1064. c001
  1065. Database Applications Lab REVA University
  1066. School of Computing and Information Technology Page 34
  1067. o. Retrieve agent ids either from "NewDelhi" or "Srinagar" who place orders for ALL
  1068. products priced over fifteen rupee.Get aid values of agents from "New York" or
  1069. "Duluth" such
  1070. that (the set of products priced over one dollar that the agent has NOT ordered) is
  1071. EMPTY.
  1072. SQL> select a.aid from agent a where (a.city in (’NewDelhi’,’Srinagar’)) and
  1073. not exists (select p.pid from product p where p.price > 15.00
  1074. and
  1075. not exists (select * from orders o where o.pid = p.pid and o.aid = a.aid));
  1076. Explanation:To retrieve aid from agent table whose cities are new delhi and srinagar and
  1077. using not exist to select the pid from product whose price is greater than 15,and also again
  1078. using not exist from orders table where pid from order and product table also aid from both
  1079. tables are equal.
  1080. OUTPUT:
  1081. no rows selected
  1082. So
  1083. insert into orders values('1026','apr','c005','a05','p02',900,17100);
  1084. OUTPUT:
  1085. AID
  1086. a05
  1087. p. Retrieve names and ids of the customers and agents along with total sales for that
  1088. pair.
  1089. Order the result from largest to smallest total sales. Also retain only those pairs for
  1090. which
  1091. total rupee sales is at least 9000.00.
  1092. SQL> select c.cname, c.cid, a.aname, a.aid, sum(o.ordamount)
  1093. from customer c, orders o, agent a
  1094. where c.cid = o.cid and o.aid = a.aid
  1095. group by c.cname, c.cid, a.aname, a.aid
  1096. having sum(o.ordamount) >= 9000.00
  1097. order by 5 desc;
  1098. Explanation:To retrieve cname,cid,from customer table and aname and aid from agent
  1099. table,with sum function for order amount from order table ,customer and agent table with
  1100. condition cid from customer and order tables and aid from order and agent tables are equal
  1101. and to get the result in one set group by is used for cname,cid of customer table and aid
  1102. ,aname from agent table with sum of ordramount of order table is >= 9000 in descending
  1103. order as result.
  1104. Database Applications Lab REVA University
  1105. School of Computing and Information Technology Page 35
  1106. OUTPUT:
  1107. CNAME CID ANAME AID SUM(O.ORDAMOUNT)
  1108. Sobhit c001 Omkar a05 20900
  1109. Sobhit c001 Sonu a01 18800
  1110. Sobhit c001 John a02 15040
  1111. Anand c005 Bhargav a03 11160
  1112. Anand c004 Sonu a06 9500
  1113. Anand c005 Sonu a01 9400
  1114. 6 rows selected.
  1115. q.Increase the percent commission by 50% for all agents in "NewDelhi".
  1116. SQL> update agent
  1117. set percent = 1.5 * percent
  1118. where city = ’NewDelhi;
  1119. Explanation:To update agent table, percentage value is set to 1.5*percent to get 50%
  1120. whose city is NewDelhi.
  1121. r. Retrieve the total quantity that has been placed for each product
  1122. SQL> select pid, sum(qty) TOTAL
  1123. from orders
  1124. group by pid;
  1125. Explanation: To get pid with total sum of qty from orders table using group by to get the
  1126. result in one set.
  1127. OUTPUT:
  1128. PID TOTAL
  1129. p01 4800
  1130. p02 800
  1131. p03 1000
  1132. p04 600
  1133. p05 2900
  1134. p06 400
  1135. p07 1400
  1136. 7 rows selected.
  1137. II. Company Database
  1138. Database Applications Lab REVA University
  1139. School of Computing and Information Technology Page 36
  1140. Designing a company database which can store department, project, employee and his
  1141. dependent details of a particular organization.
  1142. Employee (ssn, name, salary, sex, super_ssn, address, dno)
  1143. Department (dname, dnumber)
  1144. Dept_Loc ( dnumber, dloc, mgrssn)
  1145. Project (pname, pnumber, plocation, dnum)
  1146. Works_On (essn, pno, hours)
  1147. Dependent (essn, depen_name, address, relationship, sex)
  1148.  
  1149. Aim: Create the tables with the appropriate integrity constraints and Insert around 10
  1150. records
  1151. in each of the tables
  1152. NOTE: Department table has a column mgr_ssn which is a foreign key referring to ssn
  1153. column
  1154. of an employee table And employee table has a column dno which is a foreign key
  1155. referring to dnumber of department table.So it is interlinked and deadlock
  1156. appears.
  1157. step i create table department with attributes dno, dname (without mgr_ssn column)
  1158. step ii insert data into department
  1159. step iii create table employee and insert data ( without super_ssn column)
  1160. step iv insert data into employee table
  1161. step v add new column super_ssn into employee table and update data to column
  1162. super_ssn
  1163. step vi add new column mgrssn into department referring to employee table
  1164. stpe vii insert data of mgrssn in department table
  1165. SQL>Create table Department (dname varchar(15), unique not null, dnumber int ,
  1166. Primary key (dnumber));
  1167. Table Created.
  1168. SQL> Create table Employee(ssn char(9), name varchar(15) not null, salary decimal(10,2),
  1169. sex char, address varchar(30),dno int not null, primary key(ssn),
  1170. foreign key(dno) references Department(dnumber));
  1171. Table Created.
  1172. SQL>Create table Dept_Location(dnumber int not null, dlocation varchar(15) not null,
  1173. primary key(dnumber, dlocation), foreign key(dnumber)
  1174. references Department(dnumber) );
  1175. Table Created.
  1176. SQL>Create table Projet( pname varchar(15) not null, pnumber varchar(5) not null,
  1177. plocation varchar(15),dnum int not null, primary key (pnumber),
  1178. unique(pname),foreign key (dnum) references
  1179. Department(dnumber));
  1180. Database Applications Lab REVA University
  1181. School of Computing and Information Technology Page 37
  1182. Table Created.
  1183. SQL>Create table workson(essn char(9)not null, pno varchar(5) not null, hours decimal(3,1)
  1184. not null , primary key(essn, pno),foreign key (essn) references
  1185. employee(ssn), foreign key (pno) references project(pnumber));
  1186. Table Created.
  1187. SQL>Create table Dependent (essn char(9)not null, dependent_name varchar(15)not null,
  1188. sex CHAR,relationship varchar(8),primary key (essn),
  1189. dependent_name),foreign key(essn) references
  1190. Employee(ssn));
  1191. Table Created.
  1192. SQL> desc Department;
  1193. OUTPUT:
  1194. Name Null? Type
  1195. DNAME NOT NULL VARCHAR2(15)
  1196. DNUMBER NOT NULL NUMBER(38)
  1197. SQL> desc Employee;
  1198. OUTPUT :
  1199. Name Null? Type
  1200. SSN NOT NULL CHAR(9)
  1201. NAME NOT NULL VARCHAR2(15)
  1202. SALARY NUMBER(10,2)
  1203. SEX CHAR(1)
  1204. ADDRESS VARCHAR2(30)
  1205. DNO NOT NULL NUMBER(38)
  1206. SQL> desc employee;
  1207. OUTPUT :
  1208. Name Null? Type
  1209. SSN NOT NULL CHAR(9)
  1210. NAME NOT NULL VARCHAR2(15)
  1211. SALARY NUMBER(10,2)
  1212. SEX CHAR(1)
  1213. ADDRESS VARCHAR2(30)
  1214. DNO NOT NULL NUMBER(38)
  1215. SUPER_SSN CHAR(9)
  1216. Database Applications Lab REVA University
  1217. School of Computing and Information Technology Page 38
  1218. SQL> desc Dept_Location;
  1219. OUTPUT:
  1220. Name Null? Type
  1221. DNUMBER NOT NULL NUMBER(38)
  1222. DLOCATION NOT NULL VARCHAR2(15)
  1223. SQL> desc Project;
  1224. OUTPUT:
  1225. Name Null? Type
  1226. PNAME NOT NULL VARCHAR2(15)
  1227. PNUMBER NOT NULL VARCHAR2(5)
  1228. PLOCATION VARCHAR2(15)
  1229. DNUM NOT NULL NUMBER(38)
  1230. SQL> desc Workson;
  1231. OUTPUT:
  1232. Name Null? Type
  1233. ESSN NOT NULL CHAR(9)
  1234. PNO NOT NULL VARCHAR2(5)
  1235. HOURS NOT NULL NUMBER(3,1)
  1236. SQL> desc Dependent;
  1237. OUTPUT:
  1238. Name Null? Type
  1239. ESSN NOT NULL CHAR(9)
  1240. DEPENDENT_NAME NOT NULL VARCHAR2(15)
  1241. SEX CHAR(1)
  1242. RELATIONSHIP VARCHAR2(8)
  1243. SQL> Insert into Department values (‘Research’,1);
  1244. 1 row created.
  1245. SQL> Insert into Department values (‘HR’,2);
  1246. 1 row created.
  1247. SQL> Insert into Department values (‘Development’,3);
  1248. 1 row created.
  1249. SQL> Insert into Department values (‘Testing’,4);
  1250. 1 row created.
  1251. SQL> select * from Department;
  1252. Database Applications Lab REVA University
  1253. School of Computing and Information Technology Page 39
  1254. OUTPUT:
  1255. DNAME DNUMBER
  1256. Research 1
  1257. HR 2
  1258. Development 3
  1259. Testing 4
  1260. SQL>Insert into Employee values('emp001','Ram',30000,'M','RT Nagar, Blore',3);
  1261. 1 row created.
  1262. SQL>Insert into Employee values('emp002','Sudha',75000,'F','Hebbal, Blore',2);
  1263. 1 row created.
  1264. SQL>Insert into Employee values('emp003','Ravi’,20000,'M','Hebbal, Blore',4);
  1265. 1 row created.
  1266. SQL>Insert into Employee values('emp004','Rohan',80000,'M','RT Nagar, Mysore',1);
  1267. 1 row created.
  1268. SQL>Insert into Employee values('emp005','Amar',35000,'M','MG Road, Mysore',3);
  1269. 1 row created.
  1270. SQL>Insert into Employee values('emp006','Anil',45000,'M','MG Road, Noida’,3);
  1271. 1 row created.
  1272. SQL>Insert into Employee values('emp007','Tanya',35000,'F','Yelahanka, Blore',3);
  1273. 1 row created.
  1274. SQL>Insert into Employee values('emp008','Kavita',50000,'F','Baglur, Blore',1);
  1275. 1 row created.
  1276. SQL>Insert into Employee values('emp009','John',45000,'M','RT Nagar, Blore',4);
  1277. 1 row created.
  1278. SQL> select * from employee;
  1279. OUTPUT:
  1280. SSN NAME SALARY SEX ADDRESS DNO
  1281. emp001 Ram 30000 M RT Nagar, Blore 3
  1282. emp002 Sudha 75000 F Hebbal, Blore 2
  1283. emp003 Ravi 20000 M Hebbal, Blore 4
  1284. emp004 Rohan 80000 M RT Nagar, Mysore 1
  1285. emp005 Amar 35000 M MG Road, Mysore 3
  1286. emp006 Anil 45000 M MG Road, Noida 3
  1287. emp007 Tanya 35000 F Yelahanka, Blore 3
  1288. emp008 Kavita 50000 F Baglur, Blore 1
  1289. emp009 John 45000 M RT Nagar, Blore 4
  1290. SQL>alter table employee add super_ssn char(9) references employee(ssn);
  1291. Table altered.
  1292. Database Applications Lab REVA University
  1293. School of Computing and Information Technology Page 40
  1294. SQL>update employee set super_ssn=’emp006’ where ssn=’emp001’;
  1295. 1 row updated.
  1296. SQL>update employee set super_ssn=’emp008’ where ssn=’emp003’;
  1297. 1 row updated.
  1298. SQL>update employee set super_ssn=’emp002’ where ssn=’emp005’;
  1299. 1 row updated.
  1300. SQL>update employee set super_ssn=’emp008’ where ssn=’emp006’;
  1301. 1 row updated.
  1302. SQL>update employee set super_ssn=’emp008’ where ssn=’emp007’;
  1303. 1 row updated.
  1304. SQL>update employee set super_ssn=’emp004’ where ssn=’emp008’;
  1305. 1 row updated.
  1306. SQL>update employee set super_ssn=’emp008’ where ssn=’emp009’;
  1307. 1 row updated.
  1308. SQL> select * from employee;
  1309. OUTPUT:
  1310. SSN NAME SALARY S ADDRESS DNO
  1311. SUPER_SSN
  1312. emp001 Ram 30000 M RT Nagar, Blore 3 emp006
  1313. emp002 Sudha 75000 F Hebbal, Blore 2
  1314. emp003 Ravi 20000 M Hebbal, Blore 4 emp008
  1315. emp004 Rohan 80000 M RT Nagar, Mysore 1
  1316. emp005 Amar 35000 M MG Road, Mysore 3 emp002
  1317. emp006 Anil 45000 M MG Road, Noida 3 emp008
  1318. emp007 Tanya 35000 F Yelahanka, Blore 3 emp008
  1319. emp008 Kavita 50000 F Baglur, Blore 1 emp004
  1320. emp009 John 45000 M RT Nagar, Blore 4 emp008
  1321. SQL>alter table department add mgr_ssn char(9) references employee(ssn);
  1322. SQL> desc department;
  1323. OUTPUT:
  1324. Name Null? Type
  1325. DNAME NOT NULL VARCHAR2(15)
  1326. DNUMBER NOT NULL NUMBER(38)
  1327. MGR_SSN CHAR(9)
  1328. Database Applications Lab REVA University
  1329. School of Computing and Information Technology Page 41
  1330. SQL> select * from department;
  1331. OUTPUT:
  1332. DNAME DNUMBER MGR_SSN
  1333. Research 1
  1334. HR 2
  1335. Development 3
  1336. Testing 4
  1337. SQL>update department set mgr_ssn=’emp004’ where dnumber=1;
  1338. 1 row updated
  1339. SQL>update department set mgr_ssn=’emp002’ where dnumber=2;
  1340. 1 row updated
  1341. SQL>update department set mgr_ssn=’emp006’ where dnumber=3;
  1342. 1 row updated
  1343. SQL>update department set mgr_ssn=’emp009’ where dnumber=4;
  1344. 1 row updated
  1345. SQL> select * from department;
  1346. OUTPUT:
  1347. DNAME DNUMBER MGR_SSN
  1348. Research 1 emp004
  1349. HR 2 emp002
  1350. Development 3 emp006
  1351. Testing 4 emp009
  1352. SQL>Insert into Dept_Location values(1,’Blore’);
  1353. 1 row created.
  1354. SQL>Insert into Dept_Location values(2,’Blore’);
  1355. 1 row created.
  1356. SQL>Insert into Dept_Location values(3,’Blore’);
  1357. 1 row created.
  1358. SQL>Insert into Dept_Location values(3,’Mysore’);
  1359. 1 row created.
  1360. SQL>Insert into Dept_Location values(4,’Noida’);
  1361. 1 row created.
  1362. SQL>Insert into Dept_Location values(4,’Blore’);
  1363. 1 row created.
  1364. Database Applications Lab REVA University
  1365. School of Computing and Information Technology Page 42
  1366. SQL> select * from Dept_Location;
  1367. OUTPUT:
  1368. DNUMBER DLOCATION
  1369. 1 Blore
  1370. 2 Blore
  1371. 3 Blore
  1372. 3 Mysore
  1373. 4 Noida
  1374. 4 Blore
  1375. SQL>Insert into project values(‘Banking’,’p01’,’Blore’,3);
  1376. 1 row created.
  1377. SQL>Insert into project values(‘Android App’,’p02’,’Mysore’,3);
  1378. 1 row created.
  1379. SQL>Insert into project values(‘WSN’,’p03’,’Blore’,4);
  1380. 1 row created.
  1381. SQL>Insert into project values(‘Robotics’,’p04’,’Noida’,4);
  1382. 1 row created.
  1383. SQL>Insert into project values(‘Smart Vehicle’,’p05’,’Blore’,3);
  1384. 1 row created.
  1385. SQL> select * from project;
  1386. OUTPUT:
  1387. PNAME PNUMBER PLOCATION DNUM
  1388. Banking p01 Blore 3
  1389. Android App p02 Mysore 3
  1390. WSN p03 Blore 4
  1391. Robotics p04 Noida 4
  1392. Smart Vehicle p05 Blore 3
  1393. SQL>Insert into workson values(‘emp001’,’p01’,9);
  1394. 1 row created.
  1395. SQL>Insert into workson values(‘emp003’,’p01’,10);
  1396. 1 row created.
  1397. SQL>Insert into workson values(‘emp001’,’p02’,7);
  1398. 1 row created.
  1399. SQL>Insert into workson values(‘emp005’,’p03’,18);
  1400. 1 row created.
  1401. SQL>Insert into workson values(‘emp003’,’p02’,14);
  1402. 1 row created.
  1403. Database Applications Lab REVA University
  1404. School of Computing and Information Technology Page 43
  1405. SQL>Insert into workson values(‘emp004’,’p05’,12);
  1406. 1 row created.
  1407. SQL>Insert into workson values(‘emp007’,’p04’,14);
  1408. 1 row created.
  1409. SQL>Insert into workson values(‘emp001’,’p05’,12);
  1410. 1 row created.
  1411. SQL> select * from workson;
  1412. OUTPUT:
  1413. ESSN PNO HOURS
  1414. emp001 p01 14
  1415. emp003 p01 10
  1416. emp001 p02 7
  1417. emp005 p03 18
  1418. emp003 p02 14
  1419. emp004 p05 12
  1420. emp007 p04 14
  1421. emp001 p05 12
  1422. SQL> desc Dependent;
  1423. OUTPUT:
  1424. Name Null? Type
  1425. ESSN NOT NULL CHAR(9)
  1426. DEPENDENT_NAME NOT NULL VARCHAR2(15)
  1427. SEX CHAR(1)
  1428. RELATIONSHIP VARCHAR2(8)
  1429. SQL>Insert into Dependent values(‘emp001’,’Raghu’,’M’,’son’);
  1430. 1 row created.
  1431. SQL>Insert into Dependent values(‘emp004’,’Reshma’,’F’,’wife’);
  1432. 1 row created.
  1433. SQL>Insert into Dependent values(‘emp007’,’Bindu’,’F’,’daughter’);
  1434. 1 row created.
  1435. SQL>Insert into Dependent values(‘emp009’,’Shaan’,’M’,’son’);
  1436. 1 row created.
  1437. SQL>insert into dependent values('emp009','Shamir','M','son');
  1438. 1 row created.
  1439. Database Applications Lab REVA University
  1440. School of Computing and Information Technology Page 44
  1441. SQL> select * from dependent;
  1442. OUTPUT:
  1443. ESSN DEPENDENT_NAME SEX RELATION
  1444. emp001 Raghu M son
  1445. emp004 Reshma F wife
  1446. emp007 Bindu F daughter
  1447. emp009 Shaan M son
  1448. emp009 Shamir M son
  1449. a. Retrieve the names of the employees who works on all the projects controlled by dept
  1450. no 3
  1451. SQL>select name from employee
  1452. where not exists ((select pnumber from project where dnum = 3)
  1453. MINUS
  1454. (select pno from workson where essn = ssn));
  1455. Explanation :This Query gives the name of the employee using not exists with result of
  1456. minus operator whose pnumber from project table with condition dnum as 3 and pno from
  1457. workson table where essn=ssn.
  1458. OUTPUT:
  1459. NAME
  1460. Ram
  1461. b. Retrieve the names of the employees who gets second highest salary
  1462. SQL> select name from employee where salary in (select max(salary) from employee where
  1463. salary not in (select max(salary) from employee));
  1464. or
  1465. SQL> select name from employee where salary in (select max(salary) from employee where
  1466. salary < (select max(salary) from employee));
  1467. Explanation: This Query gives the name of the employee using max function for salary
  1468. column from employee table, whose sal is not in max(salary) or by using < operator .
  1469. OUTPUT:
  1470. NAME
  1471. Sudha
  1472. Database Applications Lab REVA University
  1473. School of Computing and Information Technology Page 45
  1474. C.Retrieve the names of the employees who have no dependents in alphabetical order.
  1475. SQL>select name
  1476. from employee e
  1477. where not exists (select * from dependent where essn=e.ssn) order by name;
  1478. or
  1479. SQL>select name from employee where ssn not in (select essn from dependent) order by
  1480. name;
  1481. Explanation: This query gives the name of employee using not exists in dependent with
  1482. condition essn=e.ssn using order by name.
  1483. or
  1484. By using not in and ssn column from dependent table using order by .
  1485. OUTPUT:
  1486. NAME
  1487. Anil
  1488. Sudha
  1489. Ravi
  1490. Amar
  1491. Kavita
  1492. d.List the names of all employees who have at least two dependents
  1493. SQL> Select name from employee
  1494. where ( SELECT COUNT (*) FROM DEPENDENT WHERE Ssn =Essn )>=2;
  1495. Explanation: This query gives the names of the employees,using count function as it gives
  1496. the count value of the selected table with condition ssn=Essn and >=2.
  1497. OUTPUT :
  1498. NAME
  1499. John
  1500. e. Retrieve the number of employees and their average salary working in each
  1501. department.
  1502. SQL>select dno, count (*),avg(salary) from employee group by dno;
  1503. Explanation: This Query gives dno,count and avg sal from employee table using group by
  1504. dno .
  1505. Database Applications Lab REVA University
  1506. School of Computing and Information Technology Page 46
  1507. OUTPUT :
  1508. DNO COUNT(*) AVG(SALARY)
  1509. 1 2 65000
  1510. 2 1 75000
  1511. 3 4 36250
  1512. 4 2 32500
  1513. f. Retrieve the highest salary paid in each department in descending order.
  1514. SQL>select dno,max(salary) from employee group by dno order by max(salary) desc;
  1515. Explanation: This Query gives the dno and Max (salary) Using Group by and Oder by
  1516. functions
  1517. with conditions group by dno and order by max(salary) as desc.
  1518. OUTPUT :
  1519. DNO MAX(SALARY)
  1520. 1 80000
  1521. 2 75000
  1522. 3 45000
  1523. 4 45000
  1524. g. Retrieve the SSN of all employees who work on atleast one of the project numbers 1, 2,
  1525. 3
  1526. SQL>select distinct(essn) from workson where pno in (‘p01’,’p02’,’p03’);
  1527. or
  1528. SQL>select distinct(essn) from workson where pno=‘p01’or pno=’p02’ or pno=’p03’;
  1529. Explanation :This Query gives the Essn of employee from workson table using distinct with
  1530. condition pno in (p01,p02,p03) or pno=p01 or p02,p03
  1531. OUTPUT :
  1532. ESSN
  1533. emp001
  1534. emp003
  1535. emp005
  1536. Database Applications Lab REVA University
  1537. School of Computing and Information Technology Page 47
  1538. h. Retrieve the number of dependents for an employee named RAM.
  1539. SQL>select count(*) from dependent where essn=(select ssn from employee where
  1540. name='Ram');
  1541. or
  1542. SQL>select count(*) from employee e, dependent d where d.essn=e.ssn and e.name='Ram';
  1543. Explanation :This Query gives the no .of dependents using count function for dependent
  1544. table with condition whose essn is equal to ssn of employee table whose ename is ram .
  1545. Or
  1546. Explanation: By using count for employee table and dependent with condition essn of
  1547. dependent table = ssn of employee table and whose name from employee table is ram.
  1548. OUTPUT :
  1549. COUNT(*)
  1550. 1
  1551. i. Retrieve the names of the managers working in location named xyz who has no female
  1552. dependents.
  1553. SQL>select name from employee where ssn in
  1554. (select essn from dependent where sex!='F' and essn in(
  1555. (select mgr_ssn from department where dnumber in
  1556. (select dnumber from dept_location where dlocation='Blore'))));
  1557. or
  1558. SQL>select distinct(name) from employee e , department d, dept_location l, dependent de
  1559. where e.ssn= de.essn and de.sex!='F' and de.essn=d.mgr_ssn and
  1560. d.dnumber=l.dnumber and l.dlocation='Blore';
  1561. Explanation: This query gives the name of manger from employee table by using IN
  1562. operator,
  1563. whose ssn from dependent table sex is not ‘F’ and mgr_ssn from department,whose
  1564. dnumber from dep_location is Blore.
  1565. Or
  1566. Explanation: By using distinct for name from employee table ,department ,dependent and
  1567. location tables whose ssn from employee =essn from dependent table and sex is not ‘F’ in
  1568. dependent and essn from dependent =mgr from department mgr_ssn and dnumber from
  1569. d=dhumber from l;and dlocation from l=’Blore’.
  1570. OUTPUT :
  1571. NAME
  1572. John
  1573. Database Applications Lab REVA University
  1574. School of Computing and Information Technology Page 48
  1575. j. Retrieve the names of the employees who works in the same department as that of
  1576. RAM
  1577. SQL>select name from employee where dno=
  1578. (select dno from employee where name='Ram') and name!='Ram';
  1579. Explanation: This gives the name from employee using condition get dno whose name is
  1580. ram
  1581. from emp table and name whose name is not ram.
  1582. OUTPUT :
  1583. NAME
  1584. Amar
  1585. Anil
  1586. Tanya
  1587. k. Retrieve the name of the employees whose salary is greater than the salary of all the
  1588. employees working in department 3.
  1589. SQL>SELECT name, salary FROM EMPLOYEE
  1590. WHERE Salary> ALL ( SELECT Salary FROM EMPLOYEE WHERE Dno=3 );
  1591. Explanation: To get the name, salary of employee from emp table using condition
  1592. whose salary is > All employees and whose dno=3.
  1593. OUTPUT :
  1594. NAME SALARY
  1595. Sudha 75000
  1596. Rohan 80000
  1597. Kavita 50000
  1598. l. Retrieve the names of the employees who work for dept no 3 and have a daughter as
  1599. dependent.
  1600. SQL>select name from employee e , dependent d
  1601. where e.ssn=d.essn and d.relationship='daughter' and e.dno=3;
  1602. Explanation: This Query gives the name using conditions ssn fromemp=essn from
  1603. dependent
  1604. and relationship from depend=daughter and dno from emp=3.
  1605. OUTPUT :
  1606. NAME
  1607. Tanya
  1608. m. Retrieve the employee name who paid highest salary from each department
  1609. SQL>select name from employee where salary in
  1610. (select max(salary) from employee group by dno);
  1611. Database Applications Lab REVA University
  1612. School of Computing and Information Technology Page 49
  1613. Explanation: To get the name from emp using condition whose sal in emp using max
  1614. and groupby dno.
  1615. OUTPUT :
  1616. NAME
  1617. Rohan
  1618. Sudha
  1619. John
  1620. Anil
  1621. n. Retrieve the names of the employees who are paid the same salary as that of Anil
  1622. select name from employee where salary in (select salary from employee where
  1623. name='Anil') and name!=’Anil’;
  1624. or
  1625. select name from employee where salary = (select salary from employee where name='Anil')
  1626. and name!=’Anil’;
  1627. Explanation This gives the name of employee using In operator and condition sal frm emp
  1628. table whose name is Anil and name frm emp whose name is not anil.
  1629. OUTPUT :
  1630. NAME
  1631. John
  1632. o. Retrieve the total the number of employees in the ‘Research’ department.
  1633. SQL>select count (*) from Employee, department where dno =dnumber and
  1634. dname=‘Research’;
  1635. Explanation: To get the total ,we use count function along with condition whose dno is
  1636. dnumber and dname is research.
  1637. OUTPUT :
  1638. COUNT(*)
  1639. 2
  1640. Database Applications Lab REVA University
  1641. School of Computing and Information Technology Page 50
  1642. p. For each project, retrieve the project number, the project name, and the number of
  1643. employees who work on that project.
  1644. SQL>SELECT Pnumber, Pname, COUNT (*)
  1645. FROM Project, Workson
  1646. WHERE Pnumber=Pno GROUP BY Pnumber, Pname;
  1647. Explanation: This query gives the pnumb ,pname and total number from project and
  1648. workson
  1649. tables using condition whose pnumber is pno and group by pnumber and
  1650. pname.
  1651. OUTPUT :
  1652. PNUMB PNAME COUNT(*)
  1653. p01 Banking 2
  1654. p02 Android App 2
  1655. p03 WSN 1
  1656. p04 Robotics 1
  1657. p05 Smart Vehicle 2
  1658. Database Applications Lab REVA University
  1659. School of Computing and Information Technology Page 51
  1660. III. Car rental agency database
  1661. Design a car rental agentcy database which can store customer details, vehicle details like
  1662. vehicle id, size, transmission and reservation details like who had booked from one date
  1663. to other.
  1664. Customers(cid, firstname, lastname, address)
  1665. Vehicle(vid, mileage, location, size, transmission)
  1666. Reservations(cid,vid, start_date, end_date)
  1667. Note :
  1668. ->Vehicle.transmission can have two values ‘manual’ and ‘automatic’.
  1669. ->Vehicle.size can have following values. ‘compact’, ‘mid-size’, ‘full-size’, ‘premium’ and
  1670. ‘luxury’. The default size is compact.
  1671. Aim: Create the tables with the appropriate integrity constraints and Insert around 10
  1672. records
  1673. in each of the tables
  1674. SQL> create table carcustomer (cid varchar(5) ,first_name varchar(20) not null,last_name
  1675. varchar(15) not null,address varchar(30),Primary key(cid) );
  1676. Table Created
  1677. or
  1678. SQL>create table carcustomer ( cid varchar(5) PRIMARY KEY,first_name varchar(20) not null,
  1679. last_name varchar(15) not null,address varchar(30) );
  1680. Table Created
  1681. SQL> create table vehicle ( vid varchar(5) primary key,mileage number(7,2),location
  1682. varchar(20),vsize varchar(30) check (vsize in('compact','mid-size','full-
  1683. size','premium','luxury')),transmission varchar(10) check (transmission
  1684. in('manual','automatic')) );
  1685. Table Created
  1686. SQL> create table reservation ( cid varchar(5) references carcustomer(cid),vid varchar(5)
  1687. references vehicle(vid),start_date date,end_date date,primary key(cid,vid) );
  1688. Table Created
  1689. Database Applications Lab REVA University
  1690. School of Computing and Information Technology Page 52
  1691. SQL> desc carcustomer;
  1692. OUTPUT:
  1693. Name Null? Type
  1694. CID NOT NULL VARCHAR2(5)
  1695. FIRST_NAME NOT NULL VARCHAR2(20)
  1696. LAST_NAME NOT NULL VARCHAR2(15)
  1697. ADDRESS VARCHAR2(30)
  1698. SQL> desc vehicle;
  1699. OUTPUT:
  1700. Name Null? Type
  1701. VID NOT NULL VARCHAR2(5)
  1702. MILEAGE NUMBER(7,2)
  1703. LOCATION VARCHAR2(20)
  1704. VSIZE VARCHAR2(30)
  1705. TRANSMISSION VARCHAR2(10)
  1706. SQL> desc reservation;
  1707. OUTPUT:
  1708. Name Null? Type
  1709. VID NOT NULL VARCHAR2(5)
  1710. START_DATE DATE
  1711. END_DATE DATE
  1712. SQL>insert into carcustomer values ('101','Karan','P','Malleswaram,Blore');
  1713. SQL>insert into carcustomer values ('102','Bhuvan','M’,'Vailakavali, Blore');
  1714. SQL>insert into carcustomer values ('103','Darshan',’D’,'Devanahalli,Devan');
  1715. SQL>insert into carcustomer values ('104','Vishal','D','Hebbal, Blore');
  1716. SQL>insert into carcustomer values ('105','Sagar','S','Kalyannagar, Blore');
  1717. Database Applications Lab REVA University
  1718. School of Computing and Information Technology Page 53
  1719. SQL> select * from carcustomer;
  1720. OUTPUT:
  1721. CID FIRST_NAME LAST_NAME ADDRESS
  1722. 101 Karan P Malleswaram,Blore
  1723. 102 Bhuvan M Vailakavali, Blore
  1724. 103 Darshan D Devanahalli,Devan
  1725. 104 Vishal D Hebbal, Blore
  1726. 105 Sagar S Kalyannagar, Blore
  1727. SQL> insert into vehicle values ('V-101','70',' Blore ','compact','automatic');
  1728. SQL>insert into vehicle values ('V-102','50','Surat','compact','automatic');
  1729. SQL>insert into vehicle values ('V-103','10',' Blore ','mid-size','manual');
  1730. SQL>insert into vehicle values ('V-104','30',' Blore ','mid-size','automatic');
  1731. SQL>insert into vehicle values ('V-105','15',' Vailakavali ','full-size','automatic');
  1732. SQL>insert into vehicle values ('V-106','20',' Blore ','luxury','automatic');
  1733. SQL>insert into vehicle values ('V-107','50',' Blore ','luxury','manual');
  1734. SQL> select * from vehicle;
  1735. VID MILEAGE LOCATION VSIZE TRANSMISSION
  1736. V-101 70 Blore compact automatic
  1737. V-102 50 Surat compact automatic
  1738. V-103 10 Blore mid-size manual
  1739. V-104 30 Blore mid-size automatic
  1740. V-105 15 Vailakavali full-size automatic
  1741. V-106 20 Blore luxury automatic
  1742. V-107 50 Blore luxury manual
  1743. 7 rows selected.
  1744. Database Applications Lab REVA University
  1745. School of Computing and Information Technology Page 54
  1746. SQL>insert into reservation values ('101','V-101','15-FEB-2009','18-FEB-2009');
  1747. SQL>insert into reservation values ('102','V-102','10-JAN-2011','15-JAN-2011');
  1748. SQL>insert into reservation values ('103','V-103','20-FEB-2013','24-FEB-2013');
  1749. SQL>insert into reservation values ('105','V-105','12-MAR-2016','10-JUN-2016');
  1750. SQL> select * from reservation;
  1751. OUTPUT:
  1752. CID VID START_DAT END_DATE
  1753. 101 V-101 15-FEB-09 18-FEB-09
  1754. 102 V-102 10-JAN-11 15-JAN-11
  1755. 103 V-103 20-FEB-13 24-FEB-13
  1756. 105 V-105 12-MAR-16 10-JUN-16
  1757. a. Display both the firstname and last name in uppercase as Name of the customer as
  1758. column name.
  1759. SQL> select upper(first_name) || ' '||upper(last_name) as "Name of the customers" from
  1760. carcustomer;
  1761. OUTPUT:
  1762. Name of the customers
  1763. KARAN P
  1764. BHUVAN M
  1765. DARSHAN D
  1766. VISHAL D
  1767. SAGAR S
  1768. Explanation: This query concatenates the first name and last name in uppercase whose first
  1769. name is "Vishal".
  1770. b. Display vehicles size which is having maximum mileage.
  1771. SQL> select vsize from vehicle where mileage = (select max(mileage) from vehicle);
  1772. OUTPUT:
  1773. VSIZE
  1774. Compact
  1775. Explanation: This query displays the vehicle size which has the maximum mileage.
  1776. c. Find location and total mileage of all vehicles specific to each respective location.
  1777. SQL> select location, sum(mileage) from vehicle group by location;
  1778. Database Applications Lab REVA University
  1779. School of Computing and Information Technology Page 55
  1780. OUTPUT:
  1781. LOCATION SUM(MILEAGE)
  1782. Blore 180
  1783. Vailakavali 15
  1784. Surat 50
  1785. Explanation: This query displays the location and total mileage of all vehicles specific to
  1786. each respective location using aggregate function Sum () and group by clause.
  1787. d. Find average mileage of vehicles for each location, which has at least five vehicles.
  1788. SQL> select avg(mileage),count(vid),location from vehicle
  1789. group by location having count(vid) >= 5;
  1790. OUTPUT:
  1791. AVG(MILEAGE) COUNT(VID) LOCATION
  1792. 36 5 Blore
  1793. Explanation: This query displays the average mileage of vehicles for each location in which
  1794. the location has at least five vehicles using Count and Avg aggregate functions.
  1795. e. Display the customer names whose reservation start date is before 18 Feb 2012.
  1796. SQL> SELECT c.first_name,c.last_name FROM RESERVATION r, carcustomer c
  1797. where c.cid=r.cid and r.start_date< '18-FEB-2012';
  1798. OUTPUT:
  1799. FIRST_NAME LAST_NAME
  1800. Karan P
  1801. Bhuvan M
  1802. Explanation: This query display the customer names whose reservation start date is before
  1803. 18 Feb 2012 by using the inner join between tables Customer and Reservation.
  1804. Database Applications Lab REVA University
  1805. School of Computing and Information Technology Page 56
  1806. f. Display the vehicles which has been reserved between the dates Nov 5th 2015 and Jan
  1807. 16th 2016
  1808. SQL> select vid from RESERVATION
  1809. WHERE start_date >= ‘5-JAN-2011’ AND end_date <= ‘1-JAN-2014’;
  1810. OUTPUT:
  1811. VID
  1812. V-102
  1813. V-103
  1814. Explanation: This query display the vehicles which has been reserved between the dates
  1815. Nov 5th 2015 and Jan 16th 2016 using Reservation table and where clause.
  1816. g. Display the names of the customers whose lastname starts with ‘D’ and who has
  1817. reserved more vehicles than the customer with CID as 101.
  1818. SQL> select c.first_name from carcustomer c
  1819. where c.last_name like ‘D%’ and c.cid in( select cid from reservation
  1820. group by cid having count(*) >(select count(*) from RESERVATION where cid
  1821. ='101'));
  1822. OUTPUT:
  1823. No rows selected
  1824. cid’s 103 &104 are having lastname as D,
  1825. 101 is having one record in reservation
  1826. So either 103 or 104 should have atleast 2 records
  1827. So I can insert minimum 1 record for 103 or 2 records for 104
  1828. SQL> insert into reservation values ('103','V-104','15-OCT-2014','24-OCT-2014');
  1829. OUTPUT:
  1830. FIRST_NAME
  1831. Darshan
  1832. Database Applications Lab REVA University
  1833. School of Computing and Information Technology Page 57
  1834. h. Retrieve the customers who have reserved vehicles from all the locations.
  1835. SQL> select c.cid from carcustomer c
  1836. where not exists
  1837. ((select distinct(location) from vehicle)
  1838. minus
  1839. (select v.location from vehicle v, reservation r where v.vid=r.vid and c.cid=r.cid));
  1840. OUTPUT:
  1841. No rows selected
  1842. NOTE :In reservation table we have 5records in which
  1843. 101, 102, 105 reserved once
  1844. 103 reserved twice (V-103, V-104)
  1845. But total number of distinct locations are three.
  1846. I should have atleast one customer who reserves in all these three locations.
  1847. V-103, V-104 reserved by 103 cid belongs to same location Blore
  1848. So we can’t consider 103 is reserved from 2 different locations
  1849. So I can insert data here for
  1850. 101 for surat and vailakavali or
  1851. 102 for Blore and vailakavali or
  1852. 103 for Surat and vailakavali so on
  1853. SQL>insert into reservation values ('103','V-102','12-MAR-2016','14-MAR-2016');
  1854. SQL>insert into reservation values ('103','V-105','15-APR-2016','20-APR-2016');
  1855. SQL> select * from reservation;
  1856. OUTPUT:
  1857. CID VID START_DAT END_DATE
  1858. 101 V-101 10-JAN-11 10-FEB-15
  1859. 102 V-102 12-MAR-11 10-JUN-16
  1860. 103 V-103 15-FEB-09 09-SEP-15
  1861. 105 V-105 15-FEB-13 09-SEP-15
  1862. 103 V-104 15-OCT-14 24-OCT-14
  1863. 103 V-102 12-MAR-16 14-MAR-16
  1864. 103 V-105 15-APR-16 20-APR-16
  1865. i. Retrieve the locations that have at least one vehicle with manual transmission that
  1866. has lower mileage than any luxury vehicle at that location.
  1867. SQL> select * from vehicle v1
  1868. Database Applications Lab REVA University
  1869. School of Computing and Information Technology Page 58
  1870. where v1.vsize not in (‘luxury’) and v1.transmission=’manual’
  1871. and v1.mileage<(select min(mileage) from vehicle v2 where v2.vsize=’luxury’ and
  1872. v1.location=v2.location);
  1873. OUTPUT:
  1874. VID MILEAGE LOCATION VSIZE TRANSMISSION
  1875. V-103 10 Blore mid-size manual
  1876. Explanation: This Query displays all the locations that have at least one vehicle with manual
  1877. transmission that has lower mileage than any luxury vehicle at that location by using
  1878. subquery.
  1879. j. Delete all the reservations for customer whose last name starts with ‘S’ or only S.
  1880. delete from reservation where cid in (select cid from carcustomer where last_name like
  1881. 'S%');
  1882. OUTPUT:
  1883. RESERVATION TABLE BEFORE 'DELETE' OPERATION :=====>
  1884. CID VID START_DAT END_DATE
  1885. 101 V-101 10-JAN-11 10-FEB-15
  1886. 102 V-102 12-MAR-11 10-JUN-16
  1887. 103 V-103 15-FEB-09 09-SEP-15
  1888. 105 V-105 15-FEB-13 09-SEP-15
  1889. 103 V-104 15-OCT-14 24-OCT-14
  1890. 103 V-102 12-MAR-16 14-MAR-16
  1891. 103 V-105 15-APR-16 20-APR-16
  1892. RESERVATION TABLE AFTER 'DELETE' OPERATION :=====>
  1893. CID VID START_DAT END_DATE
  1894. 101 V-101 10-JAN-11 10-FEB-15
  1895. 102 V-102 12-MAR-11 10-JUN-16
  1896. 103 V-103 15-FEB-09 09-SEP-15
  1897. 103 V-104 15-OCT-14 24-OCT-14
  1898. 103 V-102 12-MAR-16 14-MAR-16
  1899. 103 V-105 15-APR-16 20-APR-16
  1900. Explanation: This Query Delete all the reservations for customer whose last name starts
  1901. with ‘S’ or only S and the output is shown for the same, before deletion and after deletion.
  1902. Database Applications Lab REVA University
  1903. School of Computing and Information Technology Page 59
  1904. 8. Lab Assignments
  1905. SL.No. Practice & Assignment Queries
  1906. 1 Assignment Queries for Lab Exercise I
  1907. a. Retrieve the complete data from Customer table.
  1908. b. Retrieve the complete data from Agent table by mentioning attributes.
  1909. c. Display only product id and product name.
  1910. d. Display Product name and price as a single column and the column name
  1911. be “Product and their prices” (concatenation operator and alias).
  1912. e. Display the city names of the customers by eliminating duplicates.
  1913. f. Retrieve the names of the customers lives in “Mumbai”.
  1914. g. Display agent ids and names belongs to New Delhi.
  1915. h. Retrieve customer ids who ordered both “P01” and “P02”.
  1916. i. Get customers whose name begins with letter "A".
  1917. j. Retrieve the customers whose name starts with letter “A” and third letter
  1918. is “a” eg. Amar.
  1919. k. Retrieve the customers whose name consists of letter “a” eg. Amar,
  1920. Anand.
  1921. l. Get customer ids whose discount is between 8 and 10.
  1922. m. Display the product name whose price is 10 or 20 using IN and OR
  1923. operators.
  1924. n. Get total quantity of product "p01" that has been ordered.
  1925. o. Get number of cities in which customers are based.
  1926. p. Get total amount of all orders.
  1927. q. Get total number of customers.
  1928. r. Get average discount value for customers.
  1929. s. Get agent ids with the smallest percent commission.
  1930. t. Display the customer names who placed an order through the agent who
  1931. is having aid as “a01”.
  1932. u. Retrieve the names of the customers who live in “Mumbai” and order
  1933. product “P01”.
  1934. v. Retrieve customer ids who do not order part “P01”.
  1935. 2 Assignment Queries for Lab Exercise II
  1936. a. List female employees from dept no is 2 earning more than Rs.35000
  1937. b. Retrieve the names and address of all employee who work for the
  1938. ‘Research’ department.
  1939. c. Retrieve the names and salary of all employees who work in department
  1940. number 5.
  1941. d. Retrieve the names of the employees and their superSSN name
  1942. e. Display name as "Employee name" and salary for the year as "Annual
  1943. Income"
  1944. f. Display name, current salary and salary if it is going to be increased by
  1945. 800 rupees
  1946. g. Display Department name and number as a single column with the name
  1947. as “Department Details”
  1948. Database Applications Lab REVA University
  1949. School of Computing and Information Technology Page 60
  1950. h. Retrieve the names of the managers who have more than two
  1951. dependents.
  1952. i. Retrieve the names of the managers with atleast one dependent.
  1953. j. List all the Projects on which employee Ram is working
  1954. k. Retrieve the names of the employees who work on any project that
  1955. Kumar works.
  1956. l. Retrieve the names of the employees who do not have supervisor
  1957. m. Count the number of distinct salary values in the database.
  1958. n. For each project, retrieve the project number, the project name, and the
  1959. number of employees from department 3 who work on the project.
  1960. o. Retrieve all employees in department 3 whose salary is between
  1961. Rs.35,000 and Rs.40,000.
  1962. 9. Solutions for Lab Assignment Exercise I:
  1963. a) Retrieve the complete data from customer table
  1964. SQL> select * from customer;
  1965. OUTPUT:
  1966. CID CNAME CITY DISCOUNT
  1967. c001 Sobhit Darjeling 10
  1968. c002 Bhanu Srinagar 12
  1969. c003 Amar Srinagar 8
  1970. c004 Anand Darjeling 8
  1971. c005 Anand Mumbai 0
  1972. b) Retrieve the data complete from Agents by mentioning attributes
  1973. SQL>select aid, aname, city, percent from agent;
  1974. OUTPUT:
  1975. AID ANAME CITY PERCENT
  1976. a01 Sonu NewDelhi 6
  1977. a02 John Agra 6
  1978. a03 Bhargav Jaipur 7
  1979. a04 Gaurav NewDelhi 6
  1980. a05 Omkar Srinagar 5
  1981. a06 Sonu Darjeling 5
  1982. 7 rows selected.
  1983. c) Display only product id and product name
  1984. SQL> select pid,pname from product;
  1985. OUTPUT:
  1986. PID PNAME
  1987. Database Applications Lab REVA University
  1988. School of Computing and Information Technology Page 61
  1989. p01 comb
  1990. p02 brush
  1991. p03 eraser
  1992. p04 pen
  1993. p05 pencil
  1994. p06 folder
  1995. p07 Highlighter
  1996. 7 rows selected.
  1997. d) Display Product name and price as a single column and the column name be
  1998. “Product and their prices” (concatenation operator and alias)
  1999. SQL> select pname||price "product and their prices" from product;
  2000. OUTPUT:
  2001. product and their prices
  2002. comb 10
  2003. brush 20
  2004. eraser 2
  2005. pen 15
  2006. pencil 3
  2007. folder 15
  2008. Highlighter 20
  2009. 7 rows selected.
  2010. If some space has to be included between 2 column values after concatenating in the
  2011. output, use number of spaces required within the single quote along with
  2012. concatenation operator.
  2013. SQL> select pname||' '||price "product and their prices" from product;
  2014. OUTPUT:
  2015. product and their prices
  2016. comb 10
  2017. brush 20
  2018. eraser 2
  2019. pen 15
  2020. pencil 3
  2021. folder 15
  2022. Highlighter 20
  2023. Database Applications Lab REVA University
  2024. School of Computing and Information Technology Page 62
  2025. 7 rows selected.
  2026. SQL> select pname||' cost is '||price "product and their prices" from product;
  2027. OUTPUT:
  2028. product and their prices
  2029. comb cost is 10
  2030. brush cost is 20
  2031. eraser cost is 2
  2032. pen cost is 15
  2033. pencil cost is 3
  2034. folder cost is 15
  2035. Highlighter cost is 20
  2036. 8 rows selected.
  2037. e) Display the city names of the customers by eliminating duplicates
  2038.  
  2039. SQL> select distinct city from customer;
  2040. OUTPUT:
  2041. CITY
  2042. Srinagar
  2043. Darjeling
  2044. Mumbai
  2045. Srinagar
  2046. f)Retrieve the names of the customers lives in “Mumbai”
  2047.  
  2048. SQL> select cname from customer where city='Mumbai';
  2049. OUTPUT:
  2050. CNAME
  2051. Anand
  2052. g) Display agent ids and names belongs to New Delhi
  2053. SQL> select aid, aname from agent where city = 'NewDelhi';
  2054. OUTPUT:
  2055. AID ANAME
  2056. a01 Sonu
  2057. a04 Gaurav
  2058. h) Retrieve the customer ids who ordered the products “p01” and “p02”
  2059. SQL> select cid from orders where pid='p01' intersect select cid from orders where
  2060. pid='p07';
  2061. Database Applications Lab REVA University
  2062. School of Computing and Information Technology Page 63
  2063. OUTPUT:
  2064. CID
  2065. c001
  2066. c005
  2067. i) Get customers whose name begins with letter "A".
  2068. SQL> select cname from customer where cname like 'A%';
  2069. OUTPUT:
  2070. CNAME
  2071. Amar
  2072. Anand
  2073. Anand
  2074. j)Retrieve the customers whose name starts with letter “A” and third letter is “a” eg.
  2075. Amar
  2076. SQL> select cname from customer where cname like 'A_a%';
  2077. OUTPUT:
  2078. CNAME
  2079. Amar
  2080. Anand
  2081. Anand
  2082.  
  2083. k)Retrieve the customers whose name consists of letter “a”
  2084. SQL> select cname from customer where cname like '%a%';
  2085. OUTPUT:
  2086. CNAME
  2087. Bhanu
  2088. Amar
  2089. Anand
  2090. Anand
  2091. l)Get customer ids whose discount is between 8 and 10.
  2092. SQL> select cid from customer where discount between 8 and 10;
  2093. OUTPUT:
  2094. CID
  2095. c001
  2096. c003
  2097. Database Applications Lab REVA University
  2098. School of Computing and Information Technology Page 64
  2099. c004
  2100. m) Display the product name whose price is 10 or 20 using IN and OR operators
  2101. SQL> select pname from product where price in (10,20);
  2102. or
  2103. SQL> select pname from product where price=10 or price=20;
  2104. OUTPUT:
  2105. PNAME
  2106. comb
  2107. brush
  2108. Highlighter
  2109. n) Get total quantity of product "p01" that has been ordered.
  2110. SQL> select sum(qty) from orders where pid='p01'
  2111. OUTPUT:
  2112. SUM(QTY)
  2113. 4800
  2114. o) Get number of cities in which customers are based.
  2115. SQL> select count ( distinct ( cname ) ) from customer;
  2116. OUTPUT:
  2117. COUNT(DISTINCT(CNAME))
  2118. 4
  2119. p) Get total amount of all orders.
  2120. SQL> select sum(ordamount) from orders;
  2121. OUTPUT:
  2122. SUM(ORDAMOUNT)
  2123. 104598
  2124. q)Get total number of customers.
  2125. SQL> select count(cid) from customer;
  2126. OUTPUT:
  2127. COUNT(CID)
  2128. 5
  2129. r)Get average discount value for customers.
  2130. SQL> select avg(discount) from customer;
  2131. OUTPUT:
  2132. AVG(DISCOUNT)
  2133. 7.6
  2134. Database Applications Lab REVA University
  2135. School of Computing and Information Technology Page 65
  2136. s)Get agent ids with the smallest percent commission.
  2137. SQL> select aid from agent where percent in (select min(percent) from agent);
  2138. Or select aid from agent where percent= (select min(percent) from agent)
  2139. OUTPUT:
  2140. AID
  2141. a05
  2142. a06
  2143. t)Display the names of the customers who placed an order through the agent who is
  2144. having aid as “a01”
  2145. SQL>Select distinct(c.cname) from customer c , orders o where c.cid=o.cid and
  2146. o.aid=’a01’;
  2147. OUTPUT:
  2148. CNAME
  2149. Sobhit
  2150. Anand
  2151. u)Retrieve the names of the customers who live in “Mumbai” and order product “p01”
  2152. SQL> select cname from customer c , orders o where c.city='Mumbai' and c.cid=o.cid
  2153. and o.pid='p01';
  2154. OUTPUT:
  2155. CNAME
  2156. Anand
  2157. Anand
  2158. SQL> select distinct(cname) from customer c,orders o where c.city='Mumbai' and
  2159. c.cid=o.cid and o.pid='p01';
  2160. OUTPUT:
  2161. CNAME
  2162. Anand
  2163. Anand
  2164. v) Retrieve customer ids who do not order part “p01”
  2165. select cid from customer minus (select cid from orders where pid='p01') ;
  2166. or
  2167. select cid from customer minus ( select distinct (cid) from orders where pid='p01');
  2168. OUTPUT:
  2169. CID
  2170. c002
  2171. c003
  2172. Database Applications Lab REVA University
  2173. School of Computing and Information Technology Page 66
  2174. 10.Viva Voce Questions
  2175. 1) What is an RDBMS?
  2176. 2) What is the SQL?
  2177. 3) What are the different kinds of DBMS?
  2178. 4) What are the features of relational database?
  2179. 5) What are data types?
  2180. 6) What is an E-R diagram?
  2181. 7) What is the referential integrity?
  2182. 8) What is a foreign key?
  2183. 9) What is a primary key?
  2184. 10) What is an alternate key in table?
  2185. 11) What is the normalization?
  2186. 12) Explain the First Normal Form?
  2187. 13) Explain the Second Normal Form?
  2188. 14) Explain the Third Normal Form?
  2189. 15) What is an index, and how is it used to improve performance?
  2190. 16) What are the types of indexes, and if separate indexes are created on each
  2191. column of a table, what are the advantages and disadvantages of this
  2192. approach?
  2193. 17) What is the SQL Data Manipulation Language (DML)?
  2194. 18) What is the SQL Data Definition Language (DDL)?
  2195. 19) What is the de-normalization?
  2196. 20) What is a transaction?
  2197. 21) What are ACID properties?
  2198. 22) What is the difference between DELETE TABLE and TRUNCATE TABLE
  2199. commands?
  2200. 23) What are constraints?
  2201. 24) What are the different types of constraints?
  2202. 25) What are cursors? What are the different types of cursors?
  2203. 26) What are the advantages of cursors? How can you avoid cursors?
  2204. 27) What is a join and explain different types of joins.
  2205. 28) What is a self-join? Explain it with an example.
  2206. Database Applications Lab REVA University
  2207. School of Computing and Information Technology Page 67
  2208. 29) How do you implement one-to-one, one-to-many, many-to-many
  2209. relationships while designing tables?
  2210. 30) What is the difference between primary key and a unique key?
  2211. 31) What are defaults?
  2212. 32) What are triggers? How do you invoke a trigger on demand?
  2213. 33) What is a stored procedure? What are the advantages?
  2214. 34) What is the difference between stored procedure and a trigger?
  2215. 35) What are the different types of parameters available in stored procedures?
  2216. 36) How do you get the distinct rows in a table/ resultset?
  2217. 37) How do you get the distinct rows without using the keyword DISTINCT?
  2218. 38) How can you get the duplicated rows from the table using a single query?
  2219. 39) How can you get the total number of records in a table?
  2220. 40) How can you insert values in multiple rows using one insert statement?
  2221. 41) What is the database replication?
  2222. 42) What will happen when a Rollback statement is executed inside a Trigger?
  2223. Recommended Learning Resources:
  2224. 1. Raghu Ramakrishnan and Johannes Gehrke,Database Management Systems, 3rd
  2225. Edition, McGraw-Hill, 2003.
  2226. 2. Elmasri and Navathe,Fundamentals of Database Systems, 5th Edition, Pearson
  2227. Education, 2007.
  2228. 3. Abraham Silberschatz, Henry F. Korth, S. Sudarshan: Database System Concepts, 6th
  2229. Edition, McGraw Hill, 2010.
  2230. References:
  2231. 1. Christopher J Date, An Introduction to Database Systems
  2232. 2. J. D. Ullman, “Principles of Database Systems”
  2233. 3. Serge Abiteboul, Richard Hull and Victor Vianu ,“Foundations of Databases”
  2234. 4. Bipin C Desai, An Introduction to Database Systems
  2235. 5. Mark L Gillenson, Fundamentals of Database Management Systems
  2236. 6. Thomas Connolly and Carolyn Begg, Data base Solutions: A step by step Guide to
  2237. Building Data bases
  2238. 7. C J Date, Database Design and Relational Theory: Normal Forms and All that Jazz, O
  2239. ‘Reilly, April 2012.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement