Nikolay Kostov Telerik Corporation www.telerik.com.

Slides:



Advertisements
Similar presentations
Group functions cannot be used in the WHERE clause: SELECT type_code FROM d_songs WHERE SUM (duration) = 100; (this will give an error)
Advertisements

Database Programming Sections 5 & 6 – Group functions, COUNT, DISTINCT, NVL, GROUP BY, HAVING clauses, Subqueries.
4 Copyright © 2004, Oracle. All rights reserved. Reporting Aggregated Data Using the Group Functions.
5 Copyright © Oracle Corporation, All rights reserved. Aggregating Data Using Group Functions.
5 Copyright © 2007, Oracle. All rights reserved. Reporting Aggregated Data Using the Group Functions.
5 Copyright © Oracle Corporation, All rights reserved. Aggregating Data Using Group Functions.
DATABASE PROGRAMMING Sections 5-7. Write a query that shows the average, maximum, and minimum salaries for all employees with jobs in the programming.
4 การใช้ SQL Functions. Copyright © 2007, Oracle. All rights reserved What Are Group Functions? Group functions operate on sets of rows to give.
Introduction to Structured Query Language (SQL)
Structured Query Language Part I Chapter Three CIS 218.
Introduction to Structured Query Language (SQL)
ASP.NET Programming with C# and SQL Server First Edition
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
15 Structured Query Language (SQL). 2 Objectives After completing this section, you should be able to: Understand Structured Query Language (SQL) and.
 SQL stands for Structured Query Language.  SQL lets you access and manipulate databases.  SQL is an ANSI (American National Standards Institute) standard.
Copyright © 2004, Oracle. All rights reserved. Lecture 6 Displaying Data from Multiple Tables ORACLE.
(with Microsoft SQL Server) Svetlin Nakov Telerik Corporation
What is a Database, MySQL Specifics Trần Anh Tuấn Edit from Telerik Software Academy
Database Programming Sections 6 –Subqueries, Single Row Subqueries, Multiple-column subqueries, Multiple-row Subqueries, Correlated Subqueries 11/2/10,
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
4 Copyright © 2004, Oracle. All rights reserved. Reporting Aggregated Data Using the Group Functions.
SQL (DDL & DML Commands)
Structure Query Language SQL. Database Terminology Employee ID 3 3 Last name Small First name Tony 5 5 Smith James
5 Copyright © Oracle Corporation, All rights reserved. Aggregating Data Using Group Functions.
Nitin Singh/AAO RTI ALLAHABAD 1 SQL Nitin Singh/AAO RTI ALLAHABAD 2 OBJECTIVES §What is SQL? §Types of SQL commands and their function §Query §Index.
Join, Subqueries and set operators. Obtaining Data from Multiple Tables EMPLOYEES DEPARTMENTS … …
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Chapter 2 Views. Objectives ◦ Create simple and complex views ◦ Creating a view with a check constraint ◦ Retrieve data from views ◦ Data manipulation.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
Intermediate SQL: Aggregated Data, Joins and Set Operators.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
Copyright © 2004, Oracle. All rights reserved. Lecture 4: 1-Retrieving Data Using the SQL SELECT Statement 2-Restricting and Sorting Data Lecture 4: 1-Retrieving.
1 Querying a Single Table Structured Query Language (SQL) - Part II.
Queries SELECT [DISTINCT] FROM ( { }| ),... [WHERE ] [GROUP BY [HAVING ]] [ORDER BY [ ],...]
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
Using SQL Connecting, Retrieving Data, Executing SQL Commands, … Svetlin Nakov Technical Trainer Software University
1 SQL SQL (Structured Query Language) : is a database language that is used to create, modify and update database design and data. Good Example of DBMS’s.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
DML Part 1 Yogiek Indra Kurniawan. All Files Can Be Downloaded at : Menu : “Perkuliahan”
Aggregating Data Using Group Functions. What Are Group Functions? Group functions operate on sets of rows to give one result per group.
Database Programming Sections 6 –Subqueries, Single Row Subqueries, Multiple-row Subqueries, Correlated Subqueries.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
Unit-8 Introduction Of MySql. Types of table in PHP MySQL supports various of table types or storage engines to allow you to optimize your database. The.
Simple Queries DBS301 – Week 1. Objectives Basic SELECT statement Computed columns Aliases Concatenation operator Use of DISTINCT to eliminate duplicates.
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.
1 Introduction to Database Systems, CS420 SQL JOIN, Group-by and Sub-query Clauses.
5-1 Copyright © 2004, Oracle. All rights reserved. DISPLAYING DATA FROM MULTIPLE TABLES OUTER JOIN.
Oracle 10g Retrieving Data Using the SQL SELECT Statement.
SQL SQL Ayshah I. Almugahwi Maryam J. Alkhalifa
Joins, Subqueries, CTE and Indices
Restricting and Sorting Data
CHAPTER 7 DATABASE ACCESS THROUGH WEB
Writing Basic SQL SELECT Statements
Basic select statement
ATS Application Programming: Java Programming
Manipulating Data.
Aggregating Data Using Group Functions
Chapter 2 Views.
Sections 4– Review of Joins, Group functions, COUNT, DISTINCT, NVL
Manipulating Data.
Chapter 2 Views.
Reporting Aggregated Data Using the Group Functions
Contents Preface I Introduction Lesson Objectives I-2
Reporting Aggregated Data Using the Group Functions
Reporting Aggregated Data Using the Group Functions
分组函数 Schedule: Timing Topic 35 minutes Lecture 40 minutes Practice
Restricting and Sorting Data
Aggregating Data Using Group Functions
Presentation transcript:

