Database implementation Further SQL

Similar documents
CS2 Current Technologies Lecture 2: SQL Programming Basics

Real-World Performance Training SQL Introduction

CS2 Current Technologies Lecture 3: SQL - Joins and Subqueries

CS2 Current Technologies Note 1 CS2Bh

SQL. Char (30) can store ram, ramji007 or 80- b

GIFT Department of Computing Science Data Selection and Filtering using the SELECT Statement

King Fahd University of Petroleum and Minerals

Database Management System. * First install Mysql Database or Wamp Server which contains Mysql Databse.

GIFT Department of Computing Science. CS-217: Database Systems. Lab-4 Manual. Reporting Aggregated Data using Group Functions

Objectives. After completing this lesson, you should be able to do the following:

Part III. Data Modelling. Marc H. Scholl (DBIS, Uni KN) Information Management Winter 2007/08 1

Based on the following Table(s), Write down the queries as indicated: 1. Write an SQL query to insert a new row in table Dept with values: 4, Prog, MO

Introduction. Introduction to Oracle: SQL and PL/SQL

1 SQL Structured Query Language

1 SQL Structured Query Language

Pivot Tables Motivation (1)

Department of Computer Science and Information Systems, College of Business and Technology, Morehead State University

Informatics Practices (065) Sample Question Paper 1 Section A

SQL Structured Query Language Introduction

Visit for more.

Programming Languages

Create Rank Transformation in Informatica with example

Creating and Managing Tables Schedule: Timing Topic

RDBMS Using Oracle. BIT-4 Lecture Week 3. Lecture Overview

Chapter 16: Advanced MySQL- Grouping Records and Joining Tables. Informatics Practices Class XII. By- Rajesh Kumar Mishra

Table : Purchase. Field DataType Size Constraints CustID CHAR 5 Primary key CustName Varchar 30 ItemName Varchar 30 PurchaseDate Date

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables

Databases. Relational Model, Algebra and operations. How do we model and manipulate complex data structures inside a computer system? Until

Practical Workbook Database Management Systems

Databases - 5. Problems with the relational model Functions and sub-queries

P.G.D.C.M. (Semester I) Examination, : ELEMENTS OF INFORMATION TECHNOLOGY AND OFFICE AUTOMATION (2008 Pattern)

Introduc.on to Databases

SQL. Rodrigo García Carmona Universidad San Pablo-CEU Escuela Politécnica Superior

Database Foundations. 6-3 Data Definition Language (DDL) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Laboratory Manual. For. Database Management System (IT 502) B.Tech (IT) SEM V. June 2010

Why Relational Databases? Relational databases allow for the storage and analysis of large amounts of data.

THE INDIAN COMMUNITY SCHOOL, KUWAIT

: ADMINISTRATION I EXAM OBJECTIVES COVERED IN THIS CHAPTER:

5 Integrity Constraints and Triggers

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Slide 17-1

Databases - 4. Other relational operations and DDL. How to write RA expressions for dummies

COSC 304 Introduction to Database Systems SQL. Dr. Ramon Lawrence University of British Columbia Okanagan

GIFT Department of Computing Science. [Spring 2016] CS-217: Database Systems. Lab-3 Manual. Single Row Functions in SQL

Topic 8 Structured Query Language (SQL) : DML Part 2

Q.1 Short Questions Marks 1. New fields can be added to the created table by using command. a) ALTER b) SELECT c) CREATE. D. UPDATE.

Trigger is a stored procedure which is called implicitly by oracle engine whenever a insert, update or delete statement is fired.

SQL Queries. COSC 304 Introduction to Database Systems SQL. Example Relations. SQL and Relational Algebra. Example Relation Instances

RESTRICTING AND SORTING DATA

Using the Set Operators. Copyright 2006, Oracle. All rights reserved.

Sample Question Paper

SYSTEM CODE COURSE NAME DESCRIPTION SEM

Objectives. After completing this lesson, you should be able to do the following:

Oracle 1Z Oracle Database 11g SQL Fundamentals I. Download Full Version :

CSC Web Programming. Introduction to SQL

Rani Durgavati Vishwavidyalaya Jabalpur (M.P.) (UICSA) Master of Computer Application (MCA) Practical List of. MCA III SEM Session -2010

SQL STRUCTURED QUERY LANGUAGE

Q5 Question Based on SQL & Database Concept Total Marks 8. Theory Question 2 Marks / SQL Commands 6 Marks / Output of commands 2 Marks

