Presentation is loading. Please wait.

Presentation is loading. Please wait.

STRUCTURED QUERY LANGUAGE SQL-II IST 210 Organization of Data IST210 1.

Similar presentations


Presentation on theme: "STRUCTURED QUERY LANGUAGE SQL-II IST 210 Organization of Data IST210 1."— Presentation transcript:

1 STRUCTURED QUERY LANGUAGE SQL-II IST 210 Organization of Data IST210 1

2 Quick review of last lecture IST210 2

3 Insert Data to Department Table IST210 3 One to one mapping INSERT INTO DEPARTMENT VALUES('Administration', 'BC-100-10', 'BLDG01-300', '360-285- 8100');

4 Insert Data to Employee Table IST210 4 EmployeeNumber is a surrogate key, no need to insert EmployeeNumber Department is a foreign key, so we need to make sure it does exist in the DEPARTMENT table INSERT INTO EMPLOYEE VALUES( 'Mary', 'Jacobs', 'Administration', '360-285-8110', 'Mary.Jacobs@WPC.com');

5 Insert Data to Employee Table IST210 5 What if no phone number information for this employee? (When we define EMPLOYEE table, we allow phone number to be NULL) We need to specify the table and corresponding columns INSERT INTO EMPLOYEE(FirstName, LastName, Department, Email) VALUES('James', 'Nestor', 'InfoSystems', 'James.Nestor@WPC.com'); INSERT INTO EMPLOYEE VALUES('James', 'Nestor', 'InfoSystems', NULL, 'James.Nestor@WPC.com'); OR

6 Drop Tables IST210 6 Wrong order!!! Employee is dependent on Department Must delete Employee before deleting Department Correct order! The reverse order of the order we create these tables

7 Data Preparation Login Microsoft SQL Server 1. Start --> Application Development and Management --> Microsoft SQL Server 2014 --> SQL Server 2014 Management Studio 2. Server Type: Database Engine 3. Server Name: upsql 4. Authentication: Windows Authentication 5. Hit “Connect” IST210 7

8 Data Preparation Prepare tables 1. Download SQL script files from schedule page http://sites.psu.edu/ist210w/schedule/ Download 3-SQL-Files http://sites.psu.edu/ist210w/wp- content/uploads/sites/21485/2015/08/SQL-scripts.ziphttp://sites.psu.edu/ist210w/wp- content/uploads/sites/21485/2015/08/SQL-scripts.zip Execute them one by one 1. 3-SQL-Delete-Tables.sql 2. 3-SQL-Create-Tables.sql 3. 3-SQL-Insert-Data.sql IST210 8

9 Running Example IST210 9

10 Check Your Database Click “New Query” Type Click “Execute” See whether it shows 5 rows in the results panel You can try other tables by replacing “PROJECT” with other table names IST210 10 SELECT * FROM PROJECT;

11 View the Database Diagram IST210 11 Right click “Database Diagrams” Click “New Database Diagrams” Select all tables Right click “Database Diagrams” Click “New Database Diagrams” Select all tables

12 Content in today’s class Query: SELECT … FROM … WHERE Query a single table IST210 12

13 Queries SELECT is the best known SQL statement SELECT will retrieve information from the database that matches the specified criteria using the SELECT / FROM / WHERE framework SELECT ColumnName FROM Table WHERECondition; IST210 13

14 SQL for Data Retrieval: The Results of a Query is a Relation A query pulls information from one or more relations and creates (temporarily) a new relation This allows a query to: Create a new relation Feed information to another query (as a “sub-query”) IST210 14

15 SQL for Data Retrieval: Displaying All Columns To show all of the column values for the rows that match the specified criteria, use an asterisk ( * ) SELECT * FROM PROJECT; IST210 15

16 SQL for Data Retrieval: Displaying Specified Columns The following SQL statement queries three of the six columns of the PROJECT table: SELECT ProjectName, Department, MaxHours FROM PROJECT; IST210 16

17 SQL for Data Retrieval: Showing Each Row Only Once The DISTINCT keyword may be added to the SELECT statement to inhibit duplicate rows from displaying SELECT Department FROM EMPLOYEE; SELECT DISTINCT Department FROM EMPLOYEE; IST210 17

