SQL Data Manipulation Language. Lecture 5. Introduction to SQL language. Last updated: December 10, 2014

Similar documents
Querying Data with Transact SQL

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables

Structure Query Language (SQL)

MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9)

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL)

Data Manipulation Language (DML)

Chapter 7. Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel

CSC Web Programming. Introduction to SQL

SQL functions fit into two broad categories: Data definition language Data manipulation language

Querying Data with Transact-SQL

Querying Data with Transact-SQL

Querying Data with Transact SQL Microsoft Official Curriculum (MOC 20761)

Intermediate SQL: Aggregated Data, Joins and Set Operators

A subquery is a nested query inserted inside a large query Generally occurs with select, from, where Also known as inner query or inner select,

NESTED QUERIES AND AGGREGATION CHAPTER 5 (6/E) CHAPTER 8 (5/E)

GIFT Department of Computing Science. CS-217: Database Systems. Lab-4 Manual. Reporting Aggregated Data using Group Functions

Based on the following Table(s), Write down the queries as indicated: 1. Write an SQL query to insert a new row in table Dept with values: 4, Prog, MO

4. SQL - the Relational Database Language Standard 4.3 Data Manipulation Language (DML)

SQL BASICS WITH THE SMALLBANKDB STEFANO GRAZIOLI & MIKE MORRIS

Language. f SQL. Larry Rockoff COURSE TECHNOLOGY. Kingdom United States. Course Technology PTR. A part ofcenqaqe Learninq

Lesson 2. Data Manipulation Language

1Z Oracle Database 11g - SQL Fundamentals I Exam Summary Syllabus Questions

12. MS Access Tables, Relationships, and Queries

Insertions, Deletions, and Updates

Chapter 3: Introduction to SQL. Chapter 3: Introduction to SQL

SQL - Lecture 3 (Aggregation, etc.)

NESTED QUERIES AND AGGREGATION CHAPTER 5 (6/E) CHAPTER 8 (5/E)

T-SQL Training: T-SQL for SQL Server for Developers

WHAT IS SQL. Database query language, which can also: Define structure of data Modify data Specify security constraints

1) Introduction to SQL

Structured Query Language (SQL)

SQL - Data Query language

Introduction SQL DRL. Parts of SQL. SQL: Structured Query Language Previous name was SEQUEL Standardized query language for relational DBMS:

Lecture 6 - More SQL

More on SQL Nested Queries Aggregate operators and Nulls

Implementing Table Operations Using Structured Query Language (SQL) Using Multiple Operations. SQL: Structured Query Language

II. Structured Query Language (SQL)

COMP 244 DATABASE CONCEPTS & APPLICATIONS

II. Structured Query Language (SQL)

SQL queries II. Set operations and joins

SQL. Rodrigo García Carmona Universidad San Pablo-CEU Escuela Politécnica Superior

Institute of Aga. Network Database LECTURER NIYAZ M. SALIH

Chapter # 7 Introduction to Structured Query Language (SQL) Part II

20461: Querying Microsoft SQL Server 2014 Databases

Simple queries Set operations Aggregate operators Null values Joins Query Optimization. John Edgar 2

SIT772 Database and Information Retrieval WEEK 6. RELATIONAL ALGEBRAS. The foundation of good database design

RELATIONAL DATA MODEL

Retrieving Data Using the SQL SELECT Statement. Copyright 2009, Oracle. All rights reserved.

CSEN 501 CSEN501 - Databases I

Querying Microsoft SQL Server 2014

Relational Database Management Systems for Epidemiologists: SQL Part I

Lab # 6. Using Subqueries and Set Operators. Eng. Alaa O Shama

Institute of Aga. Microsoft SQL Server LECTURER NIYAZ M. SALIH

Querying Data with Transact-SQL (20761)

SQL Queries. COSC 304 Introduction to Database Systems SQL. Example Relations. SQL and Relational Algebra. Example Relation Instances

Database Management Systems,

EECS 647: Introduction to Database Systems

SQL Data Query Language

Announcements (September 14) SQL: Part I SQL. Creating and dropping tables. Basic queries: SFW statement. Example: reading a table

Retrieving Data Using the SQL SELECT Statement. Copyright 2004, Oracle. All rights reserved.

Chapter 4 SQL. Database Systems p. 121/567

Data Infrastructure IRAP Training 6/27/2016

In This Lecture. Yet More SQL SELECT ORDER BY. SQL SELECT Overview. ORDER BY Example. ORDER BY Example. Yet more SQL

