Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Similar presentations


Presentation on theme: "Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE."— Presentation transcript:

1 Introduction to SQL

2 Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE Clause Sorting with ORDER BY Selecting Data From Multiple Tables

3 Contents (2) 5.Selecting Data From Multiple Tables Natural Joins Join with USING Clause Inner Joins with ON Clause Left, Right and Full Outer Joins Cross Joins 6.Nested SELECT Statements 7.Aggregating Data Group Functions and GROUP BY

4 Contents (3) 8.Oracle SQL Functions 9.Oracle Data Types 10.Data Definition Language (DDL) 11.Creating Tables in Oracle 12.Inserting Data 13.Updating Data 14.Deleting Data

5 Relational Databases Short Overview

6 Relational Database Concepts The relational model consists of the following: Collection of tables (called relations) Set of operators to act on the relations Data integrity for accuracy and consistency

7 Definition of a Database A relational database is a collection of relations (two-dimensional tables) Database Table Name: EMPLOYEES Table Name: DEPARTMENTS EMPLO YEE_ID FIRST_ NAME LAST_NAME 100SvetlinNakovXXX 101RosenSpasovYYY 102DanailAlexievZZZ DEPARTM ENT_ID DEPARTMENT_ NAME MANAGER_ID 10IT200 20Sales201 50Finances124

8 Data Models Database Model of system in client's mind Table model of entity model Entity model of client's model

9 Entity Relationship Model Create an entity relationship diagram from business specifications or narratives Scenario... Assign one or more employees to a department Some departments do not yet have assigned employees... EMPLOYEE #* number *name ojob title DEPARTMENT #* number *name olocation assigned to composed of

10 Relating Multiple Tables Each row of data in a table is uniquely identified by a primary key (PK) You can logically relate data from multiple tables using foreign keys (FK) Table Name: EMPLOYEES Table Name: DEPARTMENTS EMPLOY EE_ID FIRST_ NAME LAST_NAMEDEPARTM ENT_ID 100SvetlinNakov80 101RosenSpasov50 102DanailAlexiev90 DEPARTM ENT_ID DEPARTMENT_NAME 10IT 20Sales 50Finances Primary key Foreign key Primary key

11 Database Terminology Table Name: EMPLOYEES EMPLOYEE_IDFIRST_NAMELAST_NAMESALARYDEPART MENT_ID 100MihailStoynov MiroslavNachev DanailAlexiev90 103RadoslavIvanov RosenSpasov RowRow Primary key column ColumnColumn Foreign key column Null value FieldField

12 Relational Databases A relational database: Can be accessed and modified by executing Structured Query Language (SQL) statements Uses a set of operations to extract subset of the data Contains a collection of tables Relationships are defined between the tables

13 Communicating with a DB Database SQL statement is sent to the database SQL statement is entered SELECT department_name FROM departments DEPARTMENT_NAME IT Sales Finances The result is returned (usually as a table)

14 The Structured Query Language (SQL) Introduction

15 What is SQL? Structured Query Language (SQL) Declarative language for query and manipulation of relational data SQL consists of: Data Manipulation Language (DML) SELECT, INSERT, UPDATE, DELETE Data Definition Language (DDL) CREATE, DROP, ALTER GRANT, REVOKE

16 Entity Relationship (E/R) Diagrams The HR Database Schema in Oracle Express

17 The HR Database Schema in Oracle 10g

18 SQL Language Introducing SELECT Statement

19 Capabilities of SQL SELECT Table 1 Table 2 Table 1 Selection Take some of the rows Projection Take some of the columns Join Combine tables by some column

20 Basic SELECT Statement SELECT identifies what columns FROM identifies which table SELECT *|{[DISTINCT] column|expression [alias],...} FROMtable

21 SELECT Example Selecting all departments Selecting specific columns SELECT * FROM DEPARTMENTS SELECT DEPARTMENT_ID, DEPARTMENT_ID, LOCATION_ID LOCATION_ID FROM DEPARTMENTS DEPARTM ENT_ID DEPARTMENT_NAMEMANAGER_IDLOCATION_ID 10Administration Marketing Shipping DEPARTMENT_IDLOCATION_ID

22 Arithmetic Operations Arithmetic operators are available: +, -, *, / Example: SELECT LAST_NAME, SALARY, SALARY FROM EMPLOYEES LAST_NAMESALARYSALARY King Kochhar De Haan