18 Exercise 1 Q1. Show all the firstname and lastname of employees Q2. Show all distinct firstname of employees IST210 18 SELECT FirstName, LastName FROM EMPLOYEE; SELECT DISTINCT FirstName FROM EMPLOYEE;

19 SQL for Data Retrieval: Specifying Search Criteria The WHERE clause stipulates the matching criteria for the record that are to be displayed IST210 19 SELECT* FROMPROJECT WHEREDepartment = 'Finance'; SELECT* FROMPROJECT WHEREMaxHours > 135;

20 SQL for Data Retrieval: Match Criteria The WHERE clause match criteria may include Equals “=“ Not Equals “<>” Greater than “>” Less than “<“ Greater than or Equal to “>=“ Less than or Equal to “<=“ IST210 20

21 SQL for Data Retrieval: Match Operators Multiple matching criteria may be specified using AND Representing an intersection of the data sets OR Representing a union of the data sets IST210 21

22 SQL for Data Retrieval: Operator Examples SELECT* FROMPROJECT WHEREDepartment = 'Finance' AND MaxHours > 135; SELECT* FROMPROJECT WHEREDepartment = 'Finance' OR MaxHours > 135; IST210 22

23 Exercise 2 Q1. Show all the employees with firstname as Mary or department is Finance Q2. Show all the employees with department is Finance or Accounting or Marketing IST210 23 SELECT * FROM EMPLOYEE WHERE FirstName = 'Mary' OR Department = 'Finance'; SELECT * FROM EMPLOYEE WHERE Department='Finance' or Department='Accounting' or Department='Marketing';

24 SQL for Data Retrieval: A List of Values The WHERE clause may include the IN keyword to specify that a particular column value must be included in a list of values SELECT FirstName, LastName, Department FROM EMPLOYEE WHERE Department IN ('Finance', 'Accounting', 'Marketing'); IST210 24

25 SQL for Data Retrieval: The Logical NOT Operator Any criteria statement may be preceded by a NOT operator which is to say that all information will be shown except that information matching the specified criteria SELECT FirstName, LastName, Department FROM EMPLOYEE WHERE Department NOT IN ('Accounting', 'Finance', 'Marketing'); IST210 25

26 SQL for Data Retrieval: Allowing for Wildcard Searches The SQL LIKE keyword allow searches on partial data values LIKE can be paired with wildcards to find rows matching a string value Multiple character wildcard character is a percentage sign (%) Single character wildcard character is an underscore (_) IST210 26

27 SQL for Data Retrieval: Wildcard Search Examples Find all employees whose last name starts with “J”. SELECT* FROM EMPLOYEE WHERE LastName LIKE 'J%'; Find all employees whose last name starts with “J” and only has 5 letters in total. SELECT * FROM EMPLOYEE WHERElastName LIKE 'J____'; IST210 27

28 Exercise 3 Q1. Find employees that have first name ends with “y” and has 4 letters in total IST210 28 SELECT * FROM EMPLOYEE WHERE FirstName LIKE '___Y';

29 Exercise 3 Q2. Find employees that have first name starts with letter “R” and ends with letter “d” IST210 29 SELECT* FROMEMPLOYEE WHEREFirstName LIKE ’R%d';

30 Exercise 3 Q3. Find employees that have first name with the 3 rd letter is “a” and ends with letter “r” IST210 30 SELECT* FROMEMPLOYEE WHEREFirstName LIKE '__a%r';

31 SQL for Data Retrieval: IS NULL Keyword Find all rows which have null values for an specified attribute: SELECT FirstName, LastName, Phone, Department FROMEMPLOYEE WHEREPhone IS NULL; IST210 31 SELECTFirstName, LastName, Phone, Department FROMEMPLOYEE WHEREPhone = NULL; Bad query

32 SQL for Data Retrieval: Sorting the Results Query results may be sorted using the ORDER BY clause SELECT * FROM EMPLOYEE ORDER BY LastName; IST210 32

33 SQL for Data Retrieval: Sorting the Results By default, SQL sorts in ascending order. To sort in descending order, use: IST210 33 SELECT * FROM EMPLOYEE ORDER BY LastName Desc;