CS Reading Packet: "Writing relational operations using SQL"

CS Reading Packet: "Views, and Simple Reports - Part 1"

QQ Group

Programming the Database

Chapter _CH06/CouchmanX 10/2/01 1:32 PM Page 259. Manipulating Oracle Data

Tables From Existing Tables

KENDRIYA VIDYALAYA ALIGANJ SHIFT-II HOLIDAY HOMEWORK CLASS-XII INFORMATICS PRACTICES

To understand the concept of candidate and primary keys and their application in table creation.

Data Manipulation Language (DML)

Database Programming with SQL

Overview of PL/SQL. About PL/SQL. PL/SQL Environment. Benefits of PL/SQL. Integration

Techno India Batanagar Computer Science and Engineering. Model Questions. Subject Name: Database Management System Subject Code: CS 601

Downloaded from

Creating SQL Tables and using Data Types

Data Modelling and Databases Exercise dates: March 22/March 23, 2018 Ce Zhang, Gustavo Alonso Last update: March 26, 2018.

2) SQL includes a data definition language, a data manipulation language, and SQL/Persistent stored modules. Answer: TRUE Diff: 2 Page Ref: 36

GIFT Department of Computing Science. CS-217/224: Database Systems. Lab-5 Manual. Displaying Data from Multiple Tables - SQL Joins

Databases - 3. Null, Cartesian Product and Join. Null Null is a value that we use when. Something will never have a value

Databases - 3. Null, Cartesian Product and Join. Null Null is a value that we use when. Something will never have a value

Databases 1. Daniel POP

Oracle Database SQL Basics

Test Bank for Database Processing Fundamentals Design and Implementation 13th Edition by Kroenke

Database design process

DUE: 9. Create a query that will return the average order total for all Global Fast Foods orders from January 1, 2002, to December 21, 2002.

@vmahawar. Agenda Topics Quiz Useful Links

Database Technology. Topic 3: SQL. Olaf Hartig.

IBM A Assessment: DB2 9 Fundamentals-Assessment. Download Full Version :

COGS 121 HCI Programming Studio. Week 03 - Tech Lecture

Assignment 6: SQL III Solution

SQL (Structured Query Language)

Marwadi University Bachelor of Computer Application Semester II (w.e.f. July, 2016)

Practical Workbook Database Management Systems

Slides by: Ms. Shree Jaswal

Full file at

ENHANCING DATABASE PERFORMANCE

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement

KKCC INFO SYSTEMS

1Z0-007 ineroduction to oracle9l:sql

PL/SQL. Exception. When the PL/SQL engine cannot execute the PLSQL block it raise an error. Every Oracle error has an error number

ajpatelit.wordpress.com

1Z Oracle Database 11g - SQL Fundamentals I Exam Summary Syllabus Questions

CIS Slightly-different version of Week 10 Lab, also intro to SQL UPDATE and DELETE, and more

RDBMS-Day3. SQL Basic DDL statements DML statements Aggregate functions

Transcription:

IRU SEMESTER 2 January 2010 Semester 1 Session 2 Database implementation Further SQL Objectives To be able to use more advanced SQL statements, including Renaming columns Order by clause Aggregate functions Group by and having clauses Table aliases Joins Creating, altering and deleting database objects All the above are required in exercise two! To continue work on the IRU assignment, part one. C:\Allwork\geoff\web stuff\askgeoff\iru\iru session 2 header - SQL 2.doc

Information Retrieval and Use (IRU) An Introduction To SQL Part 2 1 SQL Data Retrieval Recap: The SQL Data Manipulation Language (DML)has four commands: SELECT: retrieving data INSERT: creating data UPDATE: altering data DELETE: removing data 2 Select Statement: displaying data You can display data in a different format: Show all the department names found in the dept table but rename the column with the heading diff_dept: SQL> select dname as diff_dept from dept; DIFF_DEPT -------------- ACCOUNTING RESEARCH SALES OPERATIONS 3 1

The Order By Clause: Key principles Oracle will display your rows of data in an unordered fashion. We use the ORDER BY clause to order the rows that are retrieved. The ORDER BY clause should always be placed last in the query. The default ordering is ascending Numeric ascending by order value Dates chronological order Char alphabetically DESC is used to reverse the order 4 The Order By Clause: Example 1 List all departments in order of their location: SELECT * FROM dept ORDER BY loc; DEPTNO DNAME LOC --------- -------------- ------------- 40 OPERATIONS BOSTON 30 SALES CHICAGO 20 RESEARCH DALLAS 10 ACCOUNTING NEW YORK 5 The order by Clause: example 2 Show details of employees in department 10 with the earliest hire dates first: SELECT empno, ename, hiredate FROM emp WHERE deptno = 10 ORDER BY hiredate; EMPNO ENAME HIREDATE ----- ---------- --------- 7782 CLARK 09-JUN-81 7839 KING 17-NOV-81 7934 MILLER 23-JAN-82 6 2