"Charting the Course... MOC C: Querying Data with Transact-SQL. Course Summary

Downloaded from

RESTRICTING AND SORTING DATA

Database Programming with SQL

GIFT Department of Computing Science Data Selection and Filtering using the SELECT Statement

KORA. RDBMS Concepts II

Course Modules for MCSA: SQL Server 2016 Database Development Training & Certification Course:

COSC 304 Introduction to Database Systems SQL. Dr. Ramon Lawrence University of British Columbia Okanagan

"Charting the Course to Your Success!" MOC D Querying Microsoft SQL Server Course Summary

ITCertMaster. Safe, simple and fast. 100% Pass guarantee! IT Certification Guaranteed, The Easy Way!

COURSE OUTLINE MOC 20461: QUERYING MICROSOFT SQL SERVER 2014

SQL Retrieving Data from Multiple Tables

Restricting and Sorting Data. Copyright 2004, Oracle. All rights reserved.

ASSIGNMENT NO Computer System with Open Source Operating System. 2. Mysql

Database Foundations. 6-4 Data Manipulation Language (DML) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Assignment 6: SQL III Solution

Database design process

30. Structured Query Language (SQL)

[AVNICF-MCSASQL2012]: NICF - Microsoft Certified Solutions Associate (MCSA): SQL Server 2012

CS 582 Database Management Systems II

SQL Part 2. Kathleen Durant PhD Northeastern University CS3200 Lesson 6

Queries. Chapter 6. In This Chapter. c SELECT Statement: Its Clauses and Functions. c Join Operator c Correlated Subqueries c Table Expressions

Introductory SQL SQL Joins: Viewing Relationships Pg 1

Lecture 06. Fall 2018 Borough of Manhattan Community College

CS 2340 Objects and Design

Database Management Systems,

Restricting and Sorting Data. Copyright 2004, Oracle. All rights reserved.

tablename ORDER BY column ASC tablename ORDER BY column DESC sortingorder, } The WHERE and ORDER BY clauses can be combined in one

SQL: Data Querying. B0B36DBS, BD6B36DBS: Database Systems. h p:// Lecture 4

20761 Querying Data with Transact SQL

RELATIONAL DATA MODEL: Relational Algebra

Data about data is database Select correct option: True False Partially True None of the Above

QUERYING MICROSOFT SQL SERVER COURSE OUTLINE. Course: 20461C; Duration: 5 Days; Instructor-led

The SELECT-FROM-WHERE Structure

Chapter 3: Introduction to SQL

SQL Data Querying and Views

An Introduction to Structured Query Language

Transcription:

Lecture 5 Last updated: December 10, 2014

Throrought this lecture we will use the following database diagram

Inserting rows I The INSERT INTO statement enables inserting new rows into a table. The basic syntax of this statements is as follows: insert into table_name [(column_list)] values (value_list)

Inserting rows II Example Insert some rows to the Employee table. First, we set date format to day-month-year set dateformat dmy An insert statement without the list of columns to which values are inserted insert into Employee values('john','smith','08.08.1980','m','jsmith',null,null) insert into Employee values('justine','parker','24.05.1985','f','jparker',1,null)

Inserting rows III An insert statement with the list of columns (the value for the address_id is omitted, SQL Server provides the null value for it) Employee(first_name,last_name,birth_date,gender,email,manager_id) values('agnes','braun','11.09.1982','f','abraun',1) The INSERT INTO statement can be based on the SELECT clause: INSERT INTO table_name SELECT...

Updating rows I The UPDATE statement allows to update existing rows in a table: UPDATE table_name SET column_name1=value1, column_name2=value2,... [WHERE selection_predicates] If no WHERE clause is dened all rows in the table are updated. Example Increase the salary by 10% for the employees earning between 2000 and 3000. UPDATE Employment SET salary = salary*1.1 WHERE salary between 2000 and 3000 and end_date is null

Updating rows II Example Assign the rst department to the employee John Smith. UPDATE Employee SET address_id = 1 WHERE first_name = 'John' and last_name = 'Smith'

Deleting rows I The DELETE statement is applied to delete existing rows in a table: DELETE FROM table_name [WHERE selection_predicates] If no WHERE clause is dened all rows are removed from the table. Example Remove the tasks assigned to the rst employee. DELETE FROM Task WHERE emp_id = 1

