Presentation is loading. Please wait.

Presentation is loading. Please wait.

What is a Database, MySQL Specifics Trần Anh Tuấn Edit from Telerik Software Academy

Similar presentations


Presentation on theme: "What is a Database, MySQL Specifics Trần Anh Tuấn Edit from Telerik Software Academy"— Presentation transcript:

1 What is a Database, MySQL Specifics Trần Anh Tuấn Edit from Telerik Software Academy tatuanb@gmail.com

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

3

4  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 100StevenKing2400080 101NeenahKochhar1700050 102LexDe Haan(null)90 103HunoldAlexander900060 104ErnstBruce600090 FieldField RowRow

5  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

6 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)

7  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

8  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

9

10  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

11  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

12  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

13  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

14

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

16  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

17  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

18  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

19  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!

20  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

21  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 1029000.00 1034800.00 1034800.00 1034200.00 SELECT DISTINCT MANAGER_ID,SALARY FROM EMPLOYEES SELECT DISTINCT MANAGER_ID,SALARY FROM EMPLOYEES MANAGER_IDSALARY 1029000.00 1034800.00 1034200.00

22  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 King90012002400 Kochhar80011002200 De Haan85011502300

23  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

24  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

25  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')

26  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

27  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')

28  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

29  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

30  Aggregate functions operate on multiple rows and return single row as result  Usually used on numeric fields EMPLOYEE_IDSALARY 10024000 10117000 10217000 1039000 1046000... MAX(SALARY) 24000

31  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

32  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) 7983.3333339000.006900.0047900.00

33  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) 1987-06-17 00:00:002000-04-21 00:00:00

34  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

35  The aggregate functions ignore the null values SELECT AVG(COMMISSION_PCT) FROM EMPLOYEES AVG(COMMISSION) 0.222857 EMPLOYEE_IDCOMMISION 10020 10110 102(null)

36  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

37  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)

38  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

39 форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен 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# Николай Костов - блог за програмиране


Download ppt "What is a Database, MySQL Specifics Trần Anh Tuấn Edit from Telerik Software Academy"

Similar presentations


Ads by Google