23 The null Value A null is a value that is unavailable, unassigned, unknown, or inapplicable Not the same as zero or a blank space Arithmetic expressions containing a null value are evaluated to null SELECT LAST_NAME, MANAGER_ID FROM EMPLOYEES LAST_NAMEMANAGER_ID King(null) Kochhar100 De Haan100 NULL is displayed as empty space or as (null)

24 Column Alias Renames a column heading Useful with calculations Immediately follows the column name There is an optional AS keyword Double quotation marks if contains spaces SELECT LAST_NAME "Name", 12*SALARY AS "Annual Salary" FROM EMPLOYEES "Annual Salary" FROM EMPLOYEES NameAnnual Salary King Kochhar204000

25 Concatenation Operator Concatenates columns or character strings to other columns Is represented by two vertical bars ( || ) Creates a resultant column that is a character expression SELECT LAST_NAME || JOB_ID AS "Employees" FROM EMPLOYEES Employees KingAD_PRES KochharAD_VP De HaanAD_VP

26 Literal Character Strings A literal is a character, a number, or a date included in the SELECT list Date and character literal values must be enclosed within single quotation marks Each character string is output once for each row returned SELECT LAST_NAME || ' is a ' || JOB_ID AS "Employee Details" FROM EMPLOYEES Employees King is a AD_PRES Kochhar is a AD_VP De Haan is a AD_VP

27 Removing Duplicate Rows The default display of queries is all rows, including duplicate rows Eliminate duplicate rows by using the DISTINCT keyword in the SELECT clause SELECT DEPARTMENT_ID FROM EMPLOYEES DEPARTMENT_ID SELECT DISTINCT DEPARTMENT_ID DISTINCT DEPARTMENT_ID FROM EMPLOYEES DEPARTMENT_ID

28 UNION and INTERSECT UNION combines the results from several SELECT statements The columns count and types should match INTERSECT makes logical intersection of given sets of records SELECT FIRST_NAME AS NAME FROM EMPLOYEES UNION SELECT LAST_NAME AS NAME FROM EMPLOYEES NAME Abel Adam Alana Alberto...

29 Limiting the Rows Selected Restrict the rows returned by using the WHERE clause: More examples: SELECT LAST_NAME, DEPARTMENT_ID FROM EMPLOYEES WHERE DEPARTMENT_ID = 90 SELECT FIRST_NAME, LAST_NAME, JOB_ID FROM EMPLOYEES WHERE LAST_NAME = 'Whalen' LAST_NAMEDEPARTMENT_ID King90 Kochhar90 De Haan90 SELECT LAST_NAME, SALARY FROM EMPLOYEES WHERE SALARY <= 3000

30 Using BETWEEN operator to specify a range: Using IN / NOT IN operators to specify a set of values: Using LIKE operator to specify a pattern: Using BETWEEN operator to specify a range: Using IN / NOT IN operators to specify a set of values: Using LIKE operator to specify a pattern: Other Comparison Conditions SELECT LAST_NAME, SALARY FROM EMPLOYEES WHERE SALARY BETWEEN 2500 AND 3000 SELECT FIRST_NAME, LAST_NAME, MANAGER_ID FROM EMPLOYEES WHERE MANAGER_ID IN (100, 101, 201) SELECT FIRST_NAME FROM EMPLOYEES WHERE FIRST_NAME LIKE 'S%'

31 Checking for NULL value: Note: COLUMN=NULL is always false! Using OR and AND operators: Checking for NULL value: Note: COLUMN=NULL is always false! Using OR and AND operators: Other Comparison Conditions (2) SELECT LAST_NAME, MANAGER_ID FROM EMPLOYEES WHERE MANAGER_ID IS NULL SELECT LAST_NAME, JOB_ID, SALARY FROM EMPLOYEES WHERE SALARY >= 1000 AND JOB_ID LIKE '%MAN%' SELECT LAST_NAME FROM EMPLOYEES WHERE COMMISSION_PCT IS NOT NULL OR LAST_NAME LIKE '%S%' OR LAST_NAME LIKE '%S%'