Nikolay Kostov Telerik Corporation

1. What is Database? 2. Keys and Table Relations 3. Data Manipulation Language  Select  Insert  Update  Delete 4. Aggregate Functions 5. MySQL Specifics

 Relational database is set of tables with defined relations between them  Each table has columns (fields) and rows  Some fields are called primary and foreign keys and define relation 100StevenKing NeenahKochhar LexDe Haan(null)90 103HunoldAlexander ErnstBruce FieldField RowRow

 Relational databases are manipulated using Structure Query Language (SQL)  Language for describing operations on structure and content of the database  Easy and straightforward to learn  Most databases follow the SQL standard 99 with little exceptions and additions  Uses English phrases and words: SELECT department_name FROM departments

DB The query is sent to the server Enter SQL query SELECT department_name FROM departments DEPARTMENT_NAME Administration Marketing Shipping The DB returns result (usually a table)

 SQL (Structured Query Language)  Language for describing and modifying database structure and data  Consists of DDL and DML  Data Definition Language (DDL) – defines the database structure – tables, fields and relations  Data Manipulation Language (DML) – modifies the data, stored in the tables – insert, delete, update or fetch rows

 Tables relations are defined by primary and foreign keys  Special properties of tables  Pair is formed by primary key in one table and linked foreign key in another  The values in a primary key field must be unique across the rows in the table  In a table there can be only one primary key but multiple foreign keys, pointing to other tables

 Example of two tables with primary and foreign key  In table Employees we put the department id instead of all the information for the department  Data is not duplicated, less storage space required LAST_NAMEDEPARTMENT_ID King1 Kochhar1 Fay2 Toto3 Jack2 IDNAME 1Executive 2Marketing 3Administration DEPARTMENTS EMPLOYEES Primary key Foreign key to field ID in table Departments

 There are three types of relations between two tables  One-to-one – one row in the first table corresponds to single row in the other  One-to-many – one row in the first table corresponds to many rows in the other  Many-to-many – many rows in one table correspond to many rows in the other  Third table is needed to be achieved  Sum of two one-to-many relations

 There are additional properties of the fields that change their behavior  Unique – requires the values in that field to be unique  Inserting or modifying value that already exists raises error  Index – modifies the internal work of the storage engine – speeds up searching for value in that field  Requires storage space

 Autoincrement – usually used for primary key fields; if the inserted value is NULL a new value is generated and used instead  Not null fields – require the inserted value to be distinct from NULL  Raises error otherwise  All primary keys are not null  MySQL supports also full text index – index for string fields

Table 1 Table 2 Table 1 Filtering Choosing set of rows Projection Choosing set of columns Joining Combining data from two or more tables

 Example select query:  EMPLOYEE_ID, FIRST_NAME, SALARY – fields we are selecting  as sets name of the field in the result table  From defines the tables we are gathering the data from  Where filters the rows SELECT EMPLOYEE_ID, FIRST_NAME as NAME, SALARY FROM EMPLOYEES WHERE EMPLOYEE_ID > 180 SELECT EMPLOYEE_ID, FIRST_NAME as NAME, SALARY FROM EMPLOYEES WHERE EMPLOYEE_ID > 180

 Instead of list of fields to select * can be used to specify all fields  Example: table employees : Is similar to query: SELECT * FROM EMPLOYEES EMPL_IDFIRST_NAMELAST_NAMESALARY 10LarryKing900 20JohnKochhar800 30PapaDe Haan850 50MimiTochkova1200 SELECT EMPLOYEE_ID, FIRST_NAME, LAST_NAME, salary FROM EMPLOYEES

Live Demo

 To select from the employees table all employees with salary less than 1000: Produces result: SELECT FIRST_NAME, LAST_NAME, SALARY FROM EMPLOYEES WHERE SALARY < 1000 SELECT FIRST_NAME, LAST_NAME, SALARY FROM EMPLOYEES WHERE SALARY < 1000 LAST_NAMEFIRST_NAMESALARY KingLarry900 KochharJohn800 De HaanPapa850

