lOMoARcPSD|9178016 Lab Manual-Database - Lab Manual Database Systems (COMSATS University Islamabad) StuDocu is not sponsored or endorsed by any college or university Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 LAB MANUAL Course: CSC271: Database Systems Department of Computer Science Database Learning Procedure J (Journey inside-out the concept) Stage a1 (Apply the learned) Stage v (Verify the accuracy) Stage a2 (Assess your work) 1) Stage 2) 3) 4) COMSATS Institute of Information Technology (CIIT) 1 Islamabad Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 Table of Contents Lab # Lab # 01 Lab # 02 Lab # 03 Lab # 04 Lab # 05 Lab # 06 Lab # 07 Lab # 08 Lab # 09 Lab # 10 Lab # 11 Lab # 12 Lab # 13 Lab # 14 Lab # 15 Lab # 16 Topics Covered Page # Oracle 11G and Oracle SQL Developer Installation, Using and understanding tool Relational Algebra – Generic Operations Generic Operations Introduction to SQL Select Statement usage SELECT Query Modifiers Query Modifiers (ORDER BY and LIMIT) Single Row Functions and Set Operators Single Row Functions,Set Operators and Type Conversions Lab Sessional 1 SQL Join Operations Join Operations SQL Outer/Inner Join Operations Outer/Inner Join Aggregation and Groups Aggregation Operations Sub Queries Sub Queries SQL as Data Manipulation Language DML Operations Lab Sessional 2 SQL as Data Definition Language DDL Operations Relational Database Design (Normalization) Normalization Entity-Relational Model and Diagram ERD DCL, TCL and Database Connectivity with Oracle/NoSQL DB DCL, TCL and Database Connectivity with Oracle/MongoDB Terminal Examination 2 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 LAB # 01 Statement Purpose: Data is a collection of raw facts and figures, processed to obtain useful information to assist organization in making decisions. Database is an organized collection of related data. In order to manage the databases, Database Management Systems (DBMS) or Database Systems offer sets of program and tools. Activity Outcomes: After performing this lab students should be able to: Connecting Oracle and SQL Developer Explore structure of tables in a database Retrieve data from the tables Change existing data in the database tables Instructor Note: As pre-lab activity, attend theory class. Tools/Software Requirement Oracle 11G SQL Developer 1) Stage J (Journey) Introduction Data is a collection of raw facts and figures, processed to obtain useful information to assist organization in making decisions. Database is an organized collection of related data. In order to manage the databases, Database Management Systems (DBMS) or Database Systems offer sets of program and tools. Oracle is a relational database as defined by Codd. A relational database uses relations or twodimensional tables to store data as shown in the following diagram: 3 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 we will use Oracle SQL Developer as a graphical tool to connect to our Oracle database. By default, it uses the Java Database Connectivity (JDBC) thin driver. You can also freely download the Oracle SQL Developer application from the Oracle website - see: http://www.oracle.com/technetwork/developer-tools/sql-developer The basic Oracle SQL Developer screen layout is shown below The most important regions of the SQL Developer window are highlighted: 1. The list of available database connections. Please note 1a. indicates which database the SQL commands you have entered will be executed in. 2. The SQL worksheet where SQL commands are entered. 3. The execute button, which allows you to run the SQL commands you have entered. 4. The results panels which show you the results of your SQL commands in different formats. 4 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 Figure 1: Schema of HR Stage a1 (apply) Lab Activities: Activity 1: 1. Step 1: Connect to the desired database, in the diagram the HR database is selected. Please note it will show the current database you are connected to. 2. Step 2: Enter your SQL statement. 3. Step 3: Click on the Run Script icon to execute your SQL statement. 4. Step 4: The results of your executed SQL statement. Solution: 5 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 Activity 2: 1. Go through the basic SQL developer screen layout 2. Go through the table structure of oracle using HR 3. See the concepts of primary key, foreign key, relationships Solution: 6 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 2) Stage v (verify) Home Activities: 3) Answer questions from the quiz. These questions assume you are connected with Oracle using Oracle SQL Developer. Stage a2 (assess) Lab Assignment and Viva voce Deliverable There is no deliverable for this lab. You only have to attempt a quiz designed around the lab task. 7 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 LAB # 02 Statement Purpose: Relational Algebra is a meta-language and forms underlying basis of SQL query language. It has six basic operators including: select, project, union, set difference, rename, and cross product. The operators take one or two relations as inputs and produce a new relation as a result. Activity Outcomes: After performing this lab students should be able to: 1. Implement relational algebra operations 2. Design query expressions by composing relational algebra operations 3. Retrieve data from a database using RA expressions Instructor Note: As pre-lab activity, attend theory class. Tools/Software Requirement SQL Lite/Any Other Database Sqlalchemy in case of other database Relational Algebra Interpreter RA(radb) (Duke University) https://users.cs.duke.edu/~junyang/radb/ 4) Stage J (Journey) Introduction Relational Algebra is a meta-language and forms underlying basis of SQL query language. It has six basic operators including: select, project, union, set difference, rename, and cross product. The operators take one or two relations as inputs and produce a new relation as a result. Stage a1 (apply) Lab Activities: Activity 1: 1. Check the requirements at https://users.cs.duke.edu/~junyang/radb/start.html and install on your system. We will use the interpreter to write relational algebra queries and submit these to Database/SQLite for retrieving required data. 2. Download beers.ra database in case of SQLite or use any other in case other databases. 3. To Install SQLite database in current director, issue following command. radb -i beers.ra beers.db 8 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 radb beers.db 4. At RA’s ra> prompt, you can list the relations in the sample database, try some relational algebra queries, and quit. \list; \select_{name like 'B%'} Beer; \quit; 5. If you want to use RA with a different database system, or to set it up such that you don’t need to type a long list of command-line arguments every time you run RA, then use configuration file to configure this. 6. The interpreter supports handful of relational algebra operations as listed in the following table. The interpreter uses a special syntax and the expression should end with semi-colon symbol. Examples are presented in the next table. Focus on first two operations. 7. You can start your experiment with the given relational algebra expressions. 8. Continue playing with the interpreter till you are comfortable with the querying syntax and mechanism. Solution: Operation Syntax and Description SELECT \select_{CONDITION} EXPRESSION Selection over an expression PROJECT \project_{ATTRIBUTE_LIST} EXPRESSION Projection on selected attributes RENAME \rename_{NEW_ATTRIBUTE_NAME_LIST} EXPRESSION Rename all attributes of an expression UNION EXPRESSION_1 \union EXPRESSION_2 Union between two expressions DIFFERENCE EXPRESSION_1 \diff EXPRESSION_2 Difference between two expressions INTERSECT EXPRESSION_1 \intersect EXPRESSION_2 Intersection between two expressions CROSS PRODUCT EXPRESSION_1 \cross EXPRESSION_2 JOIN EXPRESSION_1 \join EXPRESSION_2 Cross-product between two expressions Natural join between two expressions; The interpreter literally follows the rules for cross product that column names must be unique from both sides. Don't forget to apply rename operation if after cross 9 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 product two columns with same name may appear in the schema. 1. You can start your experiment with the given relational algebra expressions. Information Need Expression in Interpreter Syntax Few Queries from Beer.ra \project_{beer} ( ((\project_{name} // all drinkers Drinker) \diff (\rename_{name} \project_{drinker} // rename so we can diff // drinkers who frequent JJP \select_{bar = 'James Joyce Pub'} Frequents)) \join_{drinker = name} /* join with Likes to find beers */ Likes ); Renaming \rename_{s1} Serves \join_{s1.beer=s2.beer and s1.price>s2.price} \rename_{s2} Serves; Cross Join Drinker \join_{Drinker.name=Frequents.drinker} Frequents; Theta Join Drinker \join_{Drinker.name=Frequents.drinker} Frequents; 2. Continue playing with the interpreter till you are comfortable with the querying syntax and mechanism. Activity 2: 1. Write relational algebra expression for the following Schema. First implement in the database whatever you select(SQLite,MySQL,ORACLE etc). Write their corresponding expressions in the interpreter syntax as well. Suppliers(sid: integer, sname: string, address: string) Parts(pid: integer, pname: string, color: string) Catalog(sid: integer, pid: integer, cost: real) 2. Store all expressions in a plain text file. 10 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 3. Information needs: (a) Find the names of suppliers who supply some red part. (b) Find the sids of suppliers who supply some red or green part. (c) Find the sids of suppliers who supply some red part or are at 221 Packer Ave. (d) Find the sids of suppliers who supply some red part and some green part. (e) Find the sids of suppliers who supply every part. (f) Find the sids of suppliers who supply every red part. (g) Find the sids of suppliers who supply every red or green part. (h) Find the sids of suppliers who supply every red part or supply every green part. (i) Find pairs of sids such that the supplier with the first sid charges more for some part than the supplier with the second sid. (j) Find the pids of parts that are supplied by at least two different suppliers. (k) Find the pids of the most expensive parts supplied by suppliers named Yosemite Sham. (l) Find the pids of parts supplied by every supplier at less than $200. (If any supplier either does not supply the part or charges more than $200 for it, the part is not selected.) Solution: Submit a PDF document including the relational algebra expressions in the interpreter syntax to answer above-mentioned information needs as well as snapshot of their outcome when executed on the interpreter. 5) Stage v (verify) Home Activities: 6) Answer questions from the task. These questions assume Sakila database hasn’t changed. Stage a2 (assess) Lab Assignment and Viva voce Deliverable Submit a PDF document including the relational algebra expressions in the interpreter syntax to answer above-mentioned information needs as well as snapshot of their outcome when executed on the interpreter. 11 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 LAB # 03 Statement Purpose: Structured Query Language (SQL) was developed at IBM San Jose Research Laboratory as a part of System R project. It is a declarative query language for querying a relational database. It also includes features for defining the structure of the data, for inserting and modifying data in the database, and for specifying security constraints. It is relational complete (it supports all six core relational algebra operations). SQL commands can be classified into three groups out of which we are going to practice commands that query a database, called Data Manipulation Language (DML). Activity Outcomes: After performing this lab students should be able to: 1. Design SQL queries to retrieve data using SELECT clause and various associated operators. 2. Translate relational algebra expressions to SQL queries. 3. Execute SQL queries over Oracle using SQL Developer. Instructor Note: As pre-lab activity, attend theory class. Tools/Software Requirement Oracle 11G SQL Developer 7) Stage J (Journey) Introduction Structured Query Language (SQL) was developed at IBM San Jose Research Laboratory as a part of System R project. It is a declarative query language for querying a relational database. It also includes features for defining the structure of the data, for inserting and modifying data in the database, and for specifying security constraints. It is relational complete (it supports all six core relational algebra operations). SQL commands can be classified into three groups out of which we are going to practice commands that query a database, called Data Manipulation Language (DML). Stage a1 (apply) Lab Activities: 12 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 Activity 1: 1. This lab assumes that Oracle is running and you have connected it using SQL Developer. 2. Open SQL Developer and establish the connection instance. 3. The database used in this lab is HR database. 4. A new query window would open from where you can write and execute queries. 5. You can save the query file. 6. On executing queries, results are displayed in the lower part of the screen. 7. Error or success messages are displayed in action output pane at the bottom. 8. Try running few SQL queries modeled during the lectures to get it going. 9. Continue playing with the SQL Developer and SQL queries till you are comfortable with the querying mechanism and have learnt the shortcuts to execute queries. 10. You can enter “SELECT * FROM employees;” in the SQL Worksheet (1) and click on the Run Script icon (2) as shown in below figure 11. Instead of selecting all columns, you can select, say, one column from the table as shown below Solution: Activity 2: 13 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 1. Write SQL queries for the following information needs. You should execute your attempt and make necessary corrections if needed. 2. Information needs: a. Display the structure of the table using query. b. Use Colomn Alias to remain Employee_id as Employee, Last_ Name as “Sur Name” and First_Name as First Name c. Instead of retrieving all 107 rows from employees table for all job ids, find only distinct job ids d. Show First_Name and Last_Name of Employee after concatenation of Both name as “Name” e. Display the yearly salary of employees. Solution: A: B: SELECT employee_id AS Employee, employee_id AS "Employee Id", last_name Surname, first_name "First Name" FROM employees; 14 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 C: 8) Stage v (verify) Home Activities: 9) The HR department wants a query to display the last name, job ID, hire date, and employee ID for each employee, with the employee ID appearing first. Provide an alias STARTDATE for the HIRE_DATE column. The HR department has requested a report of all employees and their job IDs. Display the last name concatenated with the job ID (separated by a comma and space) and name the column Employee and Title. To familiarize yourself with the data in the EMPLOYEES table, create a query to display all the data from that table. Separate each column output by a comma. Name the column title THE_OUTPUT. Stage a2 (assess) Lab Assignment and Viva voce Deliverable Submit a PDF document including the SQL queries to answer above-mentioned information needs as well as snapshot of their outcome when executed over SQL Developer using Oracle. 15 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 LAB # 04 Statement Purpose: WHERE clause and query modifiers (ORDER BY and LIMIT) are critical to retrieve required information for a given information need. These clauses form very commonly used in SELECT type of queries Activity Outcomes: After performing this lab students should be able to: 1. Design SQL queries to retrieve data using WHERE clause and various associated query modifiers. 2. Design SQL queries using Comparison and Logical operator Instructor Note: As pre-lab activity, attend theory class. Tools/Software Requirement Oracle 11G SQL Developer 10) Stage J (Journey) Introduction WHERE clause and query modifiers (ORDER BY and LIMIT) are critical to retrieve required information for a given information need. These clauses form very commonly used in SELECT type of queries. Moreover, Comparison and logical operators will be used. Comparison Operators are: 16 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 There are three logical operators. AND – both conditions must be true – o If A=B is true AND C=D is true, then the condition is true. OR – at least one condition must be true – o Either A=B is true OR C=D is true, then the condition is true. NOT – reverses of the ‘initial result’ – o If A=B is true, then NOT(A=B) becomes false Stage a1 (apply) Lab Activities: Activity 1: 1. This lab assumes that Oracle is running and you have connected it using SQL Developer. 2. Open SQL Developer and establish the connection instance. 3. The database used in this lab is HR database. 4. A new query window would open from where you can write and execute queries. 5. You can save the query file. 6. On executing queries, results are displayed in the lower part of the screen. 7. Error or success messages are displayed in action output pane at the bottom. 8. you can define a condition to retrieve rows from a table. SELECT column_name, column_name … FROM table_name 17 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 WHERE (condition); Solution: Activity 2: 1. Write SQL queries for the following information needs. You should execute your attempt and make necessary corrections if needed. 2. Information needs: a. Display the first Name, Last Name and salary of employees having salary greater than 10000. b. Display the first Name, Last Name and salary of employees having salary greater than 10000 and smaller than 110000 c. Display the postal code, location and country where postal code is “YSW 9T2”. d. Display the employee ID, First Name, Last Name of Employees whose first name is equal to or greater to ‘King’ and last name is smaller or equal to ‘Lee’. e. Display the employee name and hiring information whose hire date is after 8 March 2008. f. Display Employee’s last name, manager id and hire date in an ascending order of manager id and hire date. Solution: A: 18 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 B: C: 19 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 D: E: F: 20 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 11) Stage v (verify) Home Activities: Create a report that displays the last name and department number for employee number 176. The HR department needs to find high-salary and low-salary employees. Display the last name and salary for any employee whose salary is not in the range of $5,000 to $12,000. Create a report to display the last name, job ID, and hire date for employees with the last names of Matos and Taylor. Order the query in ascending order by the hire date. Display the last name and department ID of all employees in departments 20 or 50 in ascending alphabetical order by name. Create a report to display the last name and job title of all employees who do not have a manager. Create a report to display the last name, salary, and commission of all employees who earn commissions. Sort data in descending order of salary and commissions. Use the column‘s numeric position in the ORDER BY clause. The HR department wants to run reports based on a manager. Create a query that prompts the user for a manager ID and generates the employee ID, last name, salary, and department for that manager‘s employees. The HR department wants the ability to sort the report on a selected column. You can test the data with the following values: manager_id=103, sorted by last_name, manager_id = 201, sorted by salary, manager_id = 124, sorted by employee_id. Display the last names of all employees who have both an “a” and an “e” in their last name. Display the last name, job, and salary for all employees whose jobs are either those of a sales representative or of a stock clerk, and whose salaries are not equal to $2,500, $3,500, or $7,000. 21 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 12) Stage a2 (assess) Lab Assignment and Viva voce Deliverable Submit a PDF document including the SQL queries to answer above-mentioned information needs as well as snapshot of their outcome when executed in SQL Developer using Oracle 11G. 22 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 LAB # 05 Statement Purpose: Oracle contains strong methods for Set Operators, Single row functions and type conversion functions. It enables users to change combine queries, some special implementation of methods and to convert type of data at run time. Activity Outcomes: After performing this lab students should be able to: Implement Single row functions and will use character, number, and date functions in SELECT statements Use a set operator to combine multiple queries into a single query. Implement type conversion methods. Instructor Note: As pre-lab activity, attend theory class. Tools/Software Requirement Oracle 11G SQL Developer for Oracle HR Database 13) Stage J (Journey) Introduction We will cover three concepts in it. First one is single row function. These functions operate on single rows only and return one result per row. There are different types of single-row functions. These are Character, Number, Date, Conversion and General type. Character functions: Accept character input and can return both character and number values. Number functions: Accept numeric input and return numeric values. Date functions: Operate on values of the DATE data type (All date functions return a value of the DATE data type except the MONTHS_BETWEEN function, which returns a number.) Second is type conversion functions. Such functions that convert data from one type to another (for example, conversion from character data to numeric data). Third is set operators. Set operators combine the results of two or more component queries into one result. Queries containing set operators are called compound queries. 23 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 Stage a1 (apply) Lab Activities: Single Row Functions Activity 1: 1. Convert the last name in Upper, lower and email in sentence style for employee whose last name is King. 2. Display first Name, first three characters of first name, total characters of first name, display 10 digits salary padding before, then padding after salary for total of 10 digits for King as Last Name. 3. Display Commission_pct*100 after rounding of -1,0 and 1. 4. Display Commission_pct*100 after truncating of -1,0 and 1. 5. Display use of ABS and power functions in query 6. calculate how many years (approx.) the employees have been working in the company? 7. Use NVL and NVL2, NULL IF and NULL First in Query. 8. Convert Data types from number to character and dates etc using conversion functions. 9. Use the Conditional functions such as CASE IFTHENELSE and DECODE. 10. Use Set Operators such as Union, UnionALL, Intersect and minus in two queries and display the results. 24 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 Solution: 1. 2. 3,4. 25 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 5. 6. 7. 26 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 27 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 8. 9. 28 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 10. 29 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 Activity 2: 1. Execute all statements in SQL Developer. Take the screenshots and put in word/PDF file. 2. Information needs: a. The HR department needs a report to display the employee number, last name, salary, and salary increased by 15.5% (expressed as a whole number) for each employee. Label the column New Salary. b. Write a query that displays the last name (with the first letter in uppercase and all the other letters in lowercase) and the length of the last name for all employees whose name starts with the letters “J”,”A”, or “M”. Give each column an appropriate label. Sort the results by the employees ‘last names. Rewrite the query so that the user is prompted to enter a letter that the last name starts with. For example, if the user enters ―H‖ (capitalized) when prompted for a letter, then the output should show all employees whose last name starts with the letter ―H. c. The HR department wants to find the duration of employment for each employee. For each employee, display the last name and calculate the number of months between today and the date on which the employee was hired. Label the column as MONTHS_WORKED. Order your results by the number of months employed. Round the number of months up to the closest whole number. d. Create a query that displays the employees‘ last names and commission amounts. If an employee does not earn commission, show ―No Commission.‖ Label the column COMM. e. The HR department needs a list of countries that have no departments located in them. Display the country ID and the name of the countries. Use the set operators to create this report. f. The HR department needs a report with the following specifications: • Last name and department ID of all employees from the EMPLOYEES table, regardless of whether or not they belong to a department • Department ID and department name of all departments from the DEPARTMENTS table, regardless of whether or not they have employees working in them Write a compound query to accomplish this. Solution: Submit a PDF document including the screenshots and query. 14) Stage v (verify) Home Activities: Using the Case function, write a query that displays the grade of all employees based on the value of the column JOB_ID, using the following data: Job Grade 30 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 AD_PRES ST_MAN IT_PROG SA_REP A B C D. Display the last name, hire date, and day of the week on which the employee started. Label the column DAY. Order the results by the day of the week, starting with Monday. Display each employee‘s last name, hire date, and salary review date, which is the first Monday after six months of service. Label the column REVIEW. Format the dates to appear in the format similar to ―Monday, the Thirty-First of July, 2000. The HR department needs a list of department IDs for departments that do not contain the job ID ST_CLERK. Use the set operators to create this report. Produce a list of jobs for departments 10, 50, and 20, in that order. Display the job ID and department ID by using the set operators. 1. Create a report that lists the employee IDs and job IDs of those employees who currently have a job title that is the same as their job title when they were initially hired by the company (that is, they changed jobs but have now gone back to doing their original job). 15) Stage a2 (assess) Lab Assignment and Viva voce Deliverable Submit your PDF on portal after completing the tasks 31 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 LAB # 07 Statement Purpose: A SQL join clause combines records from two or more tables in a database. It creates a set that can be saved as a table or used as it is. A JOIN is a means for combining fields from two tables by using values common to each. You will be able to identify a Cartesian join; create equality and non-equality joins; create a self-join; and distinguish an inner join from an outer join. Activity Outcomes: After performing this lab students should be able to: 1. Design SQL queries to retrieve data from multiple tables by using JOIN operation. Instructor Note: As pre-lab activity, attend theory class. Tools/Software Requirement Oracle 11G SQL Developer 16) Stage J (Journey) Introduction Data is a collection of raw facts and figures, processed to obtain useful information to assist organization in making decisions. Database is an organized collection of related data. In order to manage the databases, Database Management Systems (DBMS) or Database Systems offer sets of program and tools. You will be able to identify a Cartesian join; create equality and non-equality joins; create a self-join; and distinguish an inner join from an outer join. Stage a1 (apply) Lab Activities: Activity 1: 1. This lab assumes that you have connected to Oracle 11G with HR user using SQL Developer. 2. Try running following SQL query. 32 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 a. Create different joins (ANSI and where conditional). Solution: SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE e.department_id = d.department_id; Activity 2: 1. Write SQL queries for the following information needs. You should execute your attempt and make necessary corrections if needed. 2. Information needs: a. Link employee and department using ‘using’ clause. b. Make a natural join of employees and department tables. c. Join employee and department table where department ID is 90 Solution: A: 33 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 B: C: 34 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 17) Stage v (verify) Home Activities: Write a query for the HR department to produce the addresses of all the departments. Use the LOCATIONS and COUNTRIES tables. Show the location ID, street address, city, state or province, and country in the output. Use a NATURAL JOIN to produce the results. The HR department needs a report of all employees. Write a query to display the last name, department number, and department name for all the employees. The HR department needs a report of employees in Toronto. Display the last name, job, department number, and the department name for all employees who work in Toronto. 18) Stage a2 (assess) Lab Assignment and Viva voce Deliverable Submit a PDF document including the SQL queries to answer above-mentioned information needs as well as snapshot of their outcome when executed in SQL Developer and Oracle 11G as dababase. 35 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 LAB # 08 Statement Purpose: A SQL join clause combines records from two or more tables in a database. It creates a set that can be saved as a table or used as it is. A JOIN is a means for combining fields from two tables by using values common to each. Cartesian Joins Cartesian Joins are created by omitting joining condition in the WHERE clause or through CROSS JOIN keywords in the FROM clause. This creates a result of every possible row combination (m*n). Equality Joins You can link rows through equivalent data that exists in both tables. This is created through creating equivalency condition in the WHERE clause and using NATURAL JOIN, JOIN…USING, or JOIN…ON keywords in the FROM clause. Non-equality Joins A non-equality join is when you use any other comparison operators other than the equal sign in the WHERE clause. Another instance is when you use JOIN…ON clause in the FROM clause for a non-equivalent condition. Activity Outcomes: After performing this lab students should be able to: 1. Design SQL queries to retrieve data from multiple tables by using JOIN operation. 2. Select among INNER, OUTER, NATURAL and theta join as and when required. Instructor Note: As pre-lab activity, attend theory class. Tools/Software Requirement Oracle 11G SQL Developer 19) Stage J (Journey) Introduction A SQL join clause combines records from two or more tables in a database. It creates a set that can be saved as a table or used as it is. A JOIN is a means for combining fields from two tables by using values common to each. 36 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 Stage a1 (apply) Lab Activities: Activity 1: 1. This lab assumes that Oracle is connected through SQL Developer, and the query window is open. 2. Try running following SQL query. a. Display a cross product of regions and country. b. Display all the employees along with manager’s name. Also, include the employee who have no manager. Solution: Activity 2: 37 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 1. Write SQL queries for the following information needs. You should execute your attempt on Oracle SQL Developer and make necessary corrections if needed before submission. 2. Information needs: a. Display the manager name whose employee id is 103. b. Display name, location, city, department information where department id is between 80 and 90. c. Display employee’s job history for every job in the department Solution: A: B: C: 38 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 20) Stage v (verify) Home Activities: Create a report to display employee’s last name and employee number along with their manager’s last name and manager number. Label the columns Employee, Emp#, Manager, and Mgr#, respectively. Create a report for the HR department that displays employee last names, department numbers, and all the employees who work in the same department as a given employee. Give each column an appropriate label. The HR department needs to find the names and hire dates of all the employees who were hired before their managers, along with their manager’s names and hire dates. 21) Stage a2 (assess) Lab Assignment and Viva voce Deliverable Submit a PDF document including the SQL queries to answer above-mentioned information needs as well as snapshot of their outcome when executed in SQL Developer. 39 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 LAB # 09 Statement Purpose: Aggregate functions operate on the multi-set of values from a column of a relation and return a consolidated value. This achieves scalar aggregation. Sometimes, we want to apply aggregation to each of several groups of records to achieve vector aggregation. Activity Outcomes: After performing this lab students should be able to: 1. Design SQL queries to retrieve consolidated data by applying aggregate functions. 2. Implement grouping in the SQL queries and use it in combination with WHERE, JOIN and other clauses. Instructor Note: As pre-lab activity, attend theory class. Tools/Software Requirement Oracle 11G SQL Developer 22) Stage J (Journey) Introduction Aggregate functions operate on the multi-set of values from a column of a relation and return a consolidated value. This achieves scalar aggregation. Sometimes, we want to apply aggregation to each of several groups of records to achieve vector aggregation. These functions will return one result per group. The multiple-row functions covered include SUM, AVG, MIN and MAX. You will learn to use the COUNT function to return records containing non-NULL values, or records containing NULL values. We will also cover the GROUP BY and HAVING clauses. Stage a1 (apply) Lab Activities: Activity 1: 1. This lab assumes that Oracle is running and SQL Developer is connected with HR user, and the query window is open. 2. Try running following SQL queries discussed during the lecture. 3. List accumulative payments per customer in descending order of the amount. The following command will spit out customer id and sum of all amounts paid for rentals. 40 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 a. select customer_id, sum(amount) as sum_amount from payment group by customer_id order by sum_amount desc; b. Note: the renamed attribute can NOT be referred in where clause but it may be referred in order by because select clause and hence the rename is executed after where and having clauses. Solution: Activity 2: 4. Write SQL queries for the following information needs. You should execute your attempt and make necessary corrections if needed. 5. Information needs: a. Display the longest serving member of the company as well as who has recently joined. b. Display total number of managers having employees reporting to them. c. Display each department, its number of employees, minimum, maximum and average salaries. d. Display country id, each department, its number of employees, minimum, maximum and average salaries greater than 5000. Group them by country then department. Solution: A: 41 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 B: C: D: 42 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 Stage v (verify) Home Activities: Find the highest, lowest, sum, and average salary of all employees. Label the columns as Maximum, Minimum, Sum, and Average, respectively. Round your results to the nearest whole number. Write a query to display the number of people with the same job. Determine the number of managers without listing them. Label the column as Number of Managers. Find the difference between the highest and lowest salaries. Label the column DIFFERENCE. Create a report to display the manager number and the salary of the lowest-paid employee for that manager. Exclude anyone whose manager is not known. Exclude any groups where the minimum salary is $6,000 or less. Sort the output in descending order of salary. Create a matrix query to display the job, the salary for that job based on department number, and the total salary for that job, for departments 20, 50, 80, and 90, giving each column an appropriate heading. 23) Stage a2 (assess) 43 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 Lab Assignment and Viva voce Deliverable Submit a PDF document including the SQL queries to answer above-mentioned information needs as well as snapshot of their outcome when executed using SQL Developer. 44 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 LAB # 10 Statement Purpose: SQL provides a mechanism for the nesting of sub-queries. A sub-query is a select-from-where expression that is nested within another query. It can be used in a condition of the WHERE clause or within the HAVING clause (e.g. for set membership) or as a “table” of the FROM clause. Activity Outcomes: After performing this lab students should be able to: 1. Design SQL queries to retrieve consolidated data by using sub-queries. 2. Implement correlated and non-correlated sub-queries using various clauses such as SOME, ALL, EXISTS, EXCEPT, and UNIQUE. Instructor Note: As pre-lab activity, attend theory class. Tools/Software Requirement Oracle 11G SQL Developer 24) Stage J (Journey) Introduction SQL provides a mechanism for the nesting of sub-queries. A sub-query is a select-from-where expression that is nested within another query. It can be used in a condition of the WHERE clause or within the HAVING clause (e.g. for set membership) or as a “table” of the FROM clause. Sub Query can be of 5 types: Stage a1 (apply) 45 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 Lab Activities: Activity 1: 1. This lab assumes that Oracle is connected using SQL Developer with user HR, and the query window is open. 2. Try running following SQL queries. 3. Try to run all five types of nested queries (sub queries) Solution: Single Row Sub query Multiple Row Sub query 46 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 Multiple Column Sub query: Nested Subquery 47 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 Correlated Subquery: Activity 2: 1. Write SQL queries for the following information needs. You should execute your attempt and make necessary corrections if needed. You are expected to provide two versions of the queries: one that uses sub-queries constructs and the other that doesn’t. In case the second query cannot be implemented, explain the reason. 2. Information needs: a. Find all the department whose average salary is greater than of the average salary of department 80. b. Find Employees with salary greater than all employees in department 110. c. Find Employees with salary greater than any of the employees in department 110. d. Identify the employees whose salary is exactly same as the average salary of the department. 48 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 e. Display all the locations that are not used by departments yet. Solution: A: B: 49 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 C: D: E: 50 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 25) Stage v (verify) Home Activities: The HR department needs a query that prompts the user for an employee last name. The query then displays the last name and hire date of any employee in the same department as the employee whose name they supply (excluding that employee). For example, if the user enters Zlotkey, find all employees who work with Zlotkey (excluding Zlotkey). Create a report that displays the employee number, last name, and salary of all employees who earn more than the average salary. Sort the results in order of ascending salary. Create a report for HR that displays the department number, last name, and job ID for every employee in the Executive department. Create a report for HR that displays the last name and salary of every employee who reports to King. 26) Stage a2 (assess) Lab Assignment and Viva voce Deliverable Submit a PDF document including the SQL queries to answer above-mentioned information needs as well as snapshot of their outcome when executed over Oracle using SQL Developer. 51 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 LAB # 11 Statement Purpose: SQL Insert, Update and Delete operations are expressed using the assignment operator for two or more tables in a database. It uses a set that can be saved as a table or used as it is. Activity Outcomes: After performing this lab students should be able to: 1. Design SQL queries to Insert, Update and Delete and retrieve data from multiple tables by using assignment operator. Instructor Note: As pre-lab activity, attend theory class. Tools/Software Requirement Oracle 11G SQL Developer 27) Stage J (Journey) Introduction SQL Insert, Update and Delete operations are expressed using the assignment operator for two or more tables in a database. It uses a set that can be saved as a table or used as it is. Stage a1 (apply) Lab Activities: Activity 1: 1. This lab assumes that you are connected to Oracle using SQL Developer, and the query window is open. 2. Try to insert, update or delete one record from any table of the database. Solution: Insert: 52 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 Update Delete: 53 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 Activity 2: 1. Write SQL queries for the following information needs. You should execute your attempt and make necessary corrections if needed. 2. Information needs: 3. At least 4 Queries for Each of Following: a. Insert New Department and Employee Records. b. Update Department Location Table using conditional Logic. c. Delete Records of all employees having no reference in any department. d. Roll back all changes you make. Solution: 54 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 55 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 28) Stage v (verify) Home Activities: Use a table same as employee and add, remove and update values. 29) Stage a2 (assess) Lab Assignment and Viva voce Deliverable Submit a PDF document including the SQL queries to answer above-mentioned information needs as well as snapshot of their outcome when executed over Oracle using the SQL Developer. 56 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 LAB # 13 Statement Purpose: SQL provides a subset of commands, known as data definition language (DDL), for defining new database schema. This subset includes CREATE TABLE command to define data structure for a new table, its columns and domains. Activity Outcomes: After performing this lab students should be able to: 1. Create database schema and create relation schemas using CREATE SCHEMA and CREATE TABLE command. 2. Understand the differences between different SQL data-types and chose an appropriate type in a given situation. Instructor Note: As pre-lab activity, attend theory class. Tools/Software Requirement Oracle 11G SQL Developer 30) Stage J (Journey) Introduction SQL provides a subset of commands, known as data definition language (DDL), for defining new database schema. This subset includes CREATE TABLE command to define data structure for a new table, its columns and domains. You must have a CREATE TABLE privilege Allow to access to a storage area Table and column names: Can contain a maximum 30 characters – no blank spaces Must begin with a letter Can contain numbers, underscore (_), and number sign (#) Must be unique No reserved words are allowed Column definition list must be enclosed in parentheses Datatype must be specified for each column 57 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 Maximum of 1,000 columns per table Stage a1 (apply) Lab Activities: Activity 1: 1. This lab assumes that Oracle is up and running and connected with SQL Developer. 2. Create table departments_history to keep track changes of department name.. Solution: Activity 2: 1. Create a table using employee table having same structure. 2. Do following modifications a. Add a new column in it b. Remove a column c. Change the type of a column 3. Rename the table 4. Drop the table Solution: 1: 58 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 2: 3: RENAME employees_history TO employees_hist_2017; 4: DROP TABLE employees_hist_2017; 59 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 31) Stage v (verify) Home Activities: Populate the DEPT table with data from the DEPARTMENTS table. Include only columns that you need. Create the EMPLOYEES2 table based on the structure of the EMPLOYEES table. Include only the EMPLOYEE_ID, FIRST_NAME, LAST_NAME, SALARY, and DEPARTMENT_ID columns. Name the columns in your new table ID, FIRST_NAME, LAST_NAME, SALARY, and DEPT_ID, respectively. Insert one row in Employees2 Drop table Employees2 32) Stage a2 (assess) Lab Assignment and Viva voce Deliverable Submit a PDF or plain-text document including the SQL queries to implement the database in Oracle using SQL Developer. 60 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 LAB # 15 Statement Purpose: The goal of relational database design is to generate a set of relational schemas that allows us to store information without unnecessary redundancy, yet also allows us to retrieve information easily. This is accomplished by designing schemas that are in an appropriate normal form. Activity Outcomes: After performing this lab students should be able to: 1. 2. 3. 4. Identify functional dependencies in a relation. Identify if a relation is in BCNF (and 3NF) or not. Decompose a relation to achieve BCNF. Create database schema from the design of relations. Instructor Note: As pre-lab activity, attend theory class. Tools/Software Requirement Oracle 11 G SQL Developer 33) Stage J (Journey) Introduction The goal of relational database design is to generate a set of relational schemas that allows us to store information without unnecessary redundancy, yet also allows us to retrieve information easily. This is accomplished by designing schemas that are in an appropriate normal form. Stage a1 (apply) Lab Activities: Activity 1: 1. This lab assumes that Oracle is running and the query window is open. 2. Carefully, study and analyze the following data table and perform the tasks mentioned below. 1. Convert this data to 1NF,2NF,3NF and BCNF 61 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 Solution: Following step by step identification Activity 2: 1. Identify the information items that should be recorded in a database. Outcome of this task is a list of attributes. Make sure that attribute domains are atomic. 2. Assuming the list of attributes as a single large relation, identify functional dependencies in the relation and also find closure set. 3. Based on the studied rules for lossless decomposition, translate the large relation into BCNF. 4. Use DDL to create the relation schema in MySQL. Choose an appropriate domain for each attribute and an appropriate primary key (and foreign key) for each relation. 5. Use DML to record all necessary information from the given sheet into the newly created database. Solution: Following step by step identification 34) Stage v (verify) Home Activities: Answer questions from the task. 35) Stage a2 (assess) Lab Assignment and Viva voce Deliverable Submit a PDF or plain-text document including the SQL queries to implement the database in Oracle using SQL Developer. 62 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 LAB # 15 Statement Purpose: The goal of relational database design is to generate a set of relational schemas that allows us to store information without unnecessary redundancy, yet also allows us to retrieve information easily. ERWin tool will be used to design Activity Outcomes: After performing this lab students should be able to: 1. Identify relations and associations given a case study or scenario. 2. Design and develop an E-R model using E-R Diagram notations. Instructor Note: As pre-lab activity, attend theory class. Tools/Software Requirement Oracle 11G 63 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 SQL Developer ERWin 36) Stage J (Journey) Introduction The goal of relational database design is to generate a set of relational schemas that allows us to store information without unnecessary redundancy, yet also allows us to retrieve information easily. ERWin supports three model types for use by the database designer: 1. Logical: A conceptual model that includes entities, relationships, and attributes. This model type is essentially at the ER modeling level. 2. Physical: A database specific model that contains relational tables, columns and associated data types. 3. Logical/Physical: A single model that includes both the conceptual level objects as well as physical level tables. Stage a1 (apply) Lab Activities: Activity 1: To create a model in ERWin, one should launch the program and then choose the “New” option from the File menu. The Create Model dialog appears. To add an entity type to the database design, the user may either right click the “Entities” entry in the model explorer pane and choose “New” or choose the “Entity” icon in the Menus and Toolbars section of the workspace and click in the diagram window panel. 64 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 To add attributes to the EMPLOYEE entity type, the user may right click within the EMPLOYEE entity box in the diagram window panel and choose “Attributes”. This brings up a separate window using which new attributes may be added. The user may choose an appropriate Domain (data type) and enter the Attribute Name and click OK. The data type may be further refined in the Attribute Window by choosing the Datatype tab and entering a precise data type. The user may also choose to designate this attribute as a primary key by selecting this option in the Attribute window. 65 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 To add a relationship, the user may simply right click the Relationships entry in the model explorer pane and choose “New”. This pops up a new relationship window. Solution: 66 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 Activity 2: 1. Draw an ERD for the following situation using ERWin. a. Deewan Engineering is an auto-parts manufacturing firm with approximately 500 employees. A database is required to keep track of all employees, their skills, projects assigned, and departments worked in. Every employee has a unique number assigned by the firm and is required to store his or her name and date of birth. If an employee is currently married to another employee of Deewan, the date of marriage and who is married to whom must be stored; however, no record of marriage is required if an employee’s spouse is not also an employee. Each employee is given a job title (e.g., engineer, secretary, and so on). An employee does only one type of job at any given time, and we only need to retain information for an employee’s current job. b. There are 11 different departments, each with a unique name. An employee can report to only one department. Each department has a phone number. c. To procure various kinds of equipment, each department deals with many vendors. A vendor typically supplies equipment to many departments. We are required to store the name and address of each vendor and the date of the last meeting between a department and a vendor. d. Many employees can work on a project. An employee can work on many projects (e.g., Atlas Honda, Indus Motors, and so on) but can only be assigned to at most one project in a given city. For each city, we are interested in its name and population. An employee can have many skills (preparing material requisitions, checking drawings, and so on), but she or he may use only a given set of skills on a particular project. (For example, an employee Mumtaz may prepare requisitions for the newly acquired Indus Motors project and prepare requisitions as well as check drawings for manufacturing bumpers of new City for Atlas Honda.) Employees use each skill that they possess in at least one project. Each skill is assigned a number, and we must store a short description of each skill. Projects are distinguished by project numbers, and we must store the estimated cost of each project. 2. Normalize the model into 3BNF and adjust the entities in the ERD. 3. Finally, generate the database schema from the normalized model. Solution: Figure 2: Example of EERD Relationship 67 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 37) Stage v (verify) Home Activities: Draw complete conceptual, logical and physical ERD then enhance it to EERD by showing each and every step. 38) Stage a2 (assess) Lab Assignment and Viva voce Deliverable Submit a PDF or Docx file containing the model using ERWin 68 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 LAB # 16 Statement Purpose: In this lab, we will cover three concepts. First, we will go through Data Control Language. Then we will cover Transactional Control Language. Then at the end we will cover database connectivity of Oracle and Mongo DB with JAVA to understand the application development procedure Activity Outcomes: After performing this lab students should be able to: 1. Implement Commit, rollback and save point of TCL. 2. Implement Grant, Revoke and create commands of DCL. 3. Implement connectivity and data access from oracle and mongo DB from java. Instructor Note: As pre-lab activity, attend theory class. Tools/Software Requirement Oracle 11 G Mongo DB SQL Developer Net Beans Java 39) Stage J (Journey) Introduction TRANSATIONAL CONTROL LANGUAGE (T.C.L): A transaction is a logical unit of work. All changes made to the database can be referred to as a transaction. Transaction changes can be mode permanent to the database only if they are committed a transaction begins with an executable SQL statement & ends explicitly with either role back or commit statement. 1. COMMIT: This command is used to end a transaction only with the help of the commit command transaction changes can be made permanent to the database. 2. SAVE POINT: Save points are like marks to divide a very lengthy transaction to smaller once. They are used to identify a point in a transaction to which we can latter role back. Thus, save point is used in conjunction with role back. 3. ROLE BACK: A role back command is used to undo the current transactions. We can role back the entire transaction so that all changes made by SQL statements are undo (or) role back a transaction to a save point so that the SQL statements after the save point are role back. 69 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 Data Control Language: (DCL) The DCL language is used for controlling the access to the table and hence securing the database. DCL is used to provide certain privileges to a particular user. Privileges are rights to be allocated. The privilege commands are namely, Grant and Revoke. The various privileges that can be granted or revoked are, Select Insert Delete Update References Execute All. GRANT: The GRANT command allows granting various privileges to other users and allowing them to perform operations with in their privileges For Example, if a uses is granted as ‘SELECT’ privilege then he/she can only view data but cannot perform any other DML operations on the data base object GRANTED privileges can also be withdrawn by the DBA at any time 2. REVOKE: To with draw the privileges that has been GRANTED to a uses, we use the REVOKE command Database Connectivity: To connect database with any frontend tool, you need to configure connectivity string. It consists of drivers for database, user name, password, service and database name for connection in general. Specific string is provided for connectivity. Drivers come with built in method to retrieve and store data from database. NoSQL Databases: NoSQL encompasses a wide variety of different database technologies that were developed in response to the demands presented in building modern applications: Developers are working with applications that create massive volumes of new, rapidly changing data types — structured, semi-structured, unstructured and polymorphic data. Now small teams work in agile sprints, iterating quickly and pushing code every week or two, some even multiple times every day. Applications that once served a finite audience are now delivered as services that must be always-on, accessible from many different devices and scaled globally to millions of users. Relational databases were not designed to cope with the scale and agility challenges that face modern applications, nor were they built to take advantage of the commodity storage and processing power available today. So, NoSQL are replacing relational DB. Stage a1 (apply) Lab Activities: Activity 1: Create a Commit point, save point and perform roll back. grant specific privileges to user 70 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 revoke the privileges from user Solution: Syntax: SQL>COMMIT; Example: SQL>COMMIT; Syntax: SQL>SAVE POINT ID; Example: SQL>SAVE POINT xyz; Syntax: ROLE BACK( current transaction can be role back) ROLE BACK to save point ID; Example: SQL>ROLE BACK; SQL>ROLE BACK TO SAVE POINT xyz; Syntax: SQL>GRANT PRIVILEGES on object_name To user_name; Example: SQL>GRANT SELECT, UPDATE on emp To hemanth; Syntax: SQL>REVOKE PRIVILEGES ON object-name FROM user_name; Example: SQL>REVOKE SELECT, UPDATE ON emp FROM ravi; Activity 2: 1. Create a user using system, the grant and revoke some permissions. 2. Connect the oracle database with Java and retrieve some information. 3. Connect Mongo DB with Java and retrieve the information Solution: 1. CREATING A USER SQL>CONNECT SYSTEM/MANAGER; SQL>CREATE USER CSE2 IDENTIFIED BY CSECSE; SQL>GRANT DBA TO CSE2; SQL>CONNECT CSE2/CSECSE; SQL>REVOKE DBA FROM CSE2; 2. Connecting Java with Oracle step by step For connecting java application with the oracle database, you need to follow 5 steps to perform database connectivity. In this example we are using Oracle10g as the database. So we need to know following information for the oracle database: 1. Driver class: The driver class for the oracle database is oracle.jdbc.driver.OracleDriver. You can import the library downloaded from oracle into your project. Then this driver will be available 2. Connection URL: The connection URL for the oracle11G database is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database, thin is 71 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 the driver, localhost is the server name on which oracle is running, we may also use IP address, 1521 is the port number and XE is the Oracle service name. You may get all these information from the tnsnames.ora file. 3. Username: The default username for the oracle database is system. 4. Password: Password is given by the user at the time of installing the oracle database. Step 5: Code: import java.sql.*; class OracleCon{ public static void main(String args[]){ try{ //step1 load the driver class Class.forName("oracle.jdbc.driver.OracleDriver"); //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from emp"); while(rs.next()) System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)); //step5 close the connection object con.close(); }catch(Exception e){ System.out.println(e);} } } 3. Connecting Java with MongoDB: Install MongoDB(or XAMMP) and Java. Download mongo-java driver from github. Then Connect to MongoDB server. For MongoDB version >= 2.10.0, uses MongoClient. 72 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 // Old version, uses Mongo Mongo mongo = new Mongo("localhost", 27017); // Since 2.10.0, uses MongoClient MongoClient mongo = new MongoClient( "localhost" , 27017 ); Get database. If the database doesn’t exist, MongoDB will create it for you. DB db = mongo.getDB("database name"); Display all databases. List<String> dbs = mongo.getDatabaseNames(); for(String db : dbs){ System.out.println(db); Get collection / table. In RDBMS, collection is equal to table. DB db = mongo.getDB("testdb"); DBCollection table = db.getCollection("user"); Display all collections from selected database. Set<String> tables = db.getCollectionNames(); for(String coll : tables){ System.out.println(coll); }} Saving a complete record: DBCollection table = db.getCollection("user"); BasicDBObject document = new BasicDBObject(); document.put("name", "mkyong"); document.put("age", 30); document.put("createdDate", new Date()); table.insert(document); A Complete Example: package com.mkyong.core; import java.net.UnknownHostException; 73 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 import java.util.Date; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.MongoClient; import com.mongodb.MongoException; /** * Java + MongoDB Hello world Example * */ public class App { public static void main(String[] args) { try { /**** Connect to MongoDB ****/ // Since 2.10.0, uses MongoClient MongoClient mongo = new MongoClient("localhost", 27017); /**** Get database ****/ // if database doesn't exists, MongoDB will create it for you DB db = mongo.getDB("testdb"); /**** Get collection / table from 'testdb' ****/ // if collection doesn't exists, MongoDB will create it for you DBCollection table = db.getCollection("user"); /**** Insert ****/ // create a document to store key and value BasicDBObject document = new BasicDBObject(); document.put("name", "mkyong"); document.put("age", 30); document.put("createdDate", new Date()); 74 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 table.insert(document); /**** Find and display ****/ BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("name", "mkyong"); DBCursor cursor = table.find(searchQuery); while (cursor.hasNext()) { System.out.println(cursor.next()); } /**** Update ****/ // search document where name="mkyong" and update it with new values BasicDBObject query = new BasicDBObject(); query.put("name", "mkyong"); BasicDBObject newDocument = new BasicDBObject(); newDocument.put("name", "mkyong-updated"); BasicDBObject updateObj = new BasicDBObject(); updateObj.put("$set", newDocument); table.update(query, updateObj); /**** Find and display ****/ BasicDBObject searchQuery2 = new BasicDBObject().append("name", "mkyong-updated"); DBCursor cursor2 = table.find(searchQuery2); while (cursor2.hasNext()) { System.out.println(cursor2.next()); } /**** Done ****/ System.out.println("Done"); } catch (UnknownHostException e) { e.printStackTrace(); 75 Downloaded by Usman Ali (usmanali.07442@gmail.com) lOMoARcPSD|9178016 } catch (MongoException e) { e.printStackTrace(); } } } 40) Stage v (verify) Home Activities: Create a Database in MongoDB and access in Java. Display a report Create a Database in Oracle. Connect with Java and display a report. 41) Stage a2 (assess) Lab Assignment and Viva voce Deliverable Submit a PDF document including the SQL queries to answer above-mentioned information needs as well as snapshot of their outcome when executed. 76 Downloaded by Usman Ali (usmanali.07442@gmail.com)