+ All Categories
Home > Education > 9. SQL and MySQL - PHP & MySQL Web Development

9. SQL and MySQL - PHP & MySQL Web Development

Date post: 18-May-2015
Category:
Upload: telerik-software-academy
View: 6,979 times
Download: 5 times
Share this document with a friend
Description:
Basic concepts about SQL and MySQLTelerik Software Academy: http://academy.telerik.com/school-academy/meetings/details/2011/10/11/php-school-academy-meetingThe website and all video materials are in Bulgarian.This lecture discusses the following topics:What is Database?Keys and Table RelationsData Manipulation Language:Select, Insert, Update, DeleteAggregate FunctionsMySQL Specifics
Popular Tags:
53
SQL and MySQL What is a Database, MySQL Specifics Nikolay Kostov Telerik Software Academy academy.telerik.com Technical Trainer http://nikolay.it demy.telerik.com/.../ php -school- academy-meeting
Transcript
Page 2: 9. SQL and MySQL - PHP & MySQL Web Development

Contents1. What is Database?2. Keys and Table Relations3. Data Manipulation Language

Select Insert Update Delete

4. Aggregate Functions5. MySQL Specifics

Page 3: 9. SQL and MySQL - PHP & MySQL Web Development

What is Database?

Page 4: 9. SQL and MySQL - PHP & MySQL Web Development

What is database? 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 relationEMPLOYEE_ID FIRST_NAME LAST_NAME SALARY DEPART

MENT_ID

100 Steven King 24000 80

101 Neenah Kochhar 17000 50

102 Lex De Haan (null) 90

103 Hunold Alexander 9000 60

104 Ernst Bruce 6000 90

Field

Row

Page 5: 9. SQL and MySQL - PHP & MySQL Web Development

What is SQL? 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

Page 6: 9. SQL and MySQL - PHP & MySQL Web Development

Communication

DB

The query is sentto the server

Enter SQL query

SELECT department_name FROM departments

DEPARTMENT_NAME

Administration

Marketing

Shipping

The DB returns result(usually a table)

Page 7: 9. SQL and MySQL - PHP & MySQL Web Development

SQL 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

Page 8: 9. SQL and MySQL - PHP & MySQL Web Development

Keys and Table Relations

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

Page 9: 9. SQL and MySQL - PHP & MySQL Web Development

Keys and Table Relations

Page 10: 9. SQL and MySQL - PHP & MySQL Web Development

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_NAME DEPARTMENT_ID

King 1

Kochhar 1

Fay 2

Toto 3

Jack 2

Keys and Table Relations (2)

ID NAME

1 Executive

2 Marketing

3 Administration

DEPARTMENTS

EMPLOYEES

Primary keyForeign key to field ID in table Departments

Page 11: 9. SQL and MySQL - PHP & MySQL Web Development

Types of Relations 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

Page 12: 9. SQL and MySQL - PHP & MySQL Web Development

Fields Properties 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

Page 13: 9. SQL and MySQL - PHP & MySQL Web Development

Fields Properties (2) 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

Page 14: 9. SQL and MySQL - PHP & MySQL Web Development

Data Manipulation

Language

Page 15: 9. SQL and MySQL - PHP & MySQL Web Development

Select Query

Table 1 Table 2

Table 1 Table 1

FilteringChoosing set of rows

ProjectionChoosing set of columns

JoiningCombiningdata from twoor more tables

Page 16: 9. SQL and MySQL - PHP & MySQL Web Development

Select Query (2) 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,

SALARYFROM EMPLOYEESWHERE EMPLOYEE_ID > 180

Page 17: 9. SQL and MySQL - PHP & MySQL Web Development

Selecting all Fields 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_ID FIRST_NAME LAST_NAME SALARY

10 Larry King 900

20 John Kochhar 800

30 Papa De Haan 850

50 Mimi Tochkova 1200

SELECT EMPLOYEE_ID, FIRST_NAME, LAST_NAME, salary FROM EMPLOYEES

Page 18: 9. SQL and MySQL - PHP & MySQL Web Development

Selecting FieldsLive Demo

Page 19: 9. SQL and MySQL - PHP & MySQL Web Development

Filtering Rows To select from the employees table all employees with salary less than 1000:

Produces result:

SELECT FIRST_NAME, LAST_NAME, SALARY FROM EMPLOYEESWHERE SALARY < 1000

LAST_NAME FIRST_NAME SALARY

King Larry 900

Kochhar John 800

De Haan Papa 850

Page 20: 9. SQL and MySQL - PHP & MySQL Web Development

Filtering RowsLive Demo

Page 21: 9. SQL and MySQL - PHP & MySQL Web Development

The null Value 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!

Page 22: 9. SQL and MySQL - PHP & MySQL Web Development

