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

Slides:



Advertisements
Similar presentations
Database Queries and Structured Query Language (SQL) J.G. Zheng May 16 th 2008.
Advertisements

SQL-week5-1 In-Class Exercise Answer IST 210 Organization of Data IST2101.
4c. Structured Query Language - Built-in Functions Lingma Acheson Department of Computer and Information Science IUPUI CSCI N207 Data Analysis with Spreadsheets.
Copyright © by Royal Institute of Information Technology Introduction To Structured Query Language (SQL) 1.
Introduction to Structured Query Language (SQL)
Fundamentals, Design, and Implementation, 9/e COS 346 Day 11.
Introduction to Structured Query Language (SQL)
© 2002 by Prentice Hall 1 David M. Kroenke Database Processing Eighth Edition Chapter 9 Structured Query Language.
Fundamentals, Design, and Implementation, 9/e Chapter 6 Introduction to Structured Query Language (SQL)
Structured Query Language Part I Chapter Three CIS 218.
Structured Query Language Chapter Three (Excerpts) DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Introduction to Structured Query Language (SQL)
Structured Query Language Chapter Three DAVID M. KROENKE and DAVID J. AUER DATABASE CONCEPTS, 6 th Edition.
Structured Query Language Chapter Three DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Structured Query Language (SQL)
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
Concepts of Database Management Sixth Edition
A Guide to SQL, Seventh Edition. Objectives Retrieve data from a database using SQL commands Use compound conditions Use computed columns Use the SQL.
Microsoft Access 2010 Chapter 7 Using SQL.
SQL for Data Retrieval. Save your SQL Scripts When working with SQL Management Studio, you should keep saving your scripts as a.sql file to somewhere.
+ Structured Query Language Part 2 KROENKE and AUER - DATABASE CONCEPTS (6th Edition) Copyright © 2013 Pearson Education, Inc. Publishing as Prentice Hall.
SQL Operations Aggregate Functions Having Clause Database Access Layer A2 Teacher Up skilling LECTURE 5.
Structured Query Language
SQL for Data Retrieval. Running Example IST2102 Data Preparation Login to SQL server using your account Download three SQL script files from wiki page.
Introduction to SQL J.-S. Chou Assistant Professor.
ASP.NET Programming with C# and SQL Server First Edition
Structured Query Language Chapter Three DAVID M. KROENKE and DAVID J. AUER DATABASE CONCEPTS, 5 th Edition.
15 Structured Query Language (SQL). 2 Objectives After completing this section, you should be able to: Understand Structured Query Language (SQL) and.
Chapter 3 Single-Table Queries
Structured Query Language Chapter Three DAVID M. KROENKE and DAVID J. AUER DATABASE CONCEPTS, 4 th Edition.
Microsoft Access 2010 Chapter 7 Using SQL. Change the font or font size for SQL queries Create SQL queries Include fields in SQL queries Include simple.
 SQL stands for Structured Query Language.  SQL lets you access and manipulate databases.  SQL is an ANSI (American National Standards Institute) standard.
SQL – Structured Query Language CIS 324 – Chapter 5.
Fundamentals, Design, and Implementation, 9/e CPE 481 Database Processing Chapter 6 Structured Query Language (SQL) Instructor:Suthep Madarasmi, Ph.D.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
Using Special Operators (LIKE and IN)
Concepts of Database Management Seventh Edition
Structured Query Language SQL-I
Structured Query Language (SQL) IST2101. Structured Query Language – Acronym: SQL – Pronounced as “S-Q-L” [“Ess-Que-El”] – Originally developed by IBM.
Database Processing: Fundamentals, Design, and Implementation, 9/e by David M. KroenkeChapter 6/1 Copyright © 2004 Please……. No Food Or Drink in the class.
SQL for Data Retrieval. Review Questions of Previous Class Q1. Show the sum of hours worked for project with ID 1200 (use ASSIGNMENT table) – Use “SUM”
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
SQL for Data Retrieval. Running Example IST2102 Data Preparation Login to SQL server using your account Select your database – Your database name is.
Concepts of Database Management Eighth Edition Chapter 3 The Relational Model 2: SQL.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Database Management COP4540, SCS, FIU Structured Query Language (Chapter 8)
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
STRUCTURED QUERY LANGUAGE SQL-III IST 210 Organization of Data IST210 1.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
SQL for Data Retrieval. Save your SQL Scripts When working with SQL Management Studio, you should keep saving your scripts as a.sql file to somewhere.
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Concepts of Database Management Seventh Edition Chapter 3 The Relational Model 2: SQL.
SQL-5 In-Class Exercise Answer IST 210 Organization of Data IST2101.
ITEC 3220A Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220a.htm
Structured Query Language
© 2002 by Prentice Hall 1 Structured Query Language David M. Kroenke Database Concepts 1e Chapter 3 3.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
Database: SQL, MySQL, LINQ and Java DB © by Pearson Education, Inc. All Rights Reserved.
+ Structured Query Language Part 2 KROENKE and AUER - DATABASE CONCEPTS (6th Edition) Copyright © 2013 Pearson Education, Inc. Publishing as Prentice Hall.
1 Chapter 3 Single Table Queries. 2 Simple Queries Query - a question represented in a way that the DBMS can understand Basic format SELECT-FROM Optional.
PHP AND SQL SERVER: QUERIES IST 210: Organization of Data IST210 1.
SQL: Structured Query Language It enables to create and operate on relational databases, which are sets of related information stored in tables. It is.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
Structured Query Language SQL-II IST 210 Organization of Data IST2101.
Structured Query Language SQL-I IST 210 Organization of Data IST2101.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
SQL.
Structured Query Language
Shelly Cashman: Microsoft Access 2016
Presentation transcript:

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

Quick review of last lecture IST210 2

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

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', ' ',

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, ) VALUES('James', 'Nestor', 'InfoSystems', INSERT INTO EMPLOYEE VALUES('James', 'Nestor', 'InfoSystems', NULL, OR

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

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

Data Preparation Prepare tables 1. Download SQL script files from schedule page Download 3-SQL-Files 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

Running Example IST210 9

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 IST SELECT * FROM PROJECT;

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

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

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

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

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

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

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

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

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

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

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

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

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 IST SELECT * FROM EMPLOYEE WHERE FirstName = 'Mary' OR Department = 'Finance'; SELECT * FROM EMPLOYEE WHERE Department='Finance' or Department='Accounting' or Department='Marketing';

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

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

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

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

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

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

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

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; IST SELECTFirstName, LastName, Phone, Department FROMEMPLOYEE WHEREPhone = NULL; Bad query

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

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

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

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

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

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

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

Exercise 4 (Challenging question) Can you use one SQL query to answer: Count how many projects with MaxHours less than average MaxHours? IST 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.

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

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

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

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 IST SELECT EmployeeNumber, SUM(HoursWorked) FROM ASSIGNMENT GROUP BY EmployeeNumber HAVING SUM(HoursWorked) > 100;

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 IST SELECT EmployeeNumber, SUM(HoursWorked) FROM ASSIGNMENT GROUP BY EmployeeNumber HAVING EmployeeNumber < 5; SELECT EmployeeNumber, SUM(HoursWorked) FROM ASSIGNMENT WHERE EmployeeNumber < 5 GROUP BY EmployeeNumber;

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) Requires SQL programming, so start early! Be sure to finish Assignment 3-1 and 3-2: very important for midterm! IST210 45