Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Information Retrieval and Use (IRU) An Introduction To SQL Part 2.

Similar presentations


Presentation on theme: "1 Information Retrieval and Use (IRU) An Introduction To SQL Part 2."— Presentation transcript:

1 1 Information Retrieval and Use (IRU) An Introduction To SQL Part 2

2 2 SQL Data Retrieval n Recap: n The SQL Data Manipulation Language (DML)has four commands: ä SELECT: retrieving data ä INSERT: creating data ä UPDATE: altering data ä DELETE: removing data

3 3 Select Statement: displaying data n 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

4 4 The Order By Clause: Key principles n Oracle will display your rows of data in an unordered fashion. n We use the ORDER BY clause to order the rows that are retrieved. n The ORDER BY clause should always be placed last in the query. n The default ordering is ascending ä Numeric ascending by order value ä Dates chronological order ä Charalphabetically ä DESC is used to reverse the order

5 5 The Order By Clause: Example 1 n 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

6 6 The order by Clause: example 2 n 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

7 7 The order by Clause: example 3 n 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.

8 8 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)

9 9 Group By Function n 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

10 10 Processing Data: Aggregate Functions n Some simple functions include: ä Count: returns a count of rows ä Min:returns the lowest value for an attribute ä Max:returns the highest value for an attribute ä Sum: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.

11 11 Processing Data: min/max n 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

12 12 Processing Data: sum/average n 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

13 13 Having Clause n We can constrain the subgroups that appear by using a HAVING CLAUSE. n 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

14 14 The self-join n Useful to put more than one aggregate function on the same row of output. n 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;

15 15 SQL DATA DEFINITION : DDL n Create Table n 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)); n Each column has a name, data type and column width.

16 16 DDL: Creating Tables continued. n Here’s an example. What’s it doing? Create Table account (account_numnumber (6), Account_namevarchar2 (20), Branch_namevarchar2(20), Date_openeddate, Balancenumber (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.

17 17 Simple Constraints: Primary keys n 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));

18 18 Simple Constraints: Primary keys n The PRIMARY KEY indicates that all values for these columns must be unique. n NOT NULL is used to designate that the column must have a value for all its rows. n Therefore in the ‘account’ table the first two lines should read: Create Table account (account_numnumber (6) primary key not null,

19 19 Simple Constraints: n 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));

20 20 Simple Constraints: Foreign keys n 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!)

21 21 Simple Constraints: Foreign keys n 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);

22 22 Dropping & altering objects n DROP <object name n DROP TABLE EMP; (NOT undoable!) n ALTER object name> ADD /DROP COLUMN n ALTER TABLE EMP n ADD NICKNAME VARCHAR(30)

23 23 Inserting Data Using SQL n 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.

24 24 Deleting/UPDATING Data Using SQL n Use the DELETE command to remove data from a relation (i.e. table). DELETE FROM CUSTOMER WHERE REFNO = 12345; n 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;

25 25 SQL SUMMARY n 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.

26 26 Further Reading n Rolland chapter 5 n Patrick chapters 1-3, 9-11, 13 n SQL at w3schools - click to follow the link SQL at w3schools - click to follow the link


Download ppt "1 Information Retrieval and Use (IRU) An Introduction To SQL Part 2."

Similar presentations


Ads by Google