32 Sorting with ORDER BY Sort rows with the ORDER BY clause ASC : ascending order, default DESC : descending order SELECT LAST_NAME, HIRE_DATE FROM EMPLOYEES ORDER BY HIRE_DATE LAST_NAMEHIRE_DATE King17-JUN-87 Whalen17-SEP-87 Kochhar21-SEP-89 SELECT LAST_NAME, HIRE_DATE FROM EMPLOYEES ORDER BY HIRE_DATE DESC LAST_NAMEHIRE_DATE Zlotkey29-JAN-00 Mourgos16-NOV-99 Grant24-MAY-99

33 SQL Language Selecting Data From Multiple Tables

34 Data from Multiple Tables Sometimes you need data from more than one table: LAST_NAMEDEPART MENT_ID King90 Kochhar90 Fay20 DEPARTM ENT_ID DEPARTMENT_NAME 90Executive 20Marketing 10Administration LAST_NAMEDEPARTMENT_NAME KingExecutive FayMarketing KochharExecutive

35 Cartesian Product This will produce Cartesian product: The result: SELECT LAST_NAME, DEPARTMENT_NAME FROM EMPLOYEES, DEPARTMENTS LAST_NAMEDEPARTMENT_NAME KingExecutive KingMarketing KingAdministration KochharExecutive KochharMarketing..

36 Cartesian Product A Cartesian product is formed when: A join condition is omitted A join condition is invalid All rows in the first table are joined to all rows in the second table To avoid a Cartesian product, always include a valid join condition

37 Types of Joins Natural joins Join with USING clause Inner joins with ON clause Left, right and full outer joins Cross joins

38 Natural Join The NATURAL JOIN combines the rows from two tables that have equal values in all matched by name columns SELECT DEPARTMENT_ID, DEPARTMENT_NAME, LOCATION_ID, CITY LOCATION_ID, CITY FROM DEPARTMENTS NATURAL JOIN LOCATIONS DEPARTM ENT_ID DEPARTMENT_NAMELOCATION_IDCITY 60IT1400Southlake 50Shipping1500San Francisco 10Administration1700Seattle 90Executive1700Seattle...

39 Join with USING Clause If several columns have the same names we can limit the NATURAL JOIN to only one of them by the USING clause: SELECT E.EMPLOYEE_ID, E.LAST_NAME, D.LOCATION_ID, D.DEPARTMENT_NAME D.LOCATION_ID, D.DEPARTMENT_NAME FROM EMPLOYEES E JOIN DEPARTMENTS D USING (DEPARTMENT_ID) USING (DEPARTMENT_ID) EMPLOYEE_IDLAST_NAMELOCATION_IDDEPARTMENT_NAME 102De Haan1700Executive 103Hunold1400IT 104Ernst1400IT...

40 Inner Join with ON Clause To specify arbitrary conditions or specify columns to join, the ON clause is used Such JOIN is called also INNER JOIN SELECT E.EMPLOYEE_ID, E.LAST_NAME, E.DEPARTMENT_ID, D.DEPARTMENT_ID, D.LOCATION_ID E.DEPARTMENT_ID, D.DEPARTMENT_ID, D.LOCATION_ID FROM EMPLOYEES E JOIN DEPARTMENTS D ON (E.DEPARTMENT_ID = D.DEPARTMENT_ID) ON (E.DEPARTMENT_ID = D.DEPARTMENT_ID) EMPLOYEE_IDLAST_NAMEDEPARTM ENT_ID LOCATION_ID 200Whalen Hartstein Fay

41 INNER vs. OUTER Joins The join of two tables returning only matched rows is an inner join A join between two tables that returns the results of the inner join as well as unmatched rows from the left (or right) table is a left (or right) outer join A join between two tables that returns the results of an inner join as well as the results of a left and right join is a full outer join

42 INNER JOIN SELECT E.FIRST_NAME || ' ' || E.LAST_NAME AS MANAGER_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAME MANAGER_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAME FROM EMPLOYEES E INNER JOIN DEPARTMENTS D ON E.EMPLOYEE_ID=D.MANAGER_ID ON E.EMPLOYEE_ID=D.MANAGER_ID MANAGER_NAMEDEPARTMENT_IDDEPARTMENT_ NAME Jennifer Whalen10Administration Michael Hartstein20Marketing Den Raphaely30Purchasing Susan Mavris40Human Resources Adam Fripp50Shipping Alexander Hunold60IT Hermann Baer70Public Relations...