Strings Strings are enclosed in quotes

Some RDBMS support strings, enclosed in double-quotes

Example: selecting string

Produces result:

SELECT LAST_NAME, 'foo' AS FOO FROM EMPLOYEES

LAST_NAME FOO

King foo

Kochhar foo

De Haan foo

Mimi foo

Page 23: 9. SQL and MySQL - PHP & MySQL Web Development

Selecting Only Distinct Rows

The keyword distinct sets the database engine to return only distinct rows as result

SELECT MANAGER_ID,SALARYFROM EMPLOYEES

MANAGER_ID SALARY

102 9000.00

103 4800.00

103 4800.00

103 4200.00

SELECT DISTINCTMANAGER_ID,SALARYFROM EMPLOYEES

MANAGER_ID SALARY

102 9000.00

103 4800.00

103 4200.00

Page 24: 9. SQL and MySQL - PHP & MySQL Web Development

Selecting Distinct Rows

Live Demo

Page 25: 9. SQL and MySQL - PHP & MySQL Web Development

Arithmetic Operations Arithmetic operations: - + * / ( ) Example using in select query:

SELECT LAST_NAME, SALARY, SALARY + 300,2*(SALARY + 300) AS BIG_SALARYFROM EMPLOYEES WHERE SALARY < 1000

LAST_NAME SALARY SALARY + 300 BIG_SALARY

King 900 1200 2400

Kochhar 800 1100 2200

De Haan 850 1150 2300

Page 26: 9. SQL and MySQL - PHP & MySQL Web Development

String Operations Concatenation (joining) of strings is done by CONCAT()

SELECT concat(FIRST_NAME,' ',LAST_NAME) AS Employees, SALARYFROM EMPLOYEES

Employees SALARY

Larry King 900

John Kochhar 800

Papa De Haan 850

Mimi Tochkova 1200

Page 27: 9. SQL and MySQL - PHP & MySQL Web Development

Comparison Operations 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

Page 28: 9. SQL and MySQL - PHP & MySQL Web Development

Boolean Operations Used in where clauses

Logical operations – or, and, xor, not

Used to build complex filters for select querySELECT

MANAGER_ID,DEPARTMENT_NAME

FROM DEPARTMENTSWHERE

MANAGER_ID < 200 ANDNOT (DEPARTMENT_NAME = 'SALES')

Page 29: 9. SQL and MySQL - PHP & MySQL Web Development

Boolean Operations

Live Demo

Page 30: 9. SQL and MySQL - PHP & MySQL Web Development

Sorting the Data 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

Page 31: 9. SQL and MySQL - PHP & MySQL Web Development

Inserting Data Into Table

The insert query has multiple forms:

Insert into <table> values (<values>)

INSERT INTO COUNTRIESVALUES ('BG', 'Bulgaria', '1')

INSERT INTO COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID)VALUES ('BG', 'Bulgaria', '1')

Page 32: 9. SQL and MySQL - PHP & MySQL Web Development

Inserting Data Into Table

Live Demo

Page 33: 9. SQL and MySQL - PHP & MySQL Web Development

Modifying Data

The update query modifies single or multiple rows in a table

The syntax isupdate <table> set <column>=<value>,… where <condition>

UPDATE EMPLOYEES SETFIRST_NAME = 'Updated Name',DEPARTMENT_ID = 90

WHERE EMPLOYEE_ID = 100

Page 34: 9. SQL and MySQL - PHP & MySQL Web Development

Modifying DataLive Demo

Page 35: 9. SQL and MySQL - PHP & MySQL Web Development

Deleting Data

The delete query deletes single or multiple rows from a table

Syntax is delete from <table> where <condition>

The truncate query empties tableDELETE FROM EMPLOYEES WHERE EMPLOYEE_ID = 1

DELETE FROM EMPLOYEES WHERE FIRST_NAME LIKE 'S%'

TRUNCATE TABLE EMPLOYEES

Page 36: 9. SQL and MySQL - PHP & MySQL Web Development

Aggregate Functions

Page 37: 9. SQL and MySQL - PHP & MySQL Web Development

Aggregate Functions Aggregate functions operate on multiple rows and return single row as result Usually used on numeric fields

EMPLOYEE_ID SALARY

100 24000

101 17000

102 17000

103 9000

104 6000

... ...

MAX(SALARY)

24000

Page 38: 9. SQL and MySQL - PHP & MySQL Web Development

Aggregate Functions (2)

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

Page 39: 9. SQL and MySQL - PHP & MySQL Web Development

Examples Selecting minimum, maximum, average and total salary for all representativesSELECT AVG(SALARY), MAX(SALARY), MIN(SALARY), SUM(SALARY)FROM EMPLOYEESWHERE JOB_ID LIKE '%ACC%'

