SlideShare a Scribd company logo
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 (&quot;COMMENT&quot; VARCHAR2(800)) -- Remove column COMMENT from the table PERSON ALTER TABLE PERSONS DROP COLUMN &quot;COMMENT&quot;
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 &quot; [email_address] &quot;. The produced column should be names &quot;Full Email Address&quot;. 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 &quot;AC_MGR&quot; (Accounting Manager). Write a SQL query to find the names of all employees whose first name starts with &quot;Sa&quot;.
Problems (3) Write a SQL query to find the names of all employees whose last name contains the character sequence &quot; ei &quot;. 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 &quot;Sales&quot; and &quot;Finance&quot; 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 &quot;Sales&quot; department. Write a SQL query to find the number of employees in the &quot;Sales&quot; 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 &quot;(no manager)&quot;. 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 &quot; day.month.year hour:minutes:seconds &quot;.
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.
Ad

More Related Content

What's hot (20)

Sql commands
Sql commandsSql commands
Sql commands
Pooja Dixit
 
Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)
Punjab University
 
SQL
SQLSQL
SQL
Shunya Ram
 
Joins in SQL
Joins in SQLJoins in SQL
Joins in SQL
Vigneshwaran Sankaran
 
SQL
SQLSQL
SQL
Shyam Khant
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL Commands
Shrija Madhu
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
Rumman Ansari
 
Sql select
Sql select Sql select
Sql select
Mudasir Syed
 
SQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredSQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics Covered
Danish Mehraj
 
SQL
SQLSQL
SQL
Vineeta Garg
 
Sql(structured query language)
Sql(structured query language)Sql(structured query language)
Sql(structured query language)
Ishucs
 
Sql clauses by Manan Pasricha
Sql clauses by Manan PasrichaSql clauses by Manan Pasricha
Sql clauses by Manan Pasricha
MananPasricha
 
Mysql
MysqlMysql
Mysql
TSUBHASHRI
 
DATABASE CONSTRAINTS
DATABASE CONSTRAINTSDATABASE CONSTRAINTS
DATABASE CONSTRAINTS
sunanditaAnand
 
SQL commands
SQL commandsSQL commands
SQL commands
GirdharRatne
 
MySql:Introduction
MySql:IntroductionMySql:Introduction
MySql:Introduction
DataminingTools Inc
 
Sql – Structured Query Language
Sql – Structured Query LanguageSql – Structured Query Language
Sql – Structured Query Language
pandey3045_bit
 
Sql join
Sql  joinSql  join
Sql join
Vikas Gupta
 
Sql joins
Sql joinsSql joins
Sql joins
Gaurav Dhanwant
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands
1keydata
 

Viewers also liked (12)

Ms sql server architecture
Ms sql server architectureMs sql server architecture
Ms sql server architecture
Ajeet Singh
 
Microsoft SQL Server internals & architecture
Microsoft SQL Server internals & architectureMicrosoft SQL Server internals & architecture
Microsoft SQL Server internals & architecture
Kevin Kline
 
MS Sql Server: Introduction To Database Concepts
MS Sql Server: Introduction To Database ConceptsMS Sql Server: Introduction To Database Concepts
MS Sql Server: Introduction To Database Concepts
DataminingTools Inc
 
Physical architecture of sql server
Physical architecture of sql serverPhysical architecture of sql server
Physical architecture of sql server
Divya Sharma
 
Sql Server Basics
Sql Server BasicsSql Server Basics
Sql Server Basics
rainynovember12
 
Microsoft sql server architecture
Microsoft sql server architectureMicrosoft sql server architecture
Microsoft sql server architecture
Naveen Boda
 
SQL : introduction
SQL : introductionSQL : introduction
SQL : introduction
Shakila Mahjabin
 
A must Sql notes for beginners
A must Sql notes for beginnersA must Sql notes for beginners
A must Sql notes for beginners
Ram Sagar Mourya
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
Sql Server 2012
Sql Server 2012Sql Server 2012
Sql Server 2012
Performics.Convonix
 
Sql ppt
Sql pptSql ppt
Sql ppt
Anuja Lad
 
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Beat Signer
 
Ms sql server architecture
Ms sql server architectureMs sql server architecture
Ms sql server architecture
Ajeet Singh
 
Microsoft SQL Server internals & architecture
Microsoft SQL Server internals & architectureMicrosoft SQL Server internals & architecture
Microsoft SQL Server internals & architecture
Kevin Kline
 
MS Sql Server: Introduction To Database Concepts
MS Sql Server: Introduction To Database ConceptsMS Sql Server: Introduction To Database Concepts
MS Sql Server: Introduction To Database Concepts
DataminingTools Inc
 
Physical architecture of sql server
Physical architecture of sql serverPhysical architecture of sql server
Physical architecture of sql server
Divya Sharma
 