43 LEFT OUTER JOIN SELECT E.FIRST_NAME || ' ' || E.LAST_NAME AS MANAGER_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAME MANAGER_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAME FROM EMPLOYEES E LEFT OUTER JOIN DEPARTMENTS D ON E.EMPLOYEE_ID=D.MANAGER_ID ON E.EMPLOYEE_ID=D.MANAGER_ID MANAGER_NAMEDEPARTMENT_IDDEPARTMENT_ NAME Jennifer Whalen10Administration Michael Hartstein20Marketing Den Raphaely30Purchasing Clara Vishney(null) Jason Mallin(null) Hazel Philtanker(null) Nanette Cambrault(null)...

44 RIGHT OUTER JOIN SELECT E.FIRST_NAME || ' ' || E.LAST_NAME AS MANAGER_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAME MANAGER_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAME FROM EMPLOYEES E RIGHT OUTER JOIN DEPARTMENTS D ON E.EMPLOYEE_ID=D.MANAGER_ID ON E.EMPLOYEE_ID=D.MANAGER_ID MANAGER_NAMEDEPARTMENT_IDDEPARTMENT_ NAME Jennifer Whalen10Administration Michael Hartstein20Marketing Den Raphaely30Purchasing (null)120Treasury (null)130Corporate Tax (null)140Control And Credit (null)150Shareholder Services...

45 FULL OUTER JOIN SELECT E.FIRST_NAME || ' ' || E.LAST_NAME AS MANAGER_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAME MANAGER_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAME FROM EMPLOYEES E FULL OUTER JOIN DEPARTMENTS D ON E.EMPLOYEE_ID=D.MANAGER_ID ON E.EMPLOYEE_ID=D.MANAGER_ID MANAGER_NAMEDEPARTMENT_IDDEPARTMENT_ NAME Jennifer Whalen10Administration Michael Hartstein20Marketing... Clara Vishney(null) Jason Mallin(null)... (null)150Shareholder Services...

46 Three-Way Joins A three-way join is a join of three tables SELECT E.EMPLOYEE_ID, CITY, DEPARTMENT_NAME FROM EMPLOYEES E JOIN DEPARTMENTS D ON D.DEPARTMENT_ID = E.DEPARTMENT_ID ON D.DEPARTMENT_ID = E.DEPARTMENT_ID JOIN LOCATIONS L ON D.LOCATION_ID = L.LOCATION_ID ON D.LOCATION_ID = L.LOCATION_ID EMPLOYEE_IDCITYDEPARTMENT_ NAME 103SouthlakeIT 104SouthlakeIT 124San FranciscoAdministration...

47 Cross Join The CROSS JOIN clause produces the cross- product of two tables Same as a Cartesian product Not often used SELECT LAST_NAME, DEPARTMENT_NAME FROM EMPLOYEES CROSS JOIN DEPARTMENTS LAST_NAMEDEPARTMENT_NAME KingExecutive KingMarketing KingAdministration KochharExecutive..

48 Additional Conditions You can apply additional conditions in the WHERE clause: SELECT E.EMPLOYEE_ID, E.FIRST_NAME || ' ' || E.LAST_NAME AS NAME, E.FIRST_NAME || ' ' || E.LAST_NAME AS NAME, E.MANAGER_ID, E.DEPARTMENT_ID, D.DEPARTMENT_NAME E.MANAGER_ID, E.DEPARTMENT_ID, D.DEPARTMENT_NAME FROM EMPLOYEES E JOIN DEPARTMENTS D ON (E.DEPARTMENT_ID = D.DEPARTMENT_ID) (E.DEPARTMENT_ID = D.DEPARTMENT_ID) WHERE E.MANAGER_ID = 149 EMPLO YEE_ID NAMEMANAG ER_ID DEPARTME NT_ID DEPARTMENT_NAME 174Ellen Abel14980Sales 175Alyssa Hutton14980Sales...

49 SQL Language Nested SELECT Statements