AVG(SALARY) MAX(SALARY) MIN(SALARY) SUM(SALARY)

7983.333333 9000.00 6900.00 47900.00

Page 40: 9. SQL and MySQL - PHP & MySQL Web Development

Examples (2) 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

MIN(HIRE_DATE) MAX(HIRE_DATE)

1987-06-17 00:00:00 2000-04-21 00:00:00

Page 41: 9. SQL and MySQL - PHP & MySQL Web Development

Examples (3) Counting the employees in department with id 50

Count only counts the values, different from null

SELECT COUNT(*) FROM EMPLOYEESWHERE DEPARTMENT_ID = 50

COUNT(*)

45

Page 42: 9. SQL and MySQL - PHP & MySQL Web Development

Aggregating and null The aggregate functions ignore the null values

SELECT AVG(COMMISSION_PCT) FROM EMPLOYEES

AVG(COMMISSION)

0.222857

EMPLOYEE_ID COMMISION

100 20

101 10

102 (null)

Page 43: 9. SQL and MySQL - PHP & MySQL Web Development

Nested Queries 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 comparisonSELECT FIRST_NAME, LAST_NAME, SALARYFROM EMPLOYEESWHERE SALARY = (SELECT MAX(SALARY) FROM EMPLOYEES)

SELECT FIRST_NAME, LAST_NAME, SALARYFROM EMPLOYEESWHERE DEPARTMENT_ID IN (SELECT DEPARTMENT_ID FROM DEPARTMENTS WHERE DEPARTMENT_NAME='Accounting')

SELECT D.DEPARTMENT_NAME, E.FIRST_NAME, E.SALARYFROM DEPARTMENTS DLEFT JOIN (SELECT EMPLOYEE_ID, FIRST_NAME, DEPARTMENT_ID, SALARY FROM EMPLOYEES WHERE SALARY > 10000) EON E.DEPARTMENT_ID = D.DEPARTMENT_ID

Page 44: 9. SQL and MySQL - PHP & MySQL Web Development

Nested QueriesLive Demo

Page 45: 9. SQL and MySQL - PHP & MySQL Web Development

Operator Exists 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 EWHERE EXISTS (SELECT EMPLOYEE_ID FROM JOB_HISTORY JH WHERE DEPARTMENT_ID = 110 AND JH.EMPLOYEE_ID=E.EMPLOYEE_ID)

Page 46: 9. SQL and MySQL - PHP & MySQL Web Development

Operator ExistsLive Demo

Page 47: 9. SQL and MySQL - PHP & MySQL Web Development

MySQL 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

Page 48: 9. SQL and MySQL - PHP & MySQL Web Development

replace QueryLive Demo

Page 49: 9. SQL and MySQL - PHP & MySQL Web Development

форум програмиране, форум уеб дизайнкурсове и уроци по програмиране, уеб дизайн – безплатно

програмиране за деца – безплатни курсове и уроцибезплатен SEO курс - оптимизация за търсачки

уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop

уроци по програмиране и уеб дизайн за ученициASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC

безплатен курс "Разработка на софтуер в cloud среда"

BG Coder - онлайн състезателна система - online judge

курсове и уроци по програмиране, книги – безплатно от Наков

безплатен курс "Качествен програмен код"

алго академия – състезателно програмиране, състезания

ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NETкурсове и уроци по програмиране – Телерик академия

курс мобилни приложения с iPhone, Android, WP7, PhoneGap

free C# book, безплатна книга C#, книга Java, книга C#Дончо Минков - сайт за програмиранеНиколай Костов - блог за програмиранеC# курс, програмиране, безплатно

?

? ? ??

?? ?

?

?

?

??

?

?

? ?

Questions?

?

SQL and MySQL

http://academy.telerik.com

Page 50: 9. SQL and MySQL - PHP & MySQL Web Development

Exercises1. Write a SQL query to find all

information about all departments2. Write a SQL query to find all

department names3. Write a SQL query to find the

salary of each employee4. Write a SQL query to find the full

name of each employee6. 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“

Page 51: 9. SQL and MySQL - PHP & MySQL Web Development

Exercises (2)

9. Write a SQL query to find the names of all employees whose first name starts with the prefix "Sa“

10. Write a SQL query to find the names of all employees whose last name contains the sequence "ei“

11. Write a SQL query to find the salary of all employees whose salary is in the range [20000…30000]

12. Write a SQL query to find the names of all employees whose salary is 25000, 14000, 12500 or 23600

Page 52: 9. SQL and MySQL - PHP & MySQL Web Development

Exercises (3)

11. Write a SQL query to find all employees that have salary more than 50 000. 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


Recommended