Microsoft sql server architecture
Microsoft sql server architectureMicrosoft sql server architecture
Microsoft sql server architecture
Naveen Boda
 
A must Sql notes for beginners
A must Sql notes for beginnersA must Sql notes for beginners
A must Sql notes for beginners
Ram Sagar Mourya
 
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Beat Signer
 
Ad

Similar to Introduction to-sql (20)

Sql intro
Sql introSql intro
Sql intro
glubox
 
Basic SQL Statments
Basic SQL StatmentsBasic SQL Statments
Basic SQL Statments
Umair Shakir
 
Data Manipulation Language.pptx
Data Manipulation Language.pptxData Manipulation Language.pptx
Data Manipulation Language.pptx
EllenGracePorras
 
Query
QueryQuery
Query
Raj Devaraj
 
Chinabankppt
ChinabankpptChinabankppt
Chinabankppt
newrforce
 
Select To Order By
Select  To  Order BySelect  To  Order By
Select To Order By
Krizia Capacio
 
ALL ABOUT SQL AND RDBMS
ALL ABOUT SQL AND RDBMSALL ABOUT SQL AND RDBMS
ALL ABOUT SQL AND RDBMS
gaurav koriya
 
Db1 lecture4
Db1 lecture4Db1 lecture4
Db1 lecture4
Sherif Gad
 
Lab
LabLab
Lab
neelam_rawat
 
Sql 2006
Sql 2006Sql 2006
Sql 2006
Cathie101
 
sql language
sql languagesql language
sql language
moman abde
 
Introduction to sql new
Introduction to sql newIntroduction to sql new
Introduction to sql new
SANTOSH RATH
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SabrinaShanta2
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SaiMiryala1
 
Class 8 - Database Programming
Class 8 - Database ProgrammingClass 8 - Database Programming
Class 8 - Database Programming
Ahmed Swilam
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
BhupendraShahi6
 
Module03
Module03Module03
Module03
Sridhar P
 
0808.pdf
0808.pdf0808.pdf
0808.pdf
ssuser0562f1
 
0808.pdf
0808.pdf0808.pdf
0808.pdf
ssuser0562f1
 
lect 2.pptx
lect 2.pptxlect 2.pptx
lect 2.pptx
HermanGaming
 
Sql intro
Sql introSql intro
Sql intro
glubox
 
Basic SQL Statments
Basic SQL StatmentsBasic SQL Statments
Basic SQL Statments
Umair Shakir
 
Data Manipulation Language.pptx
Data Manipulation Language.pptxData Manipulation Language.pptx
Data Manipulation Language.pptx
EllenGracePorras
 
Chinabankppt
ChinabankpptChinabankppt
Chinabankppt
newrforce
 
ALL ABOUT SQL AND RDBMS
ALL ABOUT SQL AND RDBMSALL ABOUT SQL AND RDBMS
ALL ABOUT SQL AND RDBMS
gaurav koriya
 
Introduction to sql new
Introduction to sql newIntroduction to sql new
Introduction to sql new
SANTOSH RATH
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SabrinaShanta2
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SaiMiryala1
 
Class 8 - Database Programming
Class 8 - Database ProgrammingClass 8 - Database Programming
Class 8 - Database Programming
Ahmed Swilam
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
BhupendraShahi6
 
Ad

More from BG Java EE Course (20)

Rich faces
Rich facesRich faces
Rich faces
BG Java EE Course
 
JSP Custom Tags
JSP Custom TagsJSP Custom Tags
JSP Custom Tags
BG Java EE Course
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
BG Java EE Course
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
BG Java EE Course
 
JSTL
JSTLJSTL
JSTL
BG Java EE Course
 
Unified Expression Language
Unified Expression LanguageUnified Expression Language
Unified Expression Language
BG Java EE Course
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
BG Java EE Course
 
Web Applications and Deployment
Web Applications and DeploymentWeb Applications and Deployment
Web Applications and Deployment
BG Java EE Course
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
BG Java EE Course
 
CSS
CSSCSS
CSS
BG Java EE Course
 
HTML: Tables and Forms
HTML: Tables and FormsHTML: Tables and Forms
HTML: Tables and Forms
BG Java EE Course
 
HTML Fundamentals
HTML FundamentalsHTML Fundamentals
HTML Fundamentals
BG Java EE Course
 
WWW and HTTP
WWW and HTTPWWW and HTTP
WWW and HTTP
BG Java EE Course
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
BG Java EE Course
 
Creating Web Sites with HTML and CSS
Creating Web Sites with HTML and CSSCreating Web Sites with HTML and CSS
Creating Web Sites with HTML and CSS
BG Java EE Course
 
Processing XML with Java
Processing XML with JavaProcessing XML with Java
Processing XML with Java
BG Java EE Course
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
BG Java EE Course
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
BG Java EE Course
 