50 SELECT statements can be nested in the where clause Note: Always prefer joins to nested SELECT statements (better performance) SELECT FIRST_NAME, LAST_NAME, SALARY FROM EMPLOYEES WHERE SALARY = (SELECT MAX(SALARY) FROM EMPLOYEES) (SELECT MAX(SALARY) FROM EMPLOYEES) SELECT FIRST_NAME, LAST_NAME, SALARY FROM EMPLOYEES WHERE DEPARTMENT_ID IN (SELECT DEPARTMENT_ID FROM DEPARTMENTS (SELECT DEPARTMENT_ID FROM DEPARTMENTS WHERE DEPARTMENT_NAME='Accounting') WHERE DEPARTMENT_NAME='Accounting')

51 Using the EXISTS operator in SELECT statements Find all employees that have worked in the past in the department #110 Using the EXISTS operator in SELECT statements Find all employees that have worked in the past in the department #110 Using the EXISTS operator SELECT FIRST_NAME, LAST_NAME FROM EMPLOYEES E WHERE EXISTS (SELECT EMPLOYEE_ID FROM JOB_HISTORY JH (SELECT EMPLOYEE_ID FROM JOB_HISTORY JH WHERE DEPARTMENT_ID = 110 AND WHERE DEPARTMENT_ID = 110 AND JH.EMPLOYEE_ID=E.EMPLOYEE_ID) JH.EMPLOYEE_ID=E.EMPLOYEE_ID)

52 SQL Language Aggregating Data

53 Group Functions Group functions operate on sets of rows to give one result per group EMPLOYEE_IDSALARY MAX(SALARY) 24000

54 Group Functions in SQL COUNT(*) – count of the selected rows SUM(column) – sum of the values in given column from the selected rows AVG(column) – average of the values in given column MAX(column) – the maximal value in given column MIN(column) – the minimal value in given column

55 AVG() and SUM() Functions You can use AVG() and SUM() for numeric data types SELECT AVG(SALARY), MAX(SALARY), MIN(SALARY), SUM(SALARY) MIN(SALARY), SUM(SALARY) FROM EMPLOYEES WHERE JOB_ID LIKE '%REP%' AVG(SALARY)MAX(SALARY)MIN(SALARY)SUM(SALARY)

56 MIN() and MAX() Functions You can use MIN() and MAX() for any data type (number, date, varchar,...) Displaying the first and last employee's name in alphabetical order: SELECT MIN(HIRE_DATE), MAX(HIRE_DATE) FROM EMPLOYEES MIN(HIRE_DATE)MAX(HIRE_DATE) 17-JUN JAN-00 SELECT MIN(LAST_NAME), MAX(LAST_NAME) FROM EMPLOYEES

57 The COUNT(…) Function COUNT(*) returns the number of rows in the result table COUNT(expr) returns the number of rows with non-null values for the expr SELECT COUNT(*) FROM EMPLOYEES WHERE DEPARTMENT_ID = 50 COUNT(*) 5 SELECT COUNT(COMMISSION_PCT) FROM EMPLOYEES WHERE DEPARTMENT_ID = 80 COUNT(COMMI SION_PCT) 3

58 Group Functions and Nulls Group functions ignore null values in the column If each null value in COMMISSION_PCT is considered as 0 and is included in the calculation, the result will be SELECT AVG(COMMISSION_PCT) FROM EMPLOYEES AVG(COMMISSION_PCT).2229

59 SQL Language Group Functions and the GROUP BY Statement

60 Creating Groups of Data DEPARTMENT_IDSALARY EMPLOYEES DEPART MENT_ID SUM(SALARY)