Live Demo

 The special value null means there is no value  Similar to PHP null  Different from zero or empty string  All operations with null produce null  Including comparison!

 Strings are enclosed in quotes  Some RDBMS support strings, enclosed in double- quotes  Example: selecting string Produces result: Produces result: SELECT LAST_NAME, 'foo' AS FOO FROM EMPLOYEES LAST_NAMEFOO Kingfoo Kochharfoo De Haanfoo Mimifoo

 The keyword distinct sets the database engine to return only distinct rows as result SELECT MANAGER_ID, SALARY FROM EMPLOYEES SELECT MANAGER_ID, SALARY FROM EMPLOYEES MANAGER_IDSALARY SELECT DISTINCT MANAGER_ID,SALARY FROM EMPLOYEES SELECT DISTINCT MANAGER_ID,SALARY FROM EMPLOYEES MANAGER_IDSALARY

Live Demo

 Arithmetic operations: - + * / ( )  Example using in select query: SELECT LAST_NAME, SALARY, SALARY + 300, 2*(SALARY + 300) AS BIG_SALARY FROM EMPLOYEES WHERE SALARY < 1000 SELECT LAST_NAME, SALARY, SALARY + 300, 2*(SALARY + 300) AS BIG_SALARY FROM EMPLOYEES WHERE SALARY < 1000 LAST_NAMESALARYSALARY + 300BIG_SALARY King Kochhar De Haan

 Concatenation (joining) of strings is done by CONCAT() SELECT concat(FIRST_NAME,' ',LAST_NAME) AS Employees, SALARY FROM EMPLOYEES SELECT concat(FIRST_NAME,' ',LAST_NAME) AS Employees, SALARY FROM EMPLOYEES EmployeesSALARY Larry King900 John Kochhar800 Papa De Haan850 Mimi Tochkova1200

 Used in the where clause  Comparisons -, =, <>  BETWEEN value AND value – similar to combination of comparisons  IN (value, …) – specifying if value is in a list  LIKE, RLIKE – simple and extended string comparison with regular expressions  IS NULL, IS NOT NULL – check if value is (not) null

 Used in where clauses  Logical operations – or, and, xor, not  Used to build complex filters for select query SELECTMANAGER_ID,DEPARTMENT_NAME FROM DEPARTMENTS WHERE MANAGER_ID < 200 AND NOT (DEPARTMENT_NAME = 'SALES') SELECTMANAGER_ID,DEPARTMENT_NAME FROM DEPARTMENTS WHERE MANAGER_ID < 200 AND NOT (DEPARTMENT_NAME = 'SALES')

Live Demo

 Result of select query can be sorted via the ORDER BY clause  Syntax is: order by {column [asc|desc],…}  The asc and desc modifiers sort in ascending and descending order, respectively  By default sorting is ascending SELECT LAST_NAME, HIRE_DATE FROM EMPLOYEES ORDER BY HIRE_DATE, SALARY ASC SELECT LAST_NAME, HIRE_DATE FROM EMPLOYEES ORDER BY HIRE_DATE, SALARY ASC

 The insert query has multiple forms:  Insert into values ( ) INSERT INTO COUNTRIES VALUES ('BG', 'Bulgaria', '1') INSERT INTO COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) VALUES ('BG', 'Bulgaria', '1') INSERT INTO COUNTRIES VALUES ('BG', 'Bulgaria', '1') INSERT INTO COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) VALUES ('BG', 'Bulgaria', '1')

Live Demo

 The update query modifies single or multiple rows in a table  The syntax is update set =,… where  The syntax is update set =,… where UPDATE EMPLOYEES SET FIRST_NAME = 'Updated Name', DEPARTMENT_ID = 90 WHERE EMPLOYEE_ID = 100 UPDATE EMPLOYEES SET FIRST_NAME = 'Updated Name', DEPARTMENT_ID = 90 WHERE EMPLOYEE_ID = 100

