introduction to sql - presentation
Post on 08-Apr-2016
43 Views
Preview:
TRANSCRIPT
Introduction to SQL
Contents
1. Relational Databases and Data Models2. SQL3. The HR Database Schema in Oracle4. Introducing SELECT Statement
•The WHERE Clause•Sorting with ORDER BY•Selecting Data From Multiple Tables
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 Statements7. Aggregating Data
•Group Functions and GROUP BY
Contents (3)
8. Oracle SQL Functions9. Oracle Data Types10. Data Definition Language (DDL)11. Creating Tables in Oracle12. Inserting Data13. Updating Data14. Deleting Data
Relational DatabasesShort Overview
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
Definition of a Database
• A relational database is a collection of relations (two-dimensional tables)
Database
Table Name: EMPLOYEES Table Name: DEPARTMENTS
EMPLOYEE_ID
FIRST_NAME
LAST_NAME EMAIL
100 Svetlin Nakov XXX
101 Rosen Spasov YYY
102 Danail Alexiev ZZZ
DEPARTMENT_ID
DEPARTMENT_NAME
MANAGER_ID
10 IT 200
20 Sales 201
50 Finances 124
Data Models
Database
Model of systemin client's mind
Table model ofentity model
Entity model ofclient's model
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* nameo job title
DEPARTMENT#* number* nameo location
assigned to
composed of
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: DEPARTMENTSEMPLOYEE_ID
FIRST_NAME
LAST_NAME DEPARTMENT_ID
100 Svetlin Nakov 80
101 Rosen Spasov 50
102 Danail Alexiev 90
DEPARTMENT_ID
DEPARTMENT_NAME
10 IT
20 Sales
50 Finances
Primary key Foreign key Primary key
Database Terminology
Table Name: EMPLOYEES
EMPLOYEE_ID FIRST_NAME LAST_NAME SALARY DEPARTMENT_ID
100 Mihail Stoynov 24000 80101 Miroslav Nachev 17000 50102 Danail Alexiev 90103 Radoslav Ivanov 9000 60104 Rosen Spasov 6000 90
Row
Primary key column
ColumnForeign key column Null value
Field
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
Communicating with a DB
Database
SQL statement issent to the database
SQL statement isentered
SELECT department_name FROM departments
DEPARTMENT_NAMEITSalesFinances
The result is returned(usually as a table)
The Structured Query Language (SQL)Introduction
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
Entity Relationship (E/R) DiagramsThe HR Database Schema in Oracle Express
The HR Database Schema in Oracle 10g
COUNTRIES
PK COUNTRY_ID
COUNTRY_NAMEFK1 REGION_ID
LOCATIONS
PK LOCATION_ID
STREET_ADDRESSPOSTAL_CODE
I1 CITYI3 STATE_PROVINCEFK1,I2 COUNTRY_ID
DEPARTMENTS
PK DEPARTMENT_ID
DEPARTMENT_NAMEFK1 MANAGER_IDFK2,I1 LOCATION_ID
REGIONS
PK REGION_ID
REGION_NAME
EMPLOYEES
PK EMPLOYEE_ID
I4 FIRST_NAMEI4 LAST_NAMEU1 EMAIL
PHONE_NUMBERHIRE_DATE
FK3,I2 JOB_IDSALARYCOMMISSION_PCT
FK2,I3 MANAGER_IDFK1,I1 DEPARTMENT_IDJOB_HISTORY
PK,FK2,I2 EMPLOYEE_IDPK START_DATE
END_DATEFK3,I3 JOB_IDFK1,I1 DEPARTMENT_ID
JOBS
PK JOB_ID
JOB_TITLEMIN_SALARYMAX_SALARY
SQL LanguageIntroducing SELECT Statement
Capabilities of SQL SELECT
Table 1 Table 2
Table 1 Table 1
SelectionTake some of the rows
ProjectionTake some of the columns
JoinCombine tables bysome column
Basic SELECT Statement
• SELECT identifies what columns• FROM identifies which table
SELECT *|{[DISTINCT] column|expression [alias],...}FROM table
SELECT Example
• Selecting all departments
• Selecting specific columns
SELECT * FROM DEPARTMENTS
SELECT DEPARTMENT_ID, LOCATION_ID FROM DEPARTMENTS
DEPARTMENT_ID
DEPARTMENT_NAME MANAGER_ID LOCATION_ID
10 Administration 200 170020 Marketing 201 180050 Shipping 124 1900
DEPARTMENT_ID LOCATION_ID10 170020 180050 1900
Arithmetic Operations
• Arithmetic operators are available:• +, -, *, /
• Example:
SELECT LAST_NAME, SALARY, SALARY + 300FROM EMPLOYEES
LAST_NAME SALARY SALARY + 300
King 24000 24300
Kochhar 17000 17300
De Haan 17000 17300
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_NAME MANAGER_IDKing (null)Kochhar 100De Haan 100
NULL is displayed as empty space or as (null)
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
Name Annual Salary
King 288000
Kochhar 204000
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
EmployeesKingAD_PRESKochharAD_VPDe HaanAD_VP
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
EmployeesKing is a AD_PRESKochhar is a AD_VPDe Haan is a AD_VP
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_IDFROM EMPLOYEES
DEPARTMENT_ID909060...
SELECT DISTINCT DEPARTMENT_IDFROM EMPLOYEES
DEPARTMENT_ID9060...
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 NAMEFROM EMPLOYEESUNIONSELECT LAST_NAME AS NAME FROM EMPLOYEES
NAMEAbelAdamAlanaAlberto...
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_NAME DEPARTMENT_IDKing 90Kochhar 90De Haan 90
SELECT LAST_NAME, SALARY FROM EMPLOYEESWHERE SALARY <= 3000
• 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 EMPLOYEESWHERE 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 EMPLOYEESWHERE FIRST_NAME LIKE 'S%'
• 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 EMPLOYEESWHERE MANAGER_ID IS NULL
SELECT LAST_NAME, JOB_ID, SALARY FROM EMPLOYEESWHERE SALARY >= 1000 AND JOB_ID LIKE '%MAN%'
SELECT LAST_NAME FROM EMPLOYEESWHERE COMMISSION_PCT IS NOT NULL OR LAST_NAME LIKE '%S%'
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_NAME HIRE_DATEKing 17-JUN-87Whalen 17-SEP-87Kochhar 21-SEP-89
SELECT LAST_NAME, HIRE_DATE FROM EMPLOYEES ORDER BY HIRE_DATE DESC
LAST_NAME HIRE_DATEZlotkey 29-JAN-00Mourgos 16-NOV-99Grant 24-MAY-99
SQL LanguageSelecting Data From Multiple Tables
Data from Multiple Tables
• Sometimes you need data from more than one table:
LAST_NAME DEPARTMENT_ID
King 90Kochhar 90Fay 20
DEPARTMENT_ID
DEPARTMENT_NAME
90 Executive20 Marketing10 Administration
LAST_NAME DEPARTMENT_NAMEKing ExecutiveFay MarketingKochhar Executive
Cartesian Product
• This will produce Cartesian product:
• The result:
SELECT LAST_NAME, DEPARTMENT_NAMEFROM EMPLOYEES, DEPARTMENTS
LAST_NAME DEPARTMENT_NAMEKing ExecutiveKing MarketingKing AdministrationKochhar ExecutiveKochhar Marketing.. ..
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
Types of Joins
• Natural joins• Join with USING clause• Inner joins with ON clause• Left, right and full outer joins• Cross joins
Natural Join
• The NATURAL JOIN combines the rows from two tables that have equal values in all matched by name columnsSELECT DEPARTMENT_ID, DEPARTMENT_NAME, LOCATION_ID, CITYFROM DEPARTMENTS NATURAL JOIN LOCATIONS
DEPARTMENT_ID
DEPARTMENT_NAME LOCATION_ID CITY
60 IT 1400 Southlake50 Shipping 1500 San Francisco10 Administration 1700 Seattle90 Executive 1700 Seattle... ... ... ...
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_NAMEFROM EMPLOYEES E JOIN DEPARTMENTS D USING (DEPARTMENT_ID)
EMPLOYEE_ID LAST_NAME LOCATION_ID DEPARTMENT_NAME102 De Haan 1700 Executive103 Hunold 1400 IT104 Ernst 1400 IT... ... ... ...
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_IDFROM EMPLOYEES E JOIN DEPARTMENTS D ON (E.DEPARTMENT_ID = D.DEPARTMENT_ID)
EMPLOYEE_ID LAST_NAME DEPARTMENT_ID
DEPARTMENT_ID
LOCATION_ID
200 Whalen 10 10 1700201 Hartstein 20 20 1800202 Fay 20 20 1800
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
INNER JOIN
SELECT E.FIRST_NAME || ' ' || E.LAST_NAME AS MANAGER_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAMEFROM EMPLOYEES E INNER JOIN DEPARTMENTS D ON E.EMPLOYEE_ID=D.MANAGER_ID
MANAGER_NAME DEPARTMENT_ID DEPARTMENT_ NAMEJennifer Whalen 10 AdministrationMichael Hartstein 20 MarketingDen Raphaely 30 PurchasingSusan Mavris 40 Human ResourcesAdam Fripp 50 ShippingAlexander Hunold 60 ITHermann Baer 70 Public Relations... ... ...
LEFT OUTER JOIN
SELECT E.FIRST_NAME || ' ' || E.LAST_NAME AS MANAGER_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAMEFROM EMPLOYEES E LEFT OUTER JOIN DEPARTMENTS D ON E.EMPLOYEE_ID=D.MANAGER_ID
MANAGER_NAME DEPARTMENT_ID DEPARTMENT_ NAMEJennifer Whalen 10 AdministrationMichael Hartstein 20 MarketingDen Raphaely 30 PurchasingClara Vishney (null) (null)Jason Mallin (null) (null)Hazel Philtanker (null) (null)Nanette Cambrault (null) (null)... ... ...
RIGHT OUTER JOIN
SELECT E.FIRST_NAME || ' ' || E.LAST_NAME AS MANAGER_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAMEFROM EMPLOYEES E RIGHT OUTER JOIN DEPARTMENTS D ON E.EMPLOYEE_ID=D.MANAGER_ID
MANAGER_NAME DEPARTMENT_ID DEPARTMENT_ NAMEJennifer Whalen 10 AdministrationMichael Hartstein 20 MarketingDen Raphaely 30 Purchasing(null) 120 Treasury(null) 130 Corporate Tax(null) 140 Control And Credit(null) 150 Shareholder Services... ... ...
FULL OUTER JOIN
SELECT E.FIRST_NAME || ' ' || E.LAST_NAME AS MANAGER_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAMEFROM EMPLOYEES E FULL OUTER JOIN DEPARTMENTS D ON E.EMPLOYEE_ID=D.MANAGER_ID
MANAGER_NAME DEPARTMENT_ID DEPARTMENT_ NAMEJennifer Whalen 10 AdministrationMichael Hartstein 20 Marketing... ... ...Clara Vishney (null) (null)Jason Mallin (null) (null)... ... ... (null) 150 Shareholder Services... ... ...
Three-Way Joins
• A three-way join is a join of three tables
SELECT E.EMPLOYEE_ID, CITY, DEPARTMENT_NAME FROM EMPLOYEES EJOIN DEPARTMENTS D ON D.DEPARTMENT_ID = E.DEPARTMENT_IDJOIN LOCATIONS L ON D.LOCATION_ID = L.LOCATION_ID
EMPLOYEE_ID CITY DEPARTMENT_ NAME103 Southlake IT104 Southlake IT124 San Francisco Administration... ... ...
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_NAMEFROM EMPLOYEES CROSS JOIN DEPARTMENTS
LAST_NAME DEPARTMENT_NAMEKing ExecutiveKing MarketingKing AdministrationKochhar Executive.. ..
Additional Conditions
• You can apply additional conditions in the WHERE clause:
SELECT E.EMPLOYEE_ID, E.FIRST_NAME || ' ' || E.LAST_NAME AS NAME, E.MANAGER_ID, E.DEPARTMENT_ID, D.DEPARTMENT_NAMEFROM EMPLOYEES E JOIN DEPARTMENTS D ON (E.DEPARTMENT_ID = D.DEPARTMENT_ID)WHERE E.MANAGER_ID = 149
EMPLOYEE_ID
NAME MANAGER_ID
DEPARTMENT_ID
DEPARTMENT_NAME
174 Ellen Abel 149 80 Sales175 Alyssa Hutton 149 80 Sales... ... ... ... ...
SQL LanguageNested SELECT Statements
Nested SELECT Statements
• SELECT statements can be nested in the where clause
• Note: Always prefer joins to nested SELECT statements (better performance)
SELECT FIRST_NAME, LAST_NAME, SALARYFROM EMPLOYEESWHERE SALARY = (SELECT MAX(SALARY) FROM EMPLOYEES)
SELECT FIRST_NAME, LAST_NAME, SALARYFROM EMPLOYEESWHERE DEPARTMENT_ID IN (SELECT DEPARTMENT_ID FROM DEPARTMENTS WHERE DEPARTMENT_NAME='Accounting')
• 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 EWHERE EXISTS (SELECT EMPLOYEE_ID FROM JOB_HISTORY JH WHERE DEPARTMENT_ID = 110 AND JH.EMPLOYEE_ID=E.EMPLOYEE_ID)
SQL LanguageAggregating Data
Group Functions
• Group functions operate on sets of rows to give one result per group
EMPLOYEE_ID SALARY100 24000101 17000102 17000103 9000104 6000... ...
MAX(SALARY)24000
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
AVG() and SUM() Functions
• You can use AVG() and SUM() for numeric data types
SELECT AVG(SALARY), MAX(SALARY), MIN(SALARY), SUM(SALARY)FROM EMPLOYEESWHERE JOB_ID LIKE '%REP%'
AVG(SALARY) MAX(SALARY) MIN(SALARY) SUM(SALARY)8272.72 11500 6000 273000
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-1987 29-JAN-00
SELECT MIN(LAST_NAME), MAX(LAST_NAME)FROM EMPLOYEES
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 EMPLOYEESWHERE DEPARTMENT_ID = 50
COUNT(*)
5
SELECT COUNT(COMMISSION_PCT)FROM EMPLOYEESWHERE DEPARTMENT_ID = 80
COUNT(COMMISION_PCT)
3
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 0.0425
SELECT AVG(COMMISSION_PCT) FROM EMPLOYEES
AVG(COMMISSION_PCT)
.2229
SQL LanguageGroup Functions and theGROUP BY Statement
Creating Groups of Data
DEPARTMENT_ID SALARY50 310050 300050 260050 260020 440020 1300020 600040 650040 10000110 12000110 8300... ...
EMPLOYEES
11300
23400
16500
20300
DEPARTMENT_ID
SUM(SALARY)
50 1130020 2340040 16500110 20300... ...
The GROUP BY Statement
• We can divide rows in a table into smaller groups by using the GROUP BY clause
• The syntax:
• The <group_by_expression> is a list of columns
SELECT <columns>, <group_function(column)>FROM <table>[WHERE <condition>][GROUP BY <group_by_expression>][ORDER BY <columns>
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 EMPLOYEESGROUP BY DEPARTMENT_ID
DEPARTMENT_ID SUM(SALARY)100 5160030 24900(null) 7000... ...
Grouping by Several Columns
DEPARTMENT_ID
JOB_ID SALARY
20 AD_ASST 440020 MK_MAN 1300020 MK_MAN 1200030 PU_CLERK 250030 PU_CLERK 250030 PU_CLERK 250030 PU_MAN 1100030 PU_MAN 1150030 PU_MAN 1000030 PU_MAN 11000... ... ...
4400
25000
7500
DPT_ID JOB_ID SUM(SALARY)
20 AD_ASST 440020 MK_MAN 2500030 PU_CLERK 750030 PU_MAN 43500... ... ...43500
EMPLOYEES
EMPLOYEES
Grouping by Several Columns – Example
• Example of grouping data by several columns:
SELECT DEPARTMENT_ID, JOB_ID, COUNT(EMPLOYEE_ID), SUM(SALARY)FROM EMPLOYEESGROUP BY DEPARTMENT_ID, JOB_IDORDER BY SUM(SALARY) DESC
DEPARTMENT_ID JOB_ID COUNT(EMPLOYEE_ID)
SUM(SALARY)
80 SA_REP 29 24350050 SH_CLERK 20 6430080 SA_MAN 5 61000... ... ... ...
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 EMPLOYEESWHERE AVG(SALARY) > 8000GROUP BY DEPARTMENT_ID;
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)FROM EMPLOYEESGROUP BY DEPARTMENT_IDHAVING COUNT(EMPLOYEE_ID) BETWEEN 3 AND 6
DEPARTMENT_ID COUNT(EMPLOYEE_ID) AVG(SALARY)100 6 860030 6 415090 3 19333.3360 5 5760
Using Grouping Functions and Table Joins
• We can apply grouping function from joined tables
SELECT COUNT(*) AS EMPS, DEPARTMENT_NAMEFROM EMPLOYEES E JOIN DEPARTMENTS D ON E.DEPARTMENT_ID=D.DEPARTMENT_IDWHERE HIRE_DATE BETWEEN '1991-1-1' AND '1997-12-31'GROUP BY DEPARTMENT_NAMEHAVING COUNT(*) > 5ORDER BY EMPS DESC
EMPS DEPARTMENT_NAME19 Shipping15 Sales
Oracle Data TypesOverview
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
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)
SQL LanguageData Definition Language (DDL)
Data Definition Language
• Types of commands• Defining / editing objects
• CREATE• ALTER• DROP
Creating Objects
• CREATE / CREATE OR REPLACE commands• CREATE TABLE <name> (<fields definitions>)
• CREATE SEQUENCE <name>• CREATE VIEW <name> AS <select>
CREATE TABLE PERSONS ( PERSON_ID INTEGER NOT NULL, NAME NVARCHAR2(50) NOT NULL, CONSTRAINT PERSON_PK PRIMARY KEY(PERSON_ID))
CREATE OR REPLACE VIEW PERSONS_TOP_10 ASSELECT NAME FROM PERSONS WHERE ROWNUM <= 10
Modifying Objects
• ALTER command• ALTER TABLE <name> <command>• ALTER
-- Add a foreign key constraint TOWN --> COUNTIRYALTER TABLE TOWN ADD CONSTRAINT TOWN_COUNTRY_FK FOREIGN KEY (COUNTRY_ID) REFERENCES COUNTRY(ID) ENABLE-- Add column COMMENT to the table PERSONALTER TABLE PERSONS ADD ("COMMENT" VARCHAR2(800))-- Remove column COMMENT from the table PERSONALTER TABLE PERSONS DROP COLUMN "COMMENT"
Deleting Objects
• DROP command• DROP TABLE <name>• DROP SEQUENCE <name>• DROP TRIGGER <name>• DROP INDEX <name>
DROP SEQUENCE SEQ_PERSON
DROP CONSTRAINT TRG_PERSON_INSERT
DROP TABLE PERSONS
Creating TablesBest Practices
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
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_INSERTBEFORE INSERT ON PERSONS FOR EACH ROW BEGIN SELECT SEQ_PERSONS.nextval INTO :new.PERSON_ID FROM dual; END;
SQL LanguageInserting Data in the Tables
Inserting Data
• INSERT command• INSERT INTO <table> VALUES (<values>)• INSERT INTO <table>(<columns>) VALUES (<values>)
• INSERT INTO <table> SELECT <values>
INSERT INTO COUNTRYVALUES ('1', 'Bulgaria', 'Sofia')INSERT INTO COUNTRY(NAME, CAPITAL)VALUES ('Bulgaria', 'Sofia')INSERT INTO COUNTRY(COUNTRY_ID, NAME, CAPITAL)SELECT NULL, COUNTRY, CAPITAL FROM CAPITALS
SQL LanguageUpdating Data in the Tables
Updating Data
• UPDATE command• UPDATE <table> SET <column=expression> WHERE <condition>
• Note: Don't forget the WHERE clause!
UPDATE PERSONSSET NAME = 'Updated Name'WHERE PERSON_ID = 1
UPDATE EMPLOYEESSET SALARY = SALARY * 1.10WHERE DEPARTMENT_ID = 3
Updating Joined Tables
• Updating joined tables is done by nested SELECT
UPDATE (SELECT SALARY FROM EMPLOYEES E INNER JOIN DEPARTMENTS D ON E.DEPARTMENT_ID = D.DEPARTMENT_ID WHERE D.NAME = 'Accounting')SET SALARY = SALARY * 1.10
SQL LanguageDeleting Data from the Tables
Deleting Data
• Deleting rows from a table• DELETE FROM <table> WHERE <condition>
• Note: Don’t forget the WHERE clause!• Delete all rows from a table at once
• TRUNCATE TABLE <table>
DELETE FROM PERSONS WHERE PERSON_ID = 1DELETE FROM PERSONS WHERE NAME LIKE 'S%'
TRUNCATE TABLE PERSONS
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.
Problems (2)
7. Write a SQL query to find the email addresses of each employee. Consider that the mail domain is mail.somecompany.com. Emails should look like "bernst@mail.somecompany.com". The produced column should be names "Full Email 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".
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 [3000...5000].
13. Write a SQL query to find the names of all employees whose salary is 2500, 4000 or 5000.
14. 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 10000. Order them in decreasing order by salary.
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.
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 2000.
24. 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.
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.
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".
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.
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.
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 email 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 10.03.2006.
44. Write a SQL statement that deletes all users without passwords (NULL or empty password).
Homework1. 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).
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.
top related