61 The GROUP BY Statement We can divide rows in a table into smaller groups by using the GROUP BY clause The syntax: The is a list of columns SELECT, SELECT, FROM FROM [WHERE ] [GROUP BY ] [ORDER BY [ORDER BY

62 The GROUP BY Statement Example of grouping data: The GROUP BY column does not have to be in the SELECT list SELECT DEPARTMENT_ID, SUM(SALARY) FROM EMPLOYEES GROUP BY DEPARTMENT_ID DEPARTMENT_IDSUM(SALARY) (null)

63 Grouping by Several Columns DEPART MENT_ID JOB_IDSALARY 20AD_ASST MK_MAN MK_MAN PU_CLERK PU_CLERK PU_CLERK PU_MAN PU_MAN PU_MAN PU_MAN DPT_IDJOB_IDSUM(SA LARY) 20AD_ASST MK_MAN PU_CLERK PU_MAN EMPLOYEESEMPLOYEES EMPLOYEESEMPLOYEES

64 Grouping by Several Columns – Example Example of grouping data by several columns: SELECT DEPARTMENT_ID, JOB_ID, COUNT(EMPLOYEE_ID), SUM(SALARY) COUNT(EMPLOYEE_ID), SUM(SALARY) FROM EMPLOYEES GROUP BY DEPARTMENT_ID, JOB_ID ORDER BY SUM(SALARY) DESC DEPARTMENT_IDJOB_IDCOUNT( EMPLOYEE_ID) SUM(SALARY) 80SA_REP SH_CLERK SA_MAN

65 Illegal Queries This SELECT statement is illegal Can not combine columns with groups functions unless when using GROUP BY This SELECT statement is also illegal Can not use WHERE for group functions SELECT DEPARTMENT_ID, COUNT(LAST_NAME) FROM EMPLOYEES SELECT DEPARTMENT_ID, AVG(SALARY) FROM EMPLOYEES WHERE AVG(SALARY) > 8000 GROUP BY DEPARTMENT_ID;

66 Using GROUP BY with HAVING Clause HAVING works like WHERE but is used for the grouping functions SELECT DEPARTMENT_ID, COUNT(EMPLOYEE_ID), AVG(SALARY) COUNT(EMPLOYEE_ID), AVG(SALARY) FROM EMPLOYEES GROUP BY DEPARTMENT_ID HAVING COUNT(EMPLOYEE_ID) BETWEEN 3 AND 6 DEPARTMENT_IDCOUNT(EMPLOYEE_ID)AVG(SALARY)

67 Using Grouping Functions and Table Joins We can apply grouping function from joined tables SELECT COUNT(*) AS EMPS, DEPARTMENT_NAME FROM EMPLOYEES E JOIN DEPARTMENTS D ON E.DEPARTMENT_ID=D.DEPARTMENT_ID ON E.DEPARTMENT_ID=D.DEPARTMENT_IDWHERE HIRE_DATE BETWEEN ' ' AND ' ' HIRE_DATE BETWEEN ' ' AND ' ' GROUP BY DEPARTMENT_NAME HAVING COUNT(*) > 5 ORDER BY EMPS DESC EMPSDEPARTMENT_NAME 19Shipping 15Sales

68 Oracle Data Types Overview

69 Oracle Data Types NUMBER – integer number (up to 38 digits) NUMBER(p, s) – integer/real number of given precision p and scale s NUMBER(10, 2) – fixed point real number VARCHAR2(size) – string of variable length up to given size (locale specific) VARCHAR2(50) – string of length up to 50 NVARCHAR2(size) – Unicode string of variable length up to given size

70 Oracle Data Types (2) DATE – date between Jan 1, 4712 BC and Dec 31, 9999 AD TIMESTAMP – date and time (year, month, day, hour, minute, and seconds) Precision can be defined BLOB – binary large data object, RAW data (up to 128 TB) Can contain photos, videos, etc. CLOB, NCLOB – character large data object (up to 128 TB)

71 SQL Language Data Definition Language (DDL)

72 Data Definition Language Types of commands Defining / editing objects CREATE ALTER DROP

73 Creating Objects CREATE / CREATE OR REPLACE commands CREATE TABLE ( ) CREATE SEQUENCE CREATE VIEW AS CREATE TABLE PERSONS ( PERSON_ID INTEGER NOT NULL, PERSON_ID INTEGER NOT NULL, NAME NVARCHAR2(50) NOT NULL, NAME NVARCHAR2(50) NOT NULL, CONSTRAINT PERSON_PK PRIMARY KEY(PERSON_ID) CONSTRAINT PERSON_PK PRIMARY KEY(PERSON_ID)) CREATE OR REPLACE VIEW PERSONS_TOP_10 AS SELECT NAME FROM PERSONS WHERE ROWNUM <= 10

74 Modifying Objects ALTER command ALTER TABLE ALTER -- Add a foreign key constraint TOWN --> COUNTIRY ALTER TABLE TOWN ADD CONSTRAINT TOWN_COUNTRY_FK ADD CONSTRAINT TOWN_COUNTRY_FK FOREIGN KEY (COUNTRY_ID) FOREIGN KEY (COUNTRY_ID) REFERENCES COUNTRY(ID) ENABLE REFERENCES COUNTRY(ID) ENABLE -- Add column COMMENT to the table PERSON ALTER TABLE PERSONS ADD ("COMMENT" VARCHAR2(800)) -- Remove column COMMENT from the table PERSON ALTER TABLE PERSONS DROP COLUMN "COMMENT"

75 Deleting Objects DROP command DROP TABLE DROP SEQUENCE DROP TRIGGER DROP INDEX DROP SEQUENCE SEQ_PERSON DROP CONSTRAINT TRG_PERSON_INSERT DROP TABLE PERSONS

76 Creating Tables Best Practices

77 Creating Tables in Oracle Creating new table: Define the table name Define the columns and their types Define the table primary key Define a sequence for populating the primary key Define a trigger for automatically populate the primary key on insertion Define foreign/keys and constraints

78 Creating Tables in Oracle – Example CREATE TABLE PERSONS ( PERSON_ID NUMBER NOT NULL, NAME VARCHAR2(100) NOT NULL, CONSTRAINT PERSONS_PK PRIMARY KEY(PERSON_ID) ); CREATE SEQUENCE SEQ_PERSONS; CREATE TRIGGER TRG_PERSONS_INSERT BEFORE INSERT ON PERSONS FOR EACH ROW BEGIN SELECT SEQ_PERSONS.nextval INTO :new.PERSON_ID FROM dual; END;

79 SQL Language Inserting Data in the Tables

80 Inserting Data INSERT command INSERT INTO VALUES ( ) INSERT INTO ( ) VALUES ( ) INSERT INTO SELECT INSERT INTO COUNTRY VALUES ('1', 'Bulgaria', 'Sofia') INSERT INTO COUNTRY(NAME, CAPITAL) VALUES ('Bulgaria', 'Sofia') INSERT INTO COUNTRY(COUNTRY_ID, NAME, CAPITAL) SELECT NULL, COUNTRY, CAPITAL FROM CAPITALS

81 SQL Language Updating Data in the Tables

82 Updating Data UPDATE command UPDATE SET WHERE Note: Don't forget the WHERE clause! UPDATE PERSONS SET NAME = 'Updated Name' WHERE PERSON_ID = 1 UPDATE EMPLOYEES SET SALARY = SALARY * 1.10 WHERE DEPARTMENT_ID = 3

83 Updating Joined Tables Updating joined tables is done by nested SELECT UPDATE (SELECT SALARY (SELECT SALARY FROM EMPLOYEES E INNER JOIN DEPARTMENTS D FROM EMPLOYEES E INNER JOIN DEPARTMENTS D ON E.DEPARTMENT_ID = D.DEPARTMENT_ID ON E.DEPARTMENT_ID = D.DEPARTMENT_ID WHERE D.NAME = 'Accounting') WHERE D.NAME = 'Accounting') SET SALARY = SALARY * 1.10

84 SQL Language Deleting Data from the Tables

85 Deleting Data Deleting rows from a table DELETE FROM WHERE Note: Dont forget the WHERE clause! Delete all rows from a table at once TRUNCATE TABLE DELETE FROM PERSONS WHERE PERSON_ID = 1 DELETE FROM PERSONS WHERE NAME LIKE 'S%' TRUNCATE TABLE PERSONS

86 Problems 1.What is SQL? What is DML? What is DDL? Recite the most important SQL commands. 2.What is PL/SQL? 3.Start Oracle SQL Developer and connect to the database. Use the HR user. Examine the major tables in the HR schema. 4.Write a SQL query to find all information about all department. 5.Write a SQL query to find all department names. 6.Write a SQL query to find the salary of each employee by month, by day and hour. Consider that one month has 20 workdays and each workday has 8 work hours.

87 Problems (2) 7.Write a SQL query to find the addresses of each employee. Consider that the mail domain is mail.somecompany.com. s should look like The produced column should be names "Full Address". 8.Write a SQL query to find all different salaries that are paid to the employees. 9.Write a SQL query to find all information about the employees whose position is "AC_MGR" (Accounting Manager). 10.Write a SQL query to find the names of all employees whose first name starts with "Sa".

88 Problems (3) 11.Write a SQL query to find the names of all employees whose last name contains the character sequence "ei". 12.Write a SQL query to find the names of all employees whose salary is in the range [ ]. 13.Write a SQL query to find the names of all employees whose salary is 2500, 4000 or Write a SQL query to find all locations that has no state or post code defined. 15.Write a SQL query to find all employees that are paid more than Order them in decreasing order by salary.

89 Problems (4) 16.Write a SQL query to find to top 5 best paid employees. 17.Write a SQL query to find all departments and the town of their location. Use natural join. 18.Write a SQL query to find all departments and the town of their location. Use join with USING clause. 19.Write a SQL query to find all departments and the town of their location. Use inner join with ON clause. 20.Write a SQL query to find all the locations and the departments for each location along with the locations that do not have department. User right outer join. Rewrite the query to use left outer join.

90 Problems (5) 21.Write a SQL query to find the manager of each department. 22.Write a SQL query to find the location of each department manager. 23.Write a SQL query to find the names of all employees from the departments "Sales" and "Finance" whose hire year is between 1995 and Write a SQL query to find the names and salaries of the employees that take the minimal salary in the company. Use nested SELECT statement. 25.Write a SQL query to find the names and salaries of the employees that take a salary that is up to 10% higher than the minimal salary for the company.

91 Problems (6) 26.Write a SQL query to find the average salary in the "Sales" department. 27.Write a SQL query to find the number of employees in the "Sales" department. 28.Write a SQL query to find the number of all locations where the company has an office. 29.Write a SQL query to find the number of all departments that has manager. 30.Write a SQL query to find the number of all departments that has no manager. 31.Write a SQL query to find all departments and the average salary for each of them.

92 Problems (7) 32.Write a SQL query to find the count of all employees in each department and for each manager. 33.Write a SQL query to find all managers that have exactly 5 employees. Display their names and the name and location of their department. 34.Write a SQL query to find all departments along with their managers. For departments that do not have manager display "(no manager)". 35.Write a SQL query to find the names of all employees whose last name is exactly 5 characters long. 36.Write a SQL query to print the current date and time in the format "day.month.year hour:minutes:seconds".

93 Problems (8) 37.Write a SQL statement to create a table USERS. Users should have username, password, full name and last login time. Choose appropriate data types for the fields of the table. Define a primary key column with a primary key constraint. Define a sequence for populating the primary key. Define a trigger to update the primary key column value before inserting a record. 38.Write a SQL statement to create a view that displays the users from the USERS table that have been in the system today. Test if the view works correctly.

94 Problems (9) 39.Write a SQL statement to create a table GROUPS. Groups should have unique name (use unique constraint). Define primary key and a sequence and a trigger for populating it. 40.Write a SQL statement to add a column GROUP_ID to the table USERS. Fill some data in this new column and as well in the GROUPS table. Write a SQL statement to add a foreign key constraint between tables USERS and GROUPS. 41.Write SQL statements to insert several records in the USERS and GROUPS tables.

95 Problems (10) 42.Write SQL statements to insert in the USER table the names of all employees from the EMPLOYEES table. Combine the first and last names as a full name. For user name use the column from EMPLOYEES. Use blank password. 43.Write a SQL statement that changes the password to NULL for all USERS that have not been in the system since Write a SQL statement that deletes all users without passwords (NULL or empty password).

96 Homework 1.Write a SQL query to display the average employee salary by country. 2.Write a SQL query to display the average employee salary by region. 3.Write a SQL query to display the country of each employee along with his name and department city. 4.Write a SQL query to display the country where maximal number of employees work. 5.Write a SQL query to display the number of managers for each region and each country. 6.Define table WORKHOURS to store work reports for each employee (date, task, hours, comments). Don't forget to define automatically populated primary key (primary key constraint + sequence + trigger).

97 Homework (2) 7.Define foreign key between the tables WORKHOURS and EMPLOYEE. Add additional column in the employee table if needed. 8.Write several SQL statements to fill some data in the WORKHOURS table. 9.Write a SQL query to find all the average work hours per week for each country. 10.Write a SQL query to find all the departments where some employee worked overtime (over 8 hours/day) during the last week. 11.Write a SQL query to find all employees that have worked 3 or more days overtime in the last week. Display their name, location department and country.


Download ppt "Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE."

Similar presentations


Ads by Google