Introduction to-RDBMS-systems
Introduction to-RDBMS-systemsIntroduction to-RDBMS-systems
Introduction to-RDBMS-systems
BG Java EE Course
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
BG Java EE Course
 

Recently uploaded (20)

How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 

Introduction to-sql

  • 2. 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
  • 3. 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
  • 4. Contents (3) Oracle SQL Functions Oracle Data Types Data Definition Language (DDL) Creating Tables in Oracle Inserting Data Updating Data Deleting Data
  • 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 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
  • 8. Data Models Model of system in client's mind Table model of entity model Entity model of client's model Database
  • 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 o job title DEPARTMENT #* number * name o location 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 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
  • 11. 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
  • 12. 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
  • 13. 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
  • 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 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],...} FROM table
  • 21. 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
  • 22. 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
  • 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 NULL is displayed as empty space or as (null) 100 100 (null) MANAGER_ID De Haan Kochhar King LAST_NAME
  • 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 &quot;Name&quot; , 12*SALARY AS &quot;Annual Salary&quot; FROM EMPLOYEES 204000 288000 Annual Salary Kochhar King Name
  • 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 &quot;Employees&quot; FROM EMPLOYEES De Haan AD_VP Kochhar AD_VP King AD_PRES Employees
  • 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 &quot;Employee Details&quot; FROM EMPLOYEES De Haan is a AD_VP Kochhar is a AD_VP King is a AD_PRES Employees
  • 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 SELECT DISTINCT DEPARTMENT_ID FROM EMPLOYEES 60 ... 90 90 DEPARTMENT_ID ... 60 90 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 Abel Adam Alana Alberto ... NAME
  • 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' SELECT LAST_NAME, SALARY FROM EMPLOYEES WHERE SALARY <= 3000 De Haan Kochhar King LAST_NAME 90 90 90 DEPARTMENT_ID
  • 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: 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: 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%'
  • 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 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
  • 33. SQL Language Selecting Data From Multiple Tables
  • 34. 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
  • 35. 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
  • 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 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
  • 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 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
  • 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 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
  • 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 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
  • 43. 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
  • 44. 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
  • 45. 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
  • 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 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
  • 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 Administration King Executive Kochhar .. King King LAST_NAME .. Marketing Executive DEPARTMENT_NAME
  • 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.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
  • 49. SQL Language Nested SELECT Statements
  • 50. 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')
  • 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 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)
  • 53. 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)
  • 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) FROM EMPLOYEES WHERE JOB_ID LIKE '%REP%' 273000 SUM(SALARY) 6000 MIN(SALARY) 11500 MAX(SALARY) 8272.72 AVG(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 SELECT MIN(LAST_NAME), MAX(LAST_NAME) FROM EMPLOYEES 29-JAN-00 MAX(HIRE_DATE) 17-JUN-1987 MIN(HIRE_DATE)
  • 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 SELECT COUNT(COMMISSION_PCT) FROM EMPLOYEES WHERE DEPARTMENT_ID = 80 5 COUNT(*) 3 COUNT(COMMISION_PCT)
  • 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 0.0425 SELECT AVG(COMMISSION_PCT) FROM EMPLOYEES .2229 AVG(COMMISSION_PCT)
  • 59. SQL Language Group Functions and the GROUP BY Statement
  • 60. 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
  • 61. 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 >
  • 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 ... ... 7000 (null) 24900 30 51600 100 SUM(SALARY) DEPARTMENT_ID
  • 63. 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
  • 64. 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)
  • 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) 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)
  • 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 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
  • 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 <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
  • 74. 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 (&quot;COMMENT&quot; VARCHAR2(800)) -- Remove column COMMENT from the table PERSON ALTER TABLE PERSONS DROP COLUMN &quot;COMMENT&quot;
  • 75. 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
  • 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 <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
  • 81. SQL Language Updating Data in the Tables
  • 82. 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
  • 83. 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
  • 84. SQL Language Deleting Data from the Tables
  • 85. 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
  • 86. 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.
  • 87. 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 &quot; [email_address] &quot;. The produced column should be names &quot;Full Email Address&quot;. 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 &quot;AC_MGR&quot; (Accounting Manager). Write a SQL query to find the names of all employees whose first name starts with &quot;Sa&quot;.
  • 88. Problems (3) Write a SQL query to find the names of all employees whose last name contains the character sequence &quot; ei &quot;. 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.
  • 89. 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.
  • 90. 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 &quot;Sales&quot; and &quot;Finance&quot; 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.
  • 91. Problems (6) Write a SQL query to find the average salary in the &quot;Sales&quot; department. Write a SQL query to find the number of employees in the &quot;Sales&quot; 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.
  • 92. 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 &quot;(no manager)&quot;. 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 &quot; day.month.year hour:minutes:seconds &quot;.
  • 93. 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.
  • 94. 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.
  • 95. 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).
  • 96. 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).
  • 97. 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.