The basic SELECT statement I The SELECT statement retrieves columns and rows of data from one or many tables (views). The basic syntax of this statement involves only two parts: select list (it species the columns of the nal result set and implements the projection), from clause (it determines the target table or tables). SELECT DISTINCT select_list FROM list_of_tables The optional DISTINCT keyword eliminates duplicates from the result set.

The basic SELECT statement II Example Retrieve data from all rows and all columns of the Employee table. The sign * denotes all columns. SELECT * FROM Employee Example Display the names of all employees and their birthday's. SELECT emp_id,first_name, last_name, birth_date FROM Employee

The basic SELECT statement III Example Retrieve all dierent rst names. SELECT DISTINCT first_name FROM Employee

Assigning aliases (auxiliary names) to columns and tables I Aliases are applied to improve the readability of select statements. They can be assigned both to table and column names. There are two ways of dening aliases: with or without the AS keyword: column_name AS column_alias column_name column_alias table_name AS table_alias table_name table_alias

Assigning aliases (auxiliary names) to columns and tables II Example SELECT emp_id AS "Employee identification number" FROM Employee If an alias involves only one name then putting it in quotation mark is optional. Example Assigning aliases to a table (it is very useful for dening queries involving more than one table): SELECT d.dept_id AS "Department identification number", name AS "Department name" FROM Department AS d

Restricting query result I The above mentioned queries return all rows from a given table. To limit the number of rows in the query result set the WHERE clause (selection operator) is required. It involves selection predicates (Boolean combination consisting of conditions connected by logical connectives or, and or not). The most common form of a selection predicate is: expr op value, where expr is a column name, op is a binary operator, value denotes a value compatible with the value stored in expr. The general form of the select statement with the where clause is as follows:

Restricting query result II SELECT select_list FROM list_of_tables WHERE selection_predicates Example (SQLQuery51.sql) Get employees whose rst name equals John. Example (SQLQuery52.sql) Get all females born after January rst 1980.

Null value I Remind that we use NULL value to specify that the value is undened or unknown. We consider the Employment table. To explore the meaning of the NULL value let us consider Employment table. First let us modify the table to insert some NULL value into the salary column. Since the salary column has a constrain which does not allow to insert null value we have to delete this restriction. We can do it using Ms SQL Management Studio.

Null value II Next, we insert null values. We can do it using MS SQL Management Studio or update or insert command: update Employment set salary=null where e_id=5 or e_id=11 insert into Employment values(5,2,3,null,'2010-12-05',null)

Null value III Next consider the the following queries select * from Employment where Employment.salary>8000 We observe, that null values are not included. However, the same is true for the following query: select * from Employment where Employment.salary>8000 or Employment.salary<=8000

Aggregate functions I SQL Server provides a number of predened aggregate functions that allow to make a summary of the data. The functions act on a set of values and return a single value. They appear on the select list or in the HAVING clause. The main aggregate functions are (DISTINCT forces a function to consider only various values of the given set. ALL is the default and does not eliminate duplicates): COUNT(*) - it returns the number of values in the set including null values and duplicates. COUNT(DISTINCT ALL expr) it returns the number of dierent or all values in expr. AVG(DISTINCT ALL expr) it computes the average of various or all values of expr. SUM(DISTINCT ALL expr) it computes the sum of various or all values of expr.

Aggregate functions II MIN(DISTINCT ALL expr) it returns the minimum value among dierent or all values of expr. MAX(DISTINCT ALL expr) it returns the maximum value among dierent or all values of expr. Example (SQLQuery53.sql) How many dierent rst names do exist? Example (SQLQuery54.sql) Calculate the number of current (with end_date null) employees in the second department. Example (SQLQuery55.sql) Calculate the average salary of all current employees.

Aggregate functions III Example (SQLQuery56.sql) Determine the lowest and the highest date of birth for women.

GROUP BY and HAVING clause I The GROUP BY clause in a SELECT statement allows to divide the rows of a queried table into groups. The WHERE operator restricts the returned rows. SELECT select_list FROM list_of_tables WHERE search_conditions_for_rows GROUP BY grouping_expressions

GROUP BY and HAVING clause II Remark Note that GROUP BY cannot be applied in retrieving all rows of a table grouped by grouping expression. For instance it cannot be use (at leat directly) for selecting identication number of employees (Employment.emp_id) grouped departments (Employment.dept_id). The following query does not work. select * from Employment group by dept_id The only thing we can get using query in such a structure is the list of all departments by using select dept_id instead of *.