Live Demo

 The delete query deletes single or multiple rows from a table  Syntax is delete from where  Syntax is delete from where  The truncate query empties table DELETE FROM EMPLOYEES WHERE EMPLOYEE_ID = 1 DELETE FROM EMPLOYEES WHERE FIRST_NAME LIKE 'S%' DELETE FROM EMPLOYEES WHERE EMPLOYEE_ID = 1 DELETE FROM EMPLOYEES WHERE FIRST_NAME LIKE 'S%' TRUNCATE TABLE EMPLOYEES

 Aggregate functions operate on multiple rows and return single row as result  Usually used on numeric fields EMPLOYEE_IDSALARY MAX(SALARY) 24000

 Count(*) – returns count of rows  Sum (field) – returns the sum of the values in the column  Avg (field) – returns the average of the values in the column  Max (field) - return the maximum value in the column  Can be used for string values  Min (field) – returns the minimum value in the column  Can be used for string values

 Selecting minimum, maximum, average and total salary for all representatives SELECT AVG(SALARY), MAX(SALARY), MIN(SALARY), SUM(SALARY) MIN(SALARY), SUM(SALARY) FROM EMPLOYEES WHERE JOB_ID LIKE '%ACC%' SELECT AVG(SALARY), MAX(SALARY), MIN(SALARY), SUM(SALARY) MIN(SALARY), SUM(SALARY) FROM EMPLOYEES WHERE JOB_ID LIKE '%ACC%' AVG(SALARY)MAX(SALARY)MIN(SALARY)SUM(SALARY)

 Selecting earliest and latest date of hiring of employee  Dates are stored as numbers so the numeric aggregate functions can be applied to them SELECT MIN(HIRE_DATE), MAX(HIRE_DATE) FROM EMPLOYEES SELECT MIN(HIRE_DATE), MAX(HIRE_DATE) FROM EMPLOYEES MIN(HIRE_DATE)MAX(HIRE_DATE) :00: :00:00

 Counting the employees in department with id 50  Count only counts the values, different from null SELECT COUNT(*) FROM EMPLOYEES WHERE DEPARTMENT_ID = 50 SELECT COUNT(*) FROM EMPLOYEES WHERE DEPARTMENT_ID = 50 COUNT(*) 45

 The aggregate functions ignore the null values SELECT AVG(COMMISSION_PCT) FROM EMPLOYEES AVG(COMMISSION) EMPLOYEE_IDCOMMISION (null)

 Select queries can be used in other queries  Join result of select query instead of table  Result of select query, as value or list of values in comparison 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') SELECT D.DEPARTMENT_NAME, E.FIRST_NAME, E.SALARY FROM DEPARTMENTS D LEFT JOIN (SELECT EMPLOYEE_ID, FIRST_NAME, DEPARTMENT_ID, SALARY FROM EMPLOYEES WHERE SALARY > 10000) E ON E.DEPARTMENT_ID = D.DEPARTMENT_ID 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') SELECT D.DEPARTMENT_NAME, E.FIRST_NAME, E.SALARY FROM DEPARTMENTS D LEFT JOIN (SELECT EMPLOYEE_ID, FIRST_NAME, DEPARTMENT_ID, SALARY FROM EMPLOYEES WHERE SALARY > 10000) E ON E.DEPARTMENT_ID = D.DEPARTMENT_ID

Live Demo

 Exists operator returns true if the select query returns results  Example: selecting all employees that worked in department ID 110 SELECT FIRST_NAME, LAST_NAME FROM EMPLOYEES E WHERE EXISTS (SELECT EMPLOYEE_ID FROM JOB_HISTORY JH (SELECT EMPLOYEE_ID FROM JOB_HISTORY JH WHERE DEPARTMENT_ID = 110 AND WHERE DEPARTMENT_ID = 110 AND JH.EMPLOYEE_ID=E.EMPLOYEE_ID) JH.EMPLOYEE_ID=E.EMPLOYEE_ID) SELECT FIRST_NAME, LAST_NAME FROM EMPLOYEES E WHERE EXISTS (SELECT EMPLOYEE_ID FROM JOB_HISTORY JH (SELECT EMPLOYEE_ID FROM JOB_HISTORY JH WHERE DEPARTMENT_ID = 110 AND WHERE DEPARTMENT_ID = 110 AND JH.EMPLOYEE_ID=E.EMPLOYEE_ID) JH.EMPLOYEE_ID=E.EMPLOYEE_ID)

Live Demo

 MySQL is the most common database for use with PHP  Very light and fast  Authentication is very fast  Doesn't slow page loading times  High scalability  Can work with millions of rows  Open source, free  Designed for Linux

Live Demo

Questions?

1. Write a SQL query to find all information about all departments 2. Write a SQL query to find all department names 3. Write a SQL query to find the salary of each employee 4. Write a SQL query to find the full name of each employee 6. Write a SQL query to find all different employee salaries. 7. Write a SQL query to find all information about the employees whose job title is “Sales Representative“

9. Write a SQL query to find the names of all employees whose first name starts with the prefix "Sa“ 8. Write a SQL query to find the names of all employees whose last name contains the sequence "ei“ 9. Write a SQL query to find the salary of all employees whose salary is in the range [20000…30000] 10. Write a SQL query to find the names of all employees whose salary is 25000, 14000, or 23600

11. Write a SQL query to find all employees that have salary more than Order them in decreasing order by salary 12. Write a SQL query to find all employees that do not have manager 13. Write a SQL query to find the top 5 best paid employees 14. Write a SQL query to find all employees along with their address. Use inner join with ON clause 15. Write a SQL query to find the average salary in the department #1