The order by Clause: example 3 Show all employees in job order but within each job place in descending order of salary: SELECT ename, job, sal, deptno FROM emp ORDER BY job, sal DESC; 14 rows will be selected. 7 The order by Clause: example 4 SELECT ename,job,sal, comm, comm/sal as ratio,deptno From emp Where deptno = 30 Order by ratio; ENAME JOB SAL COMM RATIO DEPTNO ---------- --------- --------- --------- --------- --------- TURNER SALESMAN 1500 0 0 30 ALLEN SALESMAN 1600 300.1875 30 WARD SALESMAN 1250 500.4 30 MARTIN SALESMAN 1250 1400 1.12 30 BLAKE MANAGER 2850 30 JAMES CLERK 950 30 (NB: Nulls sort high) 8 Group By Function Results can be grouped according to a common attribute value. We can find the sum of the salaries by department. SELECT deptno, sum(sal) FROM emp GROUP BY deptno; DEPTNO SUM(SAL) ------- --------- 10 8750 20 10875 30 9400 9 3

Processing Data: Aggregate Functions Some simple functions include: Count: Min: Max: Sum: returns a count of rows returns the lowest value for an attribute returns the highest value for an attribute returns the sum of values Avg: returns the average value SELECT COUNT (*) FROM EMP COUNT(*) -------- 14 RETURNS THE NUMBER OF ROWS IN THE EMP TABLE. 10 Processing Data: min/max 11 You can find the highest salary: Select max(sal) from emp; MAX(SAL) -------- 5000 Select min (sal) as min_sal from emp; MIN_SAL ------- 800 Processing Data: sum/average Sum is used on numeric functions to return the sum of all the values: SELECT sum(sal), sum (comm) from emp; SUM(SAL) SUM(COMM) -------- --------- 29025 2200 SELECT avg(sal) from emp; AVG(SAL) --------- 2073.2143 12 4

Having Clause We can constrain the subgroups that appear by using a HAVING CLAUSE. We can find the sum of the salaries of each department, but only request those departments with more than 5 employees. SELECT deptno, sum(sal) FROM emp GROUP BY deptno HAVING count (*) >5; DEPTNO SUM(SAL) ----- --------- 30 9400 13 14 The self-join Useful to put more than one aggregate function on the same row of output. E.g. Count the number of people in dept 10 who receive salary, and the number in dept 10 who receive commission SELECT COUNT(A.SAL) AS COUNTSAL, COUNT(B.COM) AS COUNTCOMM FROM EMP A, EMP B WHERE A.EMPNO=B.EMPNO AND A.DEPTNO=10; SQL DATA DEFINITION : DDL Create Table CREATE TABLE customer as follows: CREATE TABLE CUSTOMER (CUSTOMER_ID NUMBER (5), NAME VARCHAR2 (10), HOUSE_NUMBER NUMBER (2), STREET VARCHAR2 (15), TOWN VARCHAR2 (15)); Each column has a name, data type and column width. 15 5

