• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Introduction to-sql
 

Introduction to-sql

on

  • 5,518 views

Introduction to SQL lecture - DDL and DML, creating and altering DB schema, inserting data and searching into existing content, joining tables

Introduction to SQL lecture - DDL and DML, creating and altering DB schema, inserting data and searching into existing content, joining tables

Statistics

Views

Total Views
5,518
Views on SlideShare
4,539
Embed Views
979

Actions

Likes
0
Downloads
330
Comments
1

3 Embeds 979

http://javaeecourse.devbg.org 977
http://webcache.googleusercontent.com 1
http://www.techgig.com 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel

11 of 1 previous next

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • Superb information i clarified many doubts i had in sql............thanks
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Introduction to-sql Introduction to-sql Presentation Transcript

    • Introduction to SQL
    • Contents Relational Databases and Data Models SQL The HR Database Schema in Oracle Introducing SELECT Statement The WHERE Clause Sorting with ORDER BY Selecting Data From Multiple Tables
    • Contents (2) Selecting Data From Multiple Tables Natural Joins Join with USING Clause Inner Joins with ON Clause Left, Right and Full Outer Joins Cross Joins Nested SELECT Statements Aggregating Data Group Functions and GROUP BY
    • Contents (3) Oracle SQL Functions Oracle Data Types Data Definition Language (DDL) Creating Tables in Oracle Inserting Data Updating Data Deleting Data
    • Relational Databases Short 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 ZZZ Alexiev Danail 102 YYY Spasov Rosen 101 XXX Nakov Svetlin 100 EMAIL LAST_NAME FIRST_NAME EMPLOYEE_ID 124 Finances 50 201 Sales 20 200 IT 10 MANAGER_ID DEPARTMENT_NAME DEPARTMENT_ID
    • Data Models Model of system in client's mind Table model of entity model Entity model of client's model Database
    • 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 o job title DEPARTMENT #* number * name o 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: DEPARTMENTS Primary key Foreign key Primary key 90 Alexiev Danail 102 50 Spasov Rosen 101 80 Nakov Svetlin 100 DEPARTMENT_ID LAST_NAME FIRST_NAME EMPLOYEE_ID Finances 50 Sales 20 IT 10 DEPARTMENT_NAME DEPARTMENT_ID
    • Database Terminology Table Name: EMPLOYEES Row Primary key column Column Foreign key column Null value Field 90 Alexiev Danail 102 60 9000 Ivanov Radoslav 10 3 6000 17000 24000 SALARY 90 Spasov Rosen 10 4 50 Nachev Miroslav 101 80 Stoynov Mihail 100 DEPARTMENT_ID LAST_NAME FIRST_NAME EMPLOYEE_ID
    • Relational Databases A relational database: Can be accessed and modified by executing S tructured Q uery L anguage (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 SQL statement is sent to the database SQL statement is entered SELECT department_name FROM departments The result is returned (usually as a table) Database Finances Sales IT DEPARTMENT_NAME
    • 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) Diagrams The HR Database Schema in Oracle Express
    • The HR Database Schema in Oracle 10g
    • SQL Language Introducing SELECT Statement
    • Capabilities of SQL SELECT Table 1 Table 2 Table 1 Table 1 Selection Take some of the rows Projection Take some of the columns Join Combine tables by some 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 124 201 200 MANAGER_ID 1900 Shipping 50 1800 Marketing 20 1700 Administration 10 LOCATION_ID DEPARTMENT_NAME DEPARTMENT_ID 1900 50 1800 20 1700 10 LOCATION_ID DEPARTMENT_ID
    • Arithmetic Operations Arithmetic operators are available: +, -, *, / Example: SELECT LAST_NAME, SALARY, SALARY + 300 FROM EMPLOYEES 17000 17000 24000 SALARY 17300 De Haan 17300 Kochhar 24300 King SALARY + 300 LAST_NAME
    • 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 NULL is displayed as empty space or as (null) 100 100 (null) MANAGER_ID De Haan Kochhar King LAST_NAME
    • 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 204000 288000 Annual Salary Kochhar King Name
    • 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 De Haan AD_VP Kochhar AD_VP King AD_PRES Employees
    • 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 De Haan is a AD_VP Kochhar is a AD_VP King is a AD_PRES Employees
    • 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 SELECT DISTINCT DEPARTMENT_ID FROM EMPLOYEES 60 ... 90 90 DEPARTMENT_ID ... 60 90 DEPARTMENT_ID
    • 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 Abel Adam Alana Alberto ... NAME
    • 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' SELECT LAST_NAME, SALARY FROM EMPLOYEES WHERE SALARY <= 3000 De Haan Kochhar King LAST_NAME 90 90 90 DEPARTMENT_ID
    • 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%'
    • 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%'
    • 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 SELECT LAST_NAME, HIRE_DATE FROM EMPLOYEES ORDER BY HIRE_DATE DESC Kochhar Whalen King LAST_NAME 21-SEP-89 17-SEP-87 17-JUN-87 HIRE_DATE Grant Mourgos Zlotkey LAST_NAME 24-MAY-99 16-NOV-99 29-JAN-00 HIRE_DATE
    • SQL Language Selecting Data From Multiple Tables
    • Data from Multiple Tables Sometimes you need data from more than one table: Fay Kochhar King LAST_NAME 20 90 90 DEPARTMENT_ID 10 20 90 DEPARTMENT_ID Administration Marketing Executive DEPARTMENT_NAME Kochhar Fay King LAST_NAME Executive Marketing Executive DEPARTMENT_NAME
    • Cartesian Product This will produce Cartesian product: The result: SELECT LAST_NAME, DEPARTMENT_NAME FROM EMPLOYEES, DEPARTMENTS Administration King Executive Kochhar Marketing Kochhar .. King King LAST_NAME .. Marketing Executive DEPARTMENT_NAME
    • 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 columns SELECT DEPARTMENT_ID, DEPARTMENT_NAME, LOCATION_ID, CITY FROM DEPARTMENTS NATURAL JOIN LOCATIONS ... Executive Administration Shipping IT DEPARTMENT_NAME ... 1700 1700 1500 1400 LOCATION_ID Seattle 10 Seattle 90 ... ... 50 60 DEPARTMENT_ID San Francisco Southlake CITY
    • 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 FROM EMPLOYEES E JOIN DEPARTMENTS D USING (DEPARTMENT_ID) IT 1400 Hunold 103 IT 1400 Ernst 104 ... 1700 LOCATION_ID ... De Haan LAST_NAME ... Executive DEPARTMENT_NAME ... 102 EMPLOYEE_ID
    • 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 FROM EMPLOYEES E JOIN DEPARTMENTS D ON (E.DEPARTMENT_ID = D.DEPARTMENT_ID) 20 20 10 DEPARTMENT_ID 20 20 10 DEPARTMENT_ID Fay Hartstein Whalen LAST_NAME 1800 1800 1700 LOCATION_ID 202 201 200 EMPLOYEE_ID
    • 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_NAME FROM EMPLOYEES E INNER JOIN DEPARTMENTS D ON E.EMPLOYEE_ID=D.MANAGER_ID Shipping 50 Adam Fripp IT 60 Alexander Hunold Public Relations 70 Hermann Baer Human Resources 40 Susan Mavris Purchasing 30 Den Raphaely ... 20 10 DEPARTMENT_ID ... Marketing Administration DEPARTMENT_ NAME ... Michael Hartstein Jennifer Whalen MANAGER_NAME
    • LEFT OUTER JOIN SELECT E.FIRST_NAME || ' ' || E.LAST_NAME AS MANAGER_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAME FROM EMPLOYEES E LEFT OUTER JOIN DEPARTMENTS D ON E.EMPLOYEE_ID=D.MANAGER_ID (null) (null) Jason Mallin (null) (null) Hazel Philtanker (null) (null) Nanette Cambrault (null) (null) Clara Vishney Purchasing 30 Den Raphaely ... 20 10 DEPARTMENT_ID ... Marketing Administration DEPARTMENT_ NAME ... Michael Hartstein Jennifer Whalen MANAGER_NAME
    • RIGHT OUTER JOIN SELECT E.FIRST_NAME || ' ' || E.LAST_NAME AS MANAGER_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAME FROM EMPLOYEES E RIGHT OUTER JOIN DEPARTMENTS D ON E.EMPLOYEE_ID=D.MANAGER_ID Corporate Tax 130 (null) Control And Credit 140 (null) Shareholder Services 150 (null) Treasury 120 (null) Purchasing 30 Den Raphaely ... 20 10 DEPARTMENT_ID ... Marketing Administration DEPARTMENT_ NAME ... Michael Hartstein Jennifer Whalen MANAGER_NAME
    • FULL OUTER JOIN SELECT E.FIRST_NAME || ' ' || E.LAST_NAME AS MANAGER_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAME FROM EMPLOYEES E FULL OUTER JOIN DEPARTMENTS D ON E.EMPLOYEE_ID=D.MANAGER_ID (null) (null) Jason Mallin ... ... ... Shareholder Services 150 (null) (null) (null) Clara Vishney ... ... ... ... 20 10 DEPARTMENT_ID ... Marketing Administration DEPARTMENT_ NAME ... Michael Hartstein Jennifer Whalen MANAGER_NAME
    • 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 JOIN LOCATIONS L ON D.LOCATION_ID = L.LOCATION_ID Administration San Francisco 124 ... Southlake Southlake CITY ... IT IT DEPARTMENT_ NAME ... 104 103 EMPLOYEE_ID
    • 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 Administration King Executive Kochhar .. King King LAST_NAME .. Marketing Executive DEPARTMENT_NAME
    • 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_NAME FROM EMPLOYEES E JOIN DEPARTMENTS D ON (E.DEPARTMENT_ID = D.DEPARTMENT_ID) WHERE E.MANAGER_ID = 149 Sales 80 149 Ellen Abel 174 Sales 80 149 Alyssa Hutton 175 ... DEPARTMENT_ID ... MANAGER_ID ... NAME ... DEPARTMENT_NAME ... EMPLOYEE_ID
    • SQL Language Nested 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, SALARY FROM EMPLOYEES WHERE SALARY = (SELECT MAX(SALARY) FROM EMPLOYEES) SELECT FIRST_NAME, LAST_NAME, SALARY FROM EMPLOYEES WHERE 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 E WHERE EXISTS (SELECT EMPLOYEE_ID FROM JOB_HISTORY JH WHERE DEPARTMENT_ID = 110 AND JH.EMPLOYEE_ID=E.EMPLOYEE_ID)
    • SQL Language Aggregating Data
    • Group Functions Group functions operate on sets of rows to give one result per group 17000 102 17000 101 6000 104 ... 9000 24000 SALARY ... 103 100 EMPLOYEE_ID 24000 MAX(SALARY)
    • 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 EMPLOYEES WHERE JOB_ID LIKE '%REP%' 273000 SUM(SALARY) 6000 MIN(SALARY) 11500 MAX(SALARY) 8272.72 AVG(SALARY)
    • 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 SELECT MIN(LAST_NAME), MAX(LAST_NAME) FROM EMPLOYEES 29-JAN-00 MAX(HIRE_DATE) 17-JUN-1987 MIN(HIRE_DATE)
    • 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 SELECT COUNT(COMMISSION_PCT) FROM EMPLOYEES WHERE DEPARTMENT_ID = 80 5 COUNT(*) 3 COUNT(COMMISION_PCT)
    • 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 .2229 AVG(COMMISSION_PCT)
    • SQL Language Group Functions and the GROUP BY Statement
    • Creating Groups of Data EMPLOYEES 11300 23400 16500 20300 6000 20 6500 40 2600 50 4400 2 0 13000 20 10000 40 12000 110 8300 110 2600 50 3000 50 ... 3100 SALARY ... 50 DEPARTMENT_ID ... ... 20 3 00 110 1 6500 40 23400 2 0 11300 50 SUM(SALARY) DEPARTMENT_ID
    • 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 EMPLOYEES GROUP BY DEPARTMENT_ID ... ... 7000 (null) 24900 30 51600 100 SUM(SALARY) DEPARTMENT_ID
    • Grouping by Several Columns 4400 25000 7500 43500 EMPLOYEES EMPLOYEES ... PU_MAN PU_MAN PU_MAN PU_MAN PU_CLERK PU_CLERK PU_CLERK MK_MAN MK_MAN AD_ASST JOB_ID 11000 30 11500 30 2500 30 2500 30 2500 30 10000 30 11000 30 12000 20 13000 20 ... 4400 SALARY ... 20 DEPARTMENT_ID ... PU_MAN PU_CLERK MK_MAN AD_ASST JOB_ID ... ... 43500 30 7500 30 25000 20 4400 20 SUM(SALARY) DPT_ID
    • Grouping by Several Columns – Example Example of grouping data by several columns: SELECT DEPARTMENT_ID, JOB_ID, COUNT(EMPLOYEE_ID), SUM(SALARY) FROM EMPLOYEES GROUP BY DEPARTMENT_ID, JOB_ID ORDER BY SUM(SALARY) DESC ... 80 50 80 DEPARTMENT_ID ... SA_MAN SH_CLERK SA_REP JOB_ID ... ... 61000 5 64300 20 243500 29 SUM(SALARY) COUNT( EMPLOYEE_ID)
    • 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;
    • 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 EMPLOYEES GROUP BY DEPARTMENT_ID HAVING COUNT(EMPLOYEE_ID) BETWEEN 3 AND 6 60 90 30 100 DEPARTMENT_ID 5760 5 19333.33 3 4150 6 8600 6 AVG (SALARY) COUNT(EMPLOYEE_ID)
    • 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 WHERE HIRE_DATE BETWEEN '1991-1-1' AND '1997-12-31' GROUP BY DEPARTMENT_NAME HAVING COUNT(*) > 5 ORDER BY EMPS DESC 15 19 EMPS Sales Shipping DEPARTMENT_NAME
    • Oracle Data Types Overview
    • 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 Language Data 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 AS SELECT NAME FROM PERSONS WHERE ROWNUM <= 10
    • Modifying Objects ALTER command ALTER TABLE <name> <command> ALTER -- Add a foreign key constraint TOWN --> COUNTIRY ALTER TABLE TOWN ADD CONSTRAINT TOWN_COUNTRY_FK FOREIGN KEY (COUNTRY_ID) 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"
    • 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 Tables Best 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_INSERT BEFORE INSERT ON PERSONS FOR EACH ROW BEGIN SELECT SEQ_PERSONS.nextval INTO :new.PERSON_ID FROM dual; END;
    • SQL Language Inserting 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 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
    • SQL Language Updating Data in the Tables
    • Updating Data UPDATE command UPDATE <table> SET <column=expression> WHERE <condition> 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
    • 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 Language Deleting 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 = 1 DELETE FROM PERSONS WHERE NAME LIKE 'S%' TRUNCATE TABLE PERSONS
    • Problems What is SQL? What is DML? What is DDL? Recite the most important SQL commands. What is PL/SQL? Start Oracle SQL Developer and connect to the database. Use the HR user. Examine the major tables in the HR schema. Write a SQL query to find all information about all department. Write a SQL query to find all department names. 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) 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 " [email_address] ". The produced column should be names "Full Email Address". Write a SQL query to find all different salaries that are paid to the employees. Write a SQL query to find all information about the employees whose position is "AC_MGR" (Accounting Manager). Write a SQL query to find the names of all employees whose first name starts with "Sa".
    • Problems (3) Write a SQL query to find the names of all employees whose last name contains the character sequence " ei ". Write a SQL query to find the names of all employees whose salary is in the range [3000...5000]. Write a SQL query to find the names of all employees whose salary is 2500, 4000 or 5000. Write a SQL query to find all locations that has no state or post code defined. Write a SQL query to find all employees that are paid more than 10000. Order them in decreasing order by salary.
    • Problems (4) Write a SQL query to find to top 5 best paid employees. Write a SQL query to find all departments and the town of their location. Use natural join. Write a SQL query to find all departments and the town of their location. Use join with USING clause. Write a SQL query to find all departments and the town of their location. Use inner join with ON clause. 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) Write a SQL query to find the manager of each department. Write a SQL query to find the location of each department manager. 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. 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. 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) Write a SQL query to find the average salary in the "Sales" department. Write a SQL query to find the number of employees in the "Sales" department. Write a SQL query to find the number of all locations where the company has an office. Write a SQL query to find the number of all departments that has manager. Write a SQL query to find the number of all departments that has no manager. Write a SQL query to find all departments and the average salary for each of them.
    • Problems (7) Write a SQL query to find the count of all employees in each department and for each manager. Write a SQL query to find all managers that have exactly 5 employees. Display their names and the name and location of their department. Write a SQL query to find all departments along with their managers. For departments that do not have manager display "(no manager)". Write a SQL query to find the names of all employees whose last name is exactly 5 characters long. Write a SQL query to print the current date and time in the format " day.month.year hour:minutes:seconds ".
    • Problems (8) 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. 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) 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. 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. Write SQL statements to insert several records in the USERS and GROUPS tables.
    • Problems (10) 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. Write a SQL statement that changes the password to NULL for all USERS that have not been in the system since 10.03.2006. Write a SQL statement that deletes all users without passwords (NULL or empty password).
    • Homework Write a SQL query to display the average employee salary by country. Write a SQL query to display the average employee salary by region. Write a SQL query to display the country of each employee along with his name and department city. Write a SQL query to display the country where maximal number of employees work. Write a SQL query to display the number of managers for each region and each country. 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) Define foreign key between the tables WORKHOURS and EMPLOYEE. Add additional column in the employee table if needed. Write several SQL statements to fill some data in the WORKHOURS table. Write a SQL query to find all the average work hours per week for each country. Write a SQL query to find all the departments where some employee worked overtime (over 8 hours/day) during the last week. 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.