GROUP BY and HAVING clause III Aggregate functions usually go hand in hand with the GROUP BY clause. In such a case, an aggregate function is applied to each group of rows and returns a single value for each group. Without the GROUP BY clause, the aggregate function is used to all the rows in the queried table. SELECT select_list FROM list_of_tables WHERE search_conditions_for_rows Example (SQLQuery57.sql) Select department identication number and sum of current salaries in it.

GROUP BY and HAVING clause IV The HAVING operator makes a selection on groups of returned rows. It chooses only the groups for which the specied conditions are true. If there is no HAVING clause in a query, the nal query result involves summary rows for each group. Example (SQLQuery58.sql) Select department identication number if the average of current salaries in this department is greater then 7000.

GROUP BY and HAVING clause V SQL Server provides also the ORDER BY clause to sort the rows returned by a query ORDER BY expression(s) [ASC DESC] - it sorts the selected rows by expression(s) which usually species a column name. The ASC keyword arranges the rows in ascending order. DESC arranges the rows in descending order. ASC is the default. The following SELECT statement involves WHERE,GROUP BY, HAVING, and ORDER BY clause: SELECT select_list FROM list_of_tables WHERE search_conditions_for_rows GROUP BY grouping_expressions HAVING search_conditions_for_groups ORDER BY order_expression [ ASC DESC ]

GROUP BY and HAVING clause VI Example (SQLQuery59.sql) Determine employee identication number if he/she has more than one row in the Employment table. Arrange the result based on identication numbers in descending order.

Joins I Joins enable to retrieve data from two or more tables. Consider the following relation schemas (columns) Student={sID,sName,fName} Faculty={fName,fAddress} and the following instances (tables)

Joins II sid sname GPA fname 123 Mark 4,2 Math 672 Ana 4,5 Physics 132 John 4,0 Management 521 Eva 3,0 History fname Biology History Management Math Physics faddress Darwina Dlugosza Matejki Banacha Newtona

Joins III In the second lecture we dened a join of two instances (tables) I(S) and J(R) of the schema S and R (i.e. I(S) and J(R) are tables with columns S and R responsibly) as the instance K(S R) i.e the table with columns R and S) which consists of all rows (tuples) which restrictions to columns S is a row from I(S) and restriction to columns R is a row from J(R).

Joins IV So, we get, an example of join of Student and Faculty, the table sid sname GPA fname faddress 123 Mark 4,2 Math Banacha 672 Ana 4,5 Physics Newtona 132 John 4,0 Management Matejki 521 Eva 3,0 History Dlugosza The result of a cross join can be obtained by a select clause (how?).

Joins V Most queries with joins involve so called join condition which has the form: column1 op column2, where column1, column2 are some column names from the queried tables, op is a binary comparison operator applied to compare the values stored in column1 and column2. The join result involves only these pair of rows for which the column1 op column2 expression evaluates to true. A typical join condition is based on comparing values stored in a primary key column with the values of the foreign key column which refers to this primary key.

Joins VI SQL Server provides the following types of joins: Example inner join (join) it contains only the rows which satisfy a join condition. A general syntax of inner join is the following: select select_list from table1 [inner] join table2 on condition select * from Student join Faculty on Student.fName=Faculty.fname Example (Example510.sql) Select the names of all employees living in Warsaw.

Joins VII left outer join (left join) it involves both the rows satisfying a join condition and the rows from the left table which have no matching rows in the right table. Example (Example511.sql) Select the names of all employees living in Warsaw including those not yet assigned to any address. right outer join (right join) it involves both the rows satisfying a join condition and the rows from the right table which have no matching rows in the left table.

Joins VIII Example select * from Student right outer join Faculty on Student.fName=Faculty.fname full outer join (full join)it involves left and right outer joins. cross join it produces the Cartesian products of queried tables. self join it combines the records from a table with the rows from the same table. Example (SQLQuery512.sql) Select the names of all employees and their manager.

Subsqueries I A subquery is a select statement which is nested in another statement. select list_of_columns from list_of_tables where condition which involves another query If an inner (child) query makes no reference to the outer (parent) query then it is called the uncorrelated subquery. In the case of queries having correlated subqueries an inner query refers to the outer query.

Subsqueries II In consequence, the inner query is evaluated once for each row returned by the outer query. Example (SQLQuery513.sql) Select employees older than Adam Parker Example (SQLQuery514.sql) Get the employees older than their manager Example (SQLQuery515.sql) Select the name of employees whose salaries are greater than 1000

Thank you for your attention!