DDL: Creating Tables continued. Here s an example. What s it doing? Create Table account (account_num number (6), Account_name varchar2 (20), Branch_name varchar2(20), Date_opened date, Balance number (10,2)); The Balance column is a decimal number with a maximum Column width of ten digits and a precision of two digits i.e. 10.251 is stored as 10.25. 16 Simple Constraints: Primary keys A correct definition of the table customer might be: CREATE TABLE CUSTOMER (CUSTOMER_ID NUMBER (5), PRIMARY KEY NOT NULL, NAME VARCHAR2 (10), HOUSE_NUMBER NUMBER (2), STREET VARCHAR2 (15), TOWN VARCHAR2 (15)); 17 Simple Constraints: Primary keys The PRIMARY KEY indicates that all values for these columns must be unique. NOT NULL is used to designate that the column must have a value for all its rows. 18 Therefore in the account table the first two lines should read: Create Table account (account_num number (6) primary key not null, 6

Simple Constraints: Customer and account has a many to many relationship, we can resolve this with a table constraint by creating a composite primary key. CREATE table customer_account (CUSTOMER_ID NOT NULL, ACCOUNT_NUM NOT NULL, PRIMARY KEY (CUSTOMER_ID,ACCOUNT_NUM)); 19 Simple Constraints: Foreign keys In the CUSTOMER_ACCOUNT table that we have just created we have two foreign keys CUSTOMER_ID and ACCOUNT_NUM. We can specify these at the time of defining the table as: CREATE table CUSTOMER_ACCOUNT CUSTOMER_ID NOT NULL REFERENCES CUSTOMER, ACCOUNT_NUM NOT NULL REFERENCES ACCOUNT, PRIMARY KEY(REFNO,ACCNO)); (In order to get rid of the old table use the command DROP table customer_account. Take care when using this command because when you have dropped a table it has gone for good!) 20 Simple Constraints: Foreign keys 21 When we have created a table we may find that the original definition of the table is now unsatisfactory. For example we may create another table BANK, and the account table has a foreign key reference to the table Bank in the attribute BRANCHNAME. Therefore we need to create a relation between Account and Bank. We can use the ALTER command to change the original definition of the Account table. ALTER TABLE ACCOUNT ADD(FOREIGN KEY(BRANCHNAME) REFERENCES BANK); 7

Dropping & altering objects DROP <object type> <object name DROP TABLE EMP; (NOT undoable!) ALTER <object type> object name> ADD <column name> <data type> /DROP COLUMN <column name> ALTER TABLE EMP ADD NICKNAME VARCHAR(30) 22 Inserting Data Using SQL 23 We use the SQL command INSERT to create rows. INSERT INTO CUSTOMER VALUES(12345, DAWES, 21, BACK LANE, STAFFORD ); Remember non-numerics require quotation marks around their values. These values have been entered into the Customer table in the order in which the columns appeared in the original create table statement. Deleting/UPDATING Data Using SQL Use the DELETE command to remove data from a relation (i.e. table). DELETE FROM CUSTOMER WHERE REFNO = 12345; Use the UPDATE command to alter the data held in the rows. i.e. Change the name in the account table from Dawes to Dalby. UPDATE CUSTOMER SET NAME = DALBY WHERE CUSTOMER_ID = 12345; 24 8

25 SQL SUMMARY You have worked through some simple SQL expressions and have learnt how to : Use the SELECT command for retrieving data. Use INSERT, UPDATE, AND DELETE commands to insert, amend and delete data. Use aggregate functions to assist with processing data, i.e. COUNT, MIN, MAX, SUM, AVG. Use DDL to create, alter and drop tables. Create some simple constraints using the WHERE clause. Use the GROUP BY, HAVING and ORDER BY functions to assist with selecting and displaying data. Create simple primary and foreign key constraints. Further Reading Rolland chapter 5 Patrick chapters 1-3, 9-11, 13 SQL at w3schools - click to follow the link 26 9

IRU SEMESTER January 2010 Semester 1 Session 2 Database implementation Further SQL Tutorial work A. Complete SQL exercise two (attached). B. Continue work on IRU assignment part one (if available). Be ready to demonstrate your solutions during next week s tutorial session. C:\Allwork\geoff\web stuff\askgeoff\iru\iru session 2 tutorial - SQL 2.doc

IRU SEMESTER 2 January 2010 SQL Exercise 2: 1: Find out how many managers there are without listing them. Display as below: COUNT(JOB) ---------- 3 2: Compute the average annual salary plus commission for all salesmen: COMPENSATION ------------ 23400 3: Find the highest and lowest paid employees and the difference between them display as below: RICH POOR DIFFERENCE ---------- ---------- ---------- 5000 800 4200 4: Find the number of characters in the longest department name: LONGEST ---------- 10 5: Count the number of people in department 30 who receive a salary and the number of people who receive a commission: SALARIES COMMMISSION ---------- ----------- 6 4 6: List the average commission of employees who receive a commission and the average commission of all employees (treating employees who do not receive a commission as receiving a zero commission): AVECOMM AVEALL ---------- ---------- 550 157.142857 7: List the average salary of employees that receive a salary, the average commission of employees that receive a commission, the average salary plus commission of only those employees that receive a commission, and the average salary plus commission of all employees including those who do not receive a commission. AVESAL AVECOMM AVETOTAL AVETOTALALLL ---------- ---------- ---------- ------------ 2073.21429 550 1950 2230.35714 C:\Allwork\geoff\web stuff\askgeoff\iru\iru session 2 tutorial - SQL 2.doc