This document discusses why databases can be difficult. It begins by noting that databases are selfish, want entire systems to themselves, are messy and suck up resources. It then compares databases to toddlers. It identifies problems like most PHP developers lacking SQL training. It provides quizzes and discusses concepts like joins, indexes, foreign keys, transactions and query plans. It offers programming advice like checking return codes and scrubbing data. Finally, it recommends books and invites questions.
MySQL has a set of utilities written in Python that can do some amazing things for your MySQL instances from setting up replication with automatic fail over to copying database
MySQL is a SQL database that also does NoSQL. You can access data in the InnoDB or NDB storage engines as a key/value pair at amazing speeds while retaining simultaneous SQL access of the same data. Plus MySQL 5.7 features a new native JSON data type
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScriptDave Stokes
The MySQL Shell has a JavaScript mode where you can use JS libraries to access you data and you can also write (and save) your own custom reports (or programs) for future use.
MySQL has a set of utilities written in Python that can do some amazing things for your MySQL instances from setting up replication with automatic fail over to copying database
MySQL is a SQL database that also does NoSQL. You can access data in the InnoDB or NDB storage engines as a key/value pair at amazing speeds while retaining simultaneous SQL access of the same data. Plus MySQL 5.7 features a new native JSON data type
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScriptDave Stokes
The MySQL Shell has a JavaScript mode where you can use JS libraries to access you data and you can also write (and save) your own custom reports (or programs) for future use.
Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...Dave Stokes
Speeding up queries on a MySQL server with indexes and histograms is not a mysterious art but simple engineering. This presentation is an indepth introduction that was presented on March 30th to the Quest Insynch and Open Source 101 conferences
Confoo.ca conference talk February 24th 2021 on MySQL new features found in version 8.0 including server and supporting utility updates for those who may have missed some really neat new features
MySQL 5.7 NEW FEATURES, BETTER PERFORMANCE, AND THINGS THAT WILL BREAK -- Mid...Dave Stokes
MySQL is on the way and this presentation covers the new features, improved performance, and better admin that will come with 5.7. But there are some things that are changing that you need to know before you upgrade
MySql's NoSQL -- best of both worlds on the same disksDave Stokes
Get the best of both worlds -- SQL access and NoSQL access to the same data using the Memcached protocol. 9x faster than regular SQL, the Memcached protocol use allows applications to drink from the fire hose. Plus now your cache can be stored permanently. Easy and simple to implement.
Dutch PHP Conference 2021 - MySQL Indexes and HistogramsDave Stokes
Slides from the 2021 Dutch PHP Conference on MySQL Indexes, histograms, and other things to speed up your database queries. Speeding up your database queries is mainly learning how to efficiently give the query optimizer what is needs to provide the best query plan for your data.
MySQL® 5.7 is a great release which has a lot to offer, especially in the development and replication areas. It provides a lot of new optimizer features for developers to take advantage of, a much more powerful GIS function and high performance JSON data type, allowing for a more powerful store for semi-structured data. It also features dramatically improved Performance Schema, Parallel and Multi-Source replication, allowing you to scale much further than ever before, just to give you a taste. In this webinar, we will provide an overview of the most important MySQL 5.7 features.
This webinar will be part of a 3-part series which will include MySQL 5.7 for Developers and MySQL 5.7 for DBAs.
MySQL Indexes and Histograms - RMOUG Training Days 2022Dave Stokes
Nobody complains when the database is too fast. But they do gripe when it slows down. The two most popular ways to increase query speed are indexes and histograms. But there a dozens of options for indexes and a lot of lots of bad information on how to use them. Histograms are great but not for all types of data. This session covers the hows and whys of both approaches
MySQL High Availability Solutions - Avoid loss of service by reducing the r...Olivier DASINI
MySQL High Availability Solutions
Avoid loss of service by reducing the risk of failures
MySQL InnoDB Cluster
Collection of products that work together to provide a complete High Availability solution for MySQL
MySQL InnoDB ReplicaSet
Administer a set of MySQL instances running asynchronous replication
MySQL NDB Cluster
A high-availability, high-redundancy version of MySQL adapted for the distributed computing environment
Database Basics with PHP -- Connect JS Conference October 17th, 2015Dave Stokes
This presentation covers the basics of using a relational database for PHP developers. Included are using Venn Diagrams, examining queries, and letting the database do the heavy lifting.
MySQL Without the SQL -- Oh My! Longhorn PHP ConferenceDave Stokes
You can now use MySQL without needing to know Structured Query Language (SQL) with the MySQL Document Store. Access JSON documents and/or relational tables using the new X DevAPI
Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...Dave Stokes
Speeding up queries on a MySQL server with indexes and histograms is not a mysterious art but simple engineering. This presentation is an indepth introduction that was presented on March 30th to the Quest Insynch and Open Source 101 conferences
Confoo.ca conference talk February 24th 2021 on MySQL new features found in version 8.0 including server and supporting utility updates for those who may have missed some really neat new features
MySQL 5.7 NEW FEATURES, BETTER PERFORMANCE, AND THINGS THAT WILL BREAK -- Mid...Dave Stokes
MySQL is on the way and this presentation covers the new features, improved performance, and better admin that will come with 5.7. But there are some things that are changing that you need to know before you upgrade
MySql's NoSQL -- best of both worlds on the same disksDave Stokes
Get the best of both worlds -- SQL access and NoSQL access to the same data using the Memcached protocol. 9x faster than regular SQL, the Memcached protocol use allows applications to drink from the fire hose. Plus now your cache can be stored permanently. Easy and simple to implement.
Dutch PHP Conference 2021 - MySQL Indexes and HistogramsDave Stokes
Slides from the 2021 Dutch PHP Conference on MySQL Indexes, histograms, and other things to speed up your database queries. Speeding up your database queries is mainly learning how to efficiently give the query optimizer what is needs to provide the best query plan for your data.
MySQL® 5.7 is a great release which has a lot to offer, especially in the development and replication areas. It provides a lot of new optimizer features for developers to take advantage of, a much more powerful GIS function and high performance JSON data type, allowing for a more powerful store for semi-structured data. It also features dramatically improved Performance Schema, Parallel and Multi-Source replication, allowing you to scale much further than ever before, just to give you a taste. In this webinar, we will provide an overview of the most important MySQL 5.7 features.
This webinar will be part of a 3-part series which will include MySQL 5.7 for Developers and MySQL 5.7 for DBAs.
MySQL Indexes and Histograms - RMOUG Training Days 2022Dave Stokes
Nobody complains when the database is too fast. But they do gripe when it slows down. The two most popular ways to increase query speed are indexes and histograms. But there a dozens of options for indexes and a lot of lots of bad information on how to use them. Histograms are great but not for all types of data. This session covers the hows and whys of both approaches
MySQL High Availability Solutions - Avoid loss of service by reducing the r...Olivier DASINI
MySQL High Availability Solutions
Avoid loss of service by reducing the risk of failures
MySQL InnoDB Cluster
Collection of products that work together to provide a complete High Availability solution for MySQL
MySQL InnoDB ReplicaSet
Administer a set of MySQL instances running asynchronous replication
MySQL NDB Cluster
A high-availability, high-redundancy version of MySQL adapted for the distributed computing environment
Database Basics with PHP -- Connect JS Conference October 17th, 2015Dave Stokes
This presentation covers the basics of using a relational database for PHP developers. Included are using Venn Diagrams, examining queries, and letting the database do the heavy lifting.
MySQL Without the SQL -- Oh My! Longhorn PHP ConferenceDave Stokes
You can now use MySQL without needing to know Structured Query Language (SQL) with the MySQL Document Store. Access JSON documents and/or relational tables using the new X DevAPI
Databases are the heart of most PHP projects but roughly TWO PERCENT of PHP programmers have had any real training in Structured Query Language, SQL. Then they wonder why their queries perform poorly, why they get N+1 problems, and suddenly the database becomes the choke point of the project. This presentation will cover the basics of relational algebra (no algebra, math or calculus skills needed!!!!), how to think in sets with Venn Diagrams, and how to let the database do the heavy lifting for you. So if you want to write high performing database queries and be admired as a database deity by your co workers then you need to be in this session!
This presentation deals with the fundamentals of SQL, Installation and Database concepts. Presented by our team in Alphalogic Inc: https://www.alphalogicinc.com/
This presentation is an INTRODUCTION to intermediate MySQL query optimization for the Audience of PHP World 2017. It covers some of the more intricate features in a cursory overview.
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)Dave Stokes
MySQL 8 has many new features and this presentation covers the new data dictionary, improved JSON functions, roles, histograms, and much more. Updated after SunshinePHP 2018 after feedback
Five Database Mistakes and how to fix them -- Confoo VancouverDave Stokes
Very few developers are learning Structured Query Language (about 2%) but then wonder why their database queries stink. This presentation covers five common database problems and how to fix them
What Your Database Query is Really DoingDave Stokes
Do you ever wonder what your database servers is REALLY doing with that query you just wrote. This is a high level overview of the process of running a query
SQL For Programmers -- Boston Big Data Techcon April 27thDave Stokes
SQL For Programmers is an introduction to SQL concepts, when SQL is a better choice, and a look at the future of databases. Presented April 27th, 2015 at Big Data Techcon Boston
Fewer developers each year are getting training in Structured Query Language (SQL) but their code is more dependent on Relation Data. The MySQL Document Store allows programmers to use the full power of MySQL without needing SQL! Built on the X DevAPI, the MySQL Document Store is a power tool for working with JSON Document Store or relational tables. Best of both NoSQL and SQL worlds!
L1 Intro to Relational DBMS LP.pdfIntro to Relational .docxDIPESH30
L1 Intro to Relational DBMS LP.pdf
Intro to Relational
Databases
CS 2215 Introduction to Databases
1
2
What Is a DBMS?
Database: A collection of information.
Eg ?
Examples: Library, University
Database Management System (DBMS) :
software package designed to store
and manage databases.
Eg: Oracle, SQL server, MySQL, Access
Files vs DBMS : Why bother with
databases ?
Why not just store all the data in a big file
and write C or Java programs to manipulate
the data. 2
3
Why Use a DBMS?
Naïve users sheltered from messy
details
Data integrity:
Eg: if Bob works in Marketing, make
sure there is a dept. called Marketing.
Reduced application development
time: Avoid writing special programs
from scratch each time to access
data.
Standard Application Interface:
increased reliability
3
4
Why Use a DBMS?
Data independence: easier
to make changes
If how data is stored changes,
don’t have to change views.
Forms, etc.
Security: easier to control
how data is shared
Concurrent access: allow
multiple users to access
simultaneously
But in a controlled way !
4
5
Different people involved
DBMS implementers: who build the DBMS like
Oracle, MS SQL server
End users: Use forms & reports, might write SQL
queries
DB application programmers: write programs
to make life easier for end users.
Eg: person who creates forms for library.
Must know how databases work
DB administrator (DBA):
Handles security and authorization
Crash recovery
Database tuning as needs evolve
5
6
Overview of course: Relational Model:
Student Database, Fig 1.2
6
STUDENT
Name StudentNumber Class Major
Smith 17 1 CS
Brown 8 2 CS
7
Overview of course:
Data Models:
High level : Entity Relation (E.R.) model
Intermediate level : relational model
Student database
Low level: physical database -
Covered in CSCI 4524 Advanced
Databases
Relational databases:
Integrity constraints
Good design : normalization
Query languages: Relational
algebra, SQL
Views, Assertions, Triggers
7
8
Relational Data Model
Relation: 2-dimensional table
All info stored in tables
Eg: student, course
See Elmasri Fig 1.2
Rows (or tuples): student : 2 rows
Records: a row may correspond with a
record in a file
Commonly used if we are talking about the
physical storage of databases
Columns (or attributes): student : 4
columns
8
9
Relational Data Model
Relational model proposed by E. F.
Codd 1970
Dominant model in commercial DBMS
products.
Eg: Oracle, SQL server, MySQL, Access.
Compared to previous models
(network, hierarchical etc):
Easier to understand info in tables
Casual user can write simple SQL queries
Complex queries much easier to
understand compared to previous models.
9
10
Basic Terminology
Relational Schema (or head): set of all the
column names i.e. what info is bei ...
MySQL is an ubiquitous open source database but do you know how make it secure? This talk is from the 2022 Texas Cyber Summit on how to do just that. Make sure you data and database are secure.
Develop PHP Applications with MySQL X DevAPIDave Stokes
The X DevAPI provides a way to use MySQL as a NoSQL JSON Document Store and this presentation covers how to use it with the X DevAPI PHP PECL extension. And it also works with traditional relational tables. Presented at Oracle CodeOne 24 October 2018
The Proper Care and Feeding of MySQL DatabasesDave Stokes
Many Linux System Administrators are 'also' accidental database administrators. This is a guide for them to keep their MySQL database instances happy, health, and glowing
MySQL can now be used as a NoSQL JSON Document store so you get the best of NoSQL and SQL world. This talk covers the features of the X Devapi, the MySQL Document Store, and how to use relational tables with the new SQL features
MySQL Without The SQL -- Oh My! PHP[Tek] June 2018Dave Stokes
The MySQL Document Store allows developers to use MySQL as a JSON Document Store -- no normalizing of data, setting up relational tables, and you do not have to use SQL to query data. And you get the both the SQL and NoSQL worlds on one server
Presentation Skills for Open Source FolksDave Stokes
Do you want to present at a Linuxfest or other open source conference but do not know where or how to start. Follow these recommendations and you will be on your way to being a speaking all star. Discover how write your presentation. what tools you need, and other items of note
ConFoo MySQL Replication Evolution : From Simple to Group ReplicationDave Stokes
MySQL Replication has been around for many years but how wee do you under stand it? Do you know about read/write splitting, RBR vs SBR style replication, and InnoDB cluster?
SwanseaCon 2017 presentation on Making MySQL Agile-ish. Relational Databases are not usually considered part of the Agile Programming movement but there are many new features in MySQL to make it easier to include it. This presentation covers how MySQL is moving to help support agile development while maintaining the traditional 'non agile' stability expected from a database.
The very basics of programming in PHP to store/retrieve data on a relational database management system (RDMS). For those looking for intermediate to advanced material, please see 'What Your Database Query is Really Doing'.
MySQL Replication Evolution -- Confoo Montreal 2017Dave Stokes
MySQL Replication has evolved since the early days with simple async master/slave replication with better security, high availability, and now InnoDB Cluster
All Things Open 2016 -- Database Programming for NewbiesDave Stokes
This presentation covers much a new developer needs to know about working WITH a database instead of against it. Plus there is much on what goes on behind the scenes when you submit a query and hints on how to avoid the big problems that can ruin your data
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesSanjeev Rampal
Talk presented at Kubernetes Community Day, New York, May 2024.
Technical summary of Multi-Cluster Kubernetes Networking architectures with focus on 4 key topics.
1) Key patterns for Multi-cluster architectures
2) Architectural comparison of several OSS/ CNCF projects to address these patterns
3) Evolution trends for the APIs of these projects
4) Some design recommendations & guidelines for adopting/ deploying these solutions.
1.Wireless Communication System_Wireless communication is a broad term that i...JeyaPerumal1
Wireless communication involves the transmission of information over a distance without the help of wires, cables or any other forms of electrical conductors.
Wireless communication is a broad term that incorporates all procedures and forms of connecting and communicating between two or more devices using a wireless signal through wireless communication technologies and devices.
Features of Wireless Communication
The evolution of wireless technology has brought many advancements with its effective features.
The transmitted distance can be anywhere between a few meters (for example, a television's remote control) and thousands of kilometers (for example, radio communication).
Wireless communication can be used for cellular telephony, wireless access to the internet, wireless home networking, and so on.
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC
Ellisha Heppner, Grant Management Lead, presented an update on APNIC Foundation to the PNG DNS Forum held from 6 to 10 May, 2024 in Port Moresby, Papua New Guinea.
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBrad Spiegel Macon GA
Brad Spiegel Macon GA’s journey exemplifies the profound impact that one individual can have on their community. Through his unwavering dedication to digital inclusion, he’s not only bridging the gap in Macon but also setting an example for others to follow.
This 7-second Brain Wave Ritual Attracts Money To You.!nirahealhty
Discover the power of a simple 7-second brain wave ritual that can attract wealth and abundance into your life. By tapping into specific brain frequencies, this technique helps you manifest financial success effortlessly. Ready to transform your financial future? Try this powerful ritual and start attracting money today!
# Internet Security: Safeguarding Your Digital World
In the contemporary digital age, the internet is a cornerstone of our daily lives. It connects us to vast amounts of information, provides platforms for communication, enables commerce, and offers endless entertainment. However, with these conveniences come significant security challenges. Internet security is essential to protect our digital identities, sensitive data, and overall online experience. This comprehensive guide explores the multifaceted world of internet security, providing insights into its importance, common threats, and effective strategies to safeguard your digital world.
## Understanding Internet Security
Internet security encompasses the measures and protocols used to protect information, devices, and networks from unauthorized access, attacks, and damage. It involves a wide range of practices designed to safeguard data confidentiality, integrity, and availability. Effective internet security is crucial for individuals, businesses, and governments alike, as cyber threats continue to evolve in complexity and scale.
### Key Components of Internet Security
1. **Confidentiality**: Ensuring that information is accessible only to those authorized to access it.
2. **Integrity**: Protecting information from being altered or tampered with by unauthorized parties.
3. **Availability**: Ensuring that authorized users have reliable access to information and resources when needed.
## Common Internet Security Threats
Cyber threats are numerous and constantly evolving. Understanding these threats is the first step in protecting against them. Some of the most common internet security threats include:
### Malware
Malware, or malicious software, is designed to harm, exploit, or otherwise compromise a device, network, or service. Common types of malware include:
- **Viruses**: Programs that attach themselves to legitimate software and replicate, spreading to other programs and files.
- **Worms**: Standalone malware that replicates itself to spread to other computers.
- **Trojan Horses**: Malicious software disguised as legitimate software.
- **Ransomware**: Malware that encrypts a user's files and demands a ransom for the decryption key.
- **Spyware**: Software that secretly monitors and collects user information.
### Phishing
Phishing is a social engineering attack that aims to steal sensitive information such as usernames, passwords, and credit card details. Attackers often masquerade as trusted entities in email or other communication channels, tricking victims into providing their information.
### Man-in-the-Middle (MitM) Attacks
MitM attacks occur when an attacker intercepts and potentially alters communication between two parties without their knowledge. This can lead to the unauthorized acquisition of sensitive information.
### Denial-of-Service (DoS) and Distributed Denial-of-Service (DDoS) Attacks
1. Why Are Databases So &# %-ingWhy Are Databases So &# %-ing DifficultDifficult?!?!
Dave Stokes
MySQL Community Manager
David.Stokes@Oracle.com @Stoker
Slideshare.net/DavidMStokes
2. 2
Safe Harbor Agreement
The following is intended to outline our general product
direction. It is intended for information purposes only, and
may not be incorporated into any contract. It is not a
commitment to deliver any material, code, or functionality,
and should not be relied upon in making purchasing
decision. The development, release, and timing of any
features or functionality described for Oracle’s products
remains at the sole discretion of Oracle.
8. 8
So back to the subject at hand
Why AreWhy Are
DatabasesDatabases
So &# %-ingSo &# %-ing
DifficultDifficult?!?!
9. 9
Databases are:
● Selfish
● Want entire system to self
● Messy
● Suck up memory, disk space,
bandwidth, sanity
● Growing all the time
● Needs updates
● Suck up a good part of your life
12. 12
Quiz #1
Select City.Name, Country.Name
FROM City
Join Country On (City.CountryCode = Country.Code)
WHERE City.Population > 2000000
ORDER By Country.Name, City.Name
● Can you describe the desired output of this query?
● Is the above SQL code good?
● Will it perform well for 10 records? 100000 records? 10^10 records?
13. 13
Quiz #1 – First Answer
Select City.Name, Country.Name
FROM City
Join Country On (City.CountryCode = Country.Code)
WHERE City.Population > 2000000
ORDER By Country.Name, City.Name
Desired Output
● Return the name of the Cities and their
corresponding Countries with Populations over
two million and sort by Country and City names
14. 14
Quiz #1 -Second Answer
Select City.Name, Country.Name
FROM City
Join Country On (City.CountryCode = Country.Code)
WHERE City.Population > 2000000
ORDER By Country.Name, City.Name
Is the above SQL code good?
● Syntax is good.
● But can not tell just by observation of the query
– May not be answering desired question
– May not map to the underlying data effectively
– Unless joining on foreign keys, may be wrong relationship between tables
– What are the units for population? Is is safe to assume here?
15. 15
Quiz #1
Select City.Name, Country.Name
FROM City
Join Country On (City.CountryCode = Country.Code)
WHERE City.Population > 2000000
ORDER By Country.Name, City.Name
Will it perform well for 10 records?
100000 records? 10^10 records?
● No way to tell by observation!
16. 16
Can you tell if PHP code is bad by observation?
<?php
$foo = 8;
if( $foo<10 )
if( $foo>5 )
echo "Greater than 5!";
else
echo "Less than 5!";
else
echo "Greater than 10!";
echo "<br />Another note.";
● http://code.tutsplus.com/tutorials/why-youre-a-
bad-php-programmer--net-18384
It can be
relatively easy
to recognize
BAD PHP
programs.
17. 17
So why is SQL Different
SQL is a
Declarative
Language
18. 18
So why is SQL Different
● In computer science, declarative programming is a
programming paradigm, a style of building the
structure and elements of computer programs, that
expresses the logic of a computation without
describing its control flow. Many languages applying
this style attempt to minimize or eliminate side
effects by describing what the program should
accomplish in terms of the problem domain,
rather than describing how to go about
accomplishing it as a sequence of the
programming language primitives (the how being
left up to the language's implementation).
● https://en.wikipedia.org/wiki/Declarative_programming
20. 20
Mix and/or Match
Can you Mix and Match
Declarative with Object
Orientated/Procedural
Programing Languages??
21. 21
Yes but carefully
$QUERY = “Select City.Name, Country.Name
FROM City
Join Country On (City.CountryCode =
Country.Code)
WHERE City.Population > 2000000
ORDER By Country.Name, City.Name”;
$res = $mysqli->query($QUERY);
$row = $res->fetch_assoc();
22. 22
SQL
● SQL Structured Query Language is a special-purpose
programming language designed for managing data
held in a relational database management system
(RDBMS), or for stream processing in a relational
data stream management system (RDSMS).
● Originally based upon relational algebra and tuple
relational calculus, SQL consists of a data definition
language, data manipulation language, and a data
control language. The scope of SQL includes data
insert, query, update and delete, schema creation
and modification, and data access control.
● https://en.wikipedia.org/wiki/SQL
23. 23
What many of the audience members look like right now!
Oh No! He
said the words
relational
algebra and
tuple relational
calculus!
24. 24
Problem #2 – Joins
● A SQL join clause combines
records from two or more
tables in a relational
database. It creates a set that
can be saved as a table or
used as it is. A JOIN is a
means for combining fields
from two tables (or more) by
using values common to
each.
● https://en.wikipedia.org/wiki/Join_(SQ
L)
26. 26
●
A JOIN is a means for combining fields from two tables (or
more) by using values common to each.
Join Country On
(City.CountryCode
= Country.Code)
27. 27
Data Helpers
● Do not make every column as large as it possible can be. A BIGINT will take
8 bytes to store, 8 bytes to read off disk, 8 bytes to send over the network,
etc.
– Your are not going to have 18,446,744,073,709,551,615 customers even
if your customer_id is a BIGINT.
● If you can get by with a simple character set like LATIN1 great, otherwise
stick to UTF8mb4 but realize you are going from one to three bytes for
storage.
● SELECT the columns you are going to use, avoid the * wildcard
– The less you move disk/memory/net the better!
28. 28
Problem #2 – Let Database Do the Heavy Lifiting
● Need SUM, AVG, AMX, MIN, STD, STDDEV_POP, STDDEV_SAMP,
STDDEV, VARIANCE, VAR_SAMP, VAR_POP
● Sorting easier outside of your application!
● Joins!!!!!
● Do not INDEX everything
● Use Foreign Keys
31. 31
Indexes
● INDEX columns
– On the right side of WHERE
– Used in joins
● INDEXES have overhead – so do not index everything
– Maintenance
– Insert/update/delete
– Use mysqlindexcheck
● Finds Duplicate Indexes
– Use Sys Schema
● Find Unused Indexes
32. 32
Foreign Keys
● A foreign key is a field (or collection of fields) in one table that
uniquely identifies a row of another table. In simpler words, the
foreign key is defined in a second table, but it refers to the primary
key in the first table. For example, a table called Employee has a
primary key called employee_id. Another table called Employee
Details has a foreign key which references employee_id in
order to uniquely identify the relationship between both the
tables.
● The table containing the foreign key is called the child table, and the
table containing the candidate key is called the referenced or parent
table. In database relational modeling and implementation, a unique
key is a set of zero, one or more attributes, the value(s) of which are
guaranteed to be unique for each tuple (row) in a relation. The value
or combination of values of unique key attributes for any tuple
cannot be duplicated for any other tuple in that relation.
● https://en.wikipedia.org/wiki/Foreign_key
33. 33
Foreign Keys
CREATE TABLE
employee (
e_id INT NOT NULL,
name CHAR(20),
PRIMARY KEY (e_id)
):
CREATE TABLE building (
office_nbr INT NOT NULL,
description CHAR(20),
e_id INT NOT NULL,
PRIMARY KEY (office_nbr),
FOREIGN KEY (e_id),
REFERENCES employee
(e_id)
ON UPDATE CASCADE,
ON DELETE CASCADE);
34. 34
Now Add Data
INSERT INTO employee VALUES
(10.'Larry'), (20,'Shemp'),(30,'Moe');
INSERT INTO building VALUES
(100,'Corner Office',10),
(101,'Lobby',40);
SELECT FROM employee
JOIN BUILDING (employee.e_id = building.e_id);
e_id name office_nbr description e_id
10 Larry 100 Corner Office 10
40 Moe 101 Lobby 40
Where is SHEMP????
35. 35
How do we find Shemp?
mysql> SELECT * FROM employee
LEFT JOIN building ON(employee.e_id=building.e_id);
e_id name office_nbr description e_id
10 Larry 100 Corner Office 10
40 Moe 101 Lobby 40
20 Shemp NULL NULL NULL
36. 36
FK save you from messy data
mysql> INSERT INTO building VALUES (120,'Cubicle',77);
ERROR 1452 (23000): Cannot add or update a child row: a
foreign key constraint fails (`test`.`building`, CONSTRAINT
`building_ibfk_1` FOREIGN KEY (`e_id`) REFERENCES
`employee` (`e_id`) ON DELETE CASCADE ON UPDATE
CASCADE)
Who is employee 77?
37. 37
Using Cascade
mysql> DELETE FROM employee WHERE e_id=40;
mysql> SELECT * FROM employee LEFT JOIN building ON
(employee.e_id=building.e_id);
e_id name office_nbr description e_id
10 Larry 100 Corner Office 10
20 Shemp NULL NULL NULL
38. 38
Updates
mysql> UPDATE employee SET e_id=21 WHERE e_id=20;
mysql> SELECT * FROM employee LEFT JOIN building ON
(employee.e_id=building.e_id);
e_id name office_nbr description e_id
10 Larry 100 Corner Office 10
21 Shemp NULL NULL NULL
41. 41
● What is the N+1 Query Problem ?
● This problem occurs when the code needs to load the children
of a parent-child relationship (the “many” in the “one-to-many”).
Most ORMs have lazy-loading enabled by default, so queries
are issued for the parent record, and then one query
for EACH child record. As you can expect, doing N+1
queries instead of a single query will flood your database with
queries, which is something we can and should avoid.
● http://www.sitepoint.com/silver-bullet-n1-problem/
42. 42
N+1 Problem
function get_author_id( $name )
{
$res = $db->query( "SELECT id FROM
authors WHERE name=?",
array( $name ) );
$id = null;
while( $res->fetchInto( $row ) ) { $id =
$row[0]; }
return $id;
}
function get_books( $id )
{
$res = $db->query( "SELECT id FROM
books WHERE author_id=?",
array( $id ) );
$ids = array();
while( $res->fetchInto( $row ) ) { $ids []=
$row[0]; }
return $ids;
}
function get_book( $id )
{
$res = $db->query( "SELECT * FROM
books WHERE id=?", array( $id ) );
while( $res->fetchInto( $row ) ) { return
$row; }
return null;
}
$author_id = get_author_id( 'Jack
Herrington' );
$books = get_books( $author_id );
foreach( $books as $book_id ) {
$book = get_book( $book_id );
var_dump( $book );
}
http://www.ibm.com/developerworks/library/os-php-dbmistake/
Three queries!!!!
43. 43
N+1 Continued
function get_books( $name )
{
$res = $db->query(
"SELECT books.* FROM authors,books WHERE
books.author_id=authors.id AND
authors.name=?",
array( $name ) );
$rows = array();
while( $res->fetchInto( $row ) ) { $rows []= $row; }
return $rows;
}
$books = get_books( 'Jack Herrington' );
var_dump( $books );
One read to get the same data!!!! Yea!!!
44. 44
Transactions!!!
● A transaction symbolizes a unit of work performed within a database
management system (or similar system) against a database, and treated in a
coherent and reliable way independent of other transactions. A transaction generally
represents any change in database. Transactions in a database environment have
two main purposes:
– To provide reliable units of work that allow correct recovery from failures and keep a
database consistent even in cases of system failure, when execution stops (completely or
partially) and many operations upon a database remain uncompleted, with unclear status.
– To provide isolation between programs accessing a database concurrently. If this isolation
is not provided, the program's outcome are possibly erroneous.
● A database transaction, by definition, must be atomic, consistent, isolated and
durable. Database practitioners often refer to these properties of database
transactions using the acronym ACID.
●
Transactions provide an "all-or-nothing" proposition, stating that each work-
unit performed in a database must either complete in its entirety or have no
effect whatsoever. Further, the system must isolate each transaction from other
transactions, results must conform to existing constraints in the database, and
transactions that complete successfully must get written to durable storage.
– https://en.wikipedia.org/wiki/Database_transaction
45. 45
More Transactions!!
● InnoDB or NDB only!
● Start with
– Do your SELECT & UPDATE
to change data
● COMMIT to save
ROLLBACK to undo
● SAVEPOINT foo
ROLLBACK foo
– Intermediate rollback point
● Note MySQL SQL Mode is
STRICT by DEFAULT
– So watch for missing data
48. 48
What is a Query Plan?
● After your query syntax is
checked, the optimizer looks for
the most efficient way to gather
the data requested.
– Each column add roughly 1
factorial to the complexity
– Is the data in memory
● Dive to disk is 100,000
time slower
– Are indexes fresh? Are there
indexes?
MySQL wants to create a query
plan for each execution of each
query
49. 49
Things to tune
● innodb_stats_persistent=ON will store statistics between restarts so
your servers does not have to re-learn the best way to run the query
● innodb_stats_auto_recalc (default on, 10%) will automatically redo
stats after a limit of DML changes to a table
● Higher cardinality helps
– Design your indexes accordingly!!
● See MySQL Manual 14.3.11.1 Configuring Persistent Optimizer
Statistics Parameters for details
● Also add skip-name-resolve to keep bad DNS zone transfers from
killing your application
50. 50
● Check return codes
<?php
// we connect to example.com and port 3307
$link = mysql_connect('example.com:3307', 'mysql_user',
'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
Some Programming Advice
51. 51
● Check return codes
// Create connection
conn = new mysqli($servername, $username, $password, $dbname);
/ Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
Some More Programming Advice
52. 52
● Scrub all data coming into your database
– Less SQL Injection, more data integrity
● Think in SETs of data not ROWs
– Let database do heavy lifting
● Try to write good SQL
– Learn to use Visual Explain
– Actively look to reduce/combine queries
● Use Sys Schema to find indexes not being used, redundant
indexes and slow query log for queries that are running slow and
without indexes
Some Programming Advice