34 SQL for Data Retrieval: Sorting the Results Sort the result by LastName in descending order, and then by FirstName in ascending order IST210 34 SELECT * FROM EMPLOYEE ORDER BY LastName DESC, FirstName ASC;

35 SQL for Data Retrieval: Built-in SQL Functions SQL provides several built-in functions COUNT Counts the number of rows that match the specified criteria MIN Finds the minimum value for a specific column for those rows matching the criteria MAX Finds the maximum value for a specific column for those rows matching the criteria SUM Calculates the sum for a specific column for those rows matching the criteria AVG Calculates the numerical average of a specific column for those rows matching the criteria IST210 35

36 SQL for Data Retrieval: Built-in Function Examples Count the total number of projects: SELECT COUNT(*) FROM PROJECT; Find the minimum, maximum, and average hours for all projects. SELECT MIN(MaxHours) AS MinimumHours, MAX(MaxHours) AS MaximumHours, AVG(MaxHours) AS AverageHours FROM PROJECT IST210 36

37 Exercise 4 Q1. Count how many projects with MaxHours less than 130 IST210 37 /*** Count how many projects with MaxHours less than 130 ***/ SELECT COUNT(*) FROM PROJECT WHEREMaxHours < 130;

38 Exercise 4 Q2. Show average MaxHours of all projects IST210 38 SELECT AVG(MaxHours) FROMPROJECT;

39 Exercise 4 (Challenging question) Can you use one SQL query to answer: Count how many projects with MaxHours less than average MaxHours? IST210 39 SELECT COUNT(*) FROM PROJECT WHERE MaxHours < (SELECT AVG(MaxHours) FROM PROJECT); Cannot say: WHERE MaxHours<AVG(MaxHours); Build-in functions cannot be used in WHERE clauses.

40 SQL for Data Retrieval: Providing Subtotals: GROUP BY How many employees each department has? Subtotals may be calculated by using the GROUP BY clause Show how many employees in each department SELECT Department, COUNT(*) AS NumOfEmployees FROM EMPLOYEE GROUP BY Department The GROUP BY keyword tells the DBMS to sort the table by the named column and then to apply the build-in function to groups of rows that have the same value for the named column. IST210 40

41 SQL for Data Retrieval: Providing Subtotals: GROUP BY Further restrict results by using the HAVING clause Only show those departments with more than one employee The HAVING clause may be used to restrict which data is displayed SELECT Department, COUNT(*) AS NumOfEmployees FROM EMPLOYEE GROUP BY Department HAVING COUNT(*) > 1; IST210 41

42 Exercise 5 Q1. Group assignments by employees. Show employee numbers and total hours work IST210 42 SELECT EmployeeNumber, SUM(HoursWorked) FROM ASSIGNMENT GROUP BY EmployeeNumber;

43 Exercise 5 Q1. Group assignments by employees. Show employee numbers and total hours work Q2. Add a constraint to Q1: the employees with total hours worked more than 100 IST210 43 SELECT EmployeeNumber, SUM(HoursWorked) FROM ASSIGNMENT GROUP BY EmployeeNumber HAVING SUM(HoursWorked) > 100;

44 Exercise 5 Q1. Group assignments by employees. Show employee numbers and total hours work Q3. Add a constraint to Q1: only show the employees with employee number less than 5 Try to use two ways to answer this query IST210 44 SELECT EmployeeNumber, SUM(HoursWorked) FROM ASSIGNMENT GROUP BY EmployeeNumber HAVING EmployeeNumber < 5; SELECT EmployeeNumber, SUM(HoursWorked) FROM ASSIGNMENT WHERE EmployeeNumber < 5 GROUP BY EmployeeNumber;

45 Assignment 3-1 Assignment 3 is divided into two parts Part 1 (40 points) is on course website now, and is due on Monday Sept 28 th (no late submission!) How to access SQL? Come and work in the classroom Use remote desktop (if working outside of IST) https://www.up.ist.psu.edu/vlabs/ Requires SQL programming, so start early! Be sure to finish Assignment 3-1 and 3-2: very important for midterm! IST210 45


Download ppt "STRUCTURED QUERY LANGUAGE SQL-II IST 210 Organization of Data IST210 1."

Similar presentations


Ads by Google