0% found this document useful (0 votes)
48 views

Relational Databases and Mysql: This Work Is Licensed Under A

This document discusses relational databases and MySQL. It introduces relational databases and how they store data in tables with rows and columns. It describes structured query language (SQL) which is used to issue commands to databases, and MySQL, a popular open source database management system. The document provides examples of SQL commands like SELECT, INSERT, UPDATE, and DELETE.

Uploaded by

Raya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Relational Databases and Mysql: This Work Is Licensed Under A

This document discusses relational databases and MySQL. It introduces relational databases and how they store data in tables with rows and columns. It describes structured query language (SQL) which is used to issue commands to databases, and MySQL, a popular open source database management system. The document provides examples of SQL commands like SELECT, INSERT, UPDATE, and DELETE.

Uploaded by

Raya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Lecture 9

Relational Databases and MySQL

This work is licensed under a Creative Commons Attribution- Share Alike 4. 0 International License
Sequentia
OLD l NEW
Sorted Master Sorted
Update
1970s
Merge

Transaction
s
Sorted https://en.wikipedia.org/wiki/IBM_72
9
Random Access

• When you can randomly access


data...

• How can you lay out data to be


most efficient?

• Sorting might not be the best idea

https://en.wikipedia.org/wiki/Hard_disk_drive_platter
Relational Databases
Relational databases model data by storing
rows and columns in tables. The power of
the relational database lies in its ability to
efficiently retrieve data from those tables - in
particular, where the query involves multiple
tables and the relationships between those
tables.
http://en.wikipedia.org/wiki/Relational_database
Structured Query Language
• Structured Query Language
(SQL) came out of a
government / industry
partnership

• National Institute of
Standards and Technology
(NIST)

https://youtu.be/rLUm3vst87g
SQL
Structured Query Language is the
language we use to issue commands
to the database

- Create/Insert data

- Read/Select some data

- Update data
http://en.wikipedia.org/wiki/SQL
- Delete data
https://en.wikipedia.org/wiki/ANSI-SPARC_Architecture
Terminology
• Database - contains one or more tables

• Relation (or table) - contains tuples and attributes

• Tuple (or row) - a set of fields which generally represent an “object”


like a person or a music track

• Attribute (also column or field) - one of possibly many elements of


data corresponding to the object represented by the row
A relation is defined as a set of tuples that have the same attributes. A tuple usually represents an object
and information about that object. Objects are typically physical objects or concepts. A relation is usually
described as a table, which is organized into rows and columns. All the data referenced by an attribute are
in the same domain and conform to the same constraints. (wikipedia)
Columns /
Attributes
Rows /
Tuples

Tables /
Relations
Common Database Systems
• Three major Database Management Systems in wide use

- Oracle - Large, commercial, enterprise-scale, very tweakable

- MySQL - Simpler but very fast and scalable - commercial open source

- SqlServer - Very nice - from Microsoft (also Access)

• Many other smaller projects, free and open source

- HSQL, SQLite, PostgreSQL ...


Using SQL
Using SQL

phpMyAdmin SQL
(Browser)
User Database
D.B.A. Server
mysql MySQL
(Command SQL

Line)
• Macintosh Command Line
- /Applications/MAMP/Library/bin/mysql … (see handout for PW)

- Enter "root" when prompted for the password

• Windows

- c:\xampp\mysql\bin\mysql.exe -u root –p

- Press enter when prompted for password

TRY THIS AND SEE THE OUTPUT

https://www.wa4e.com/lectures/SQL-01-MySQL-Handout.txt
Your First MySQL Command

show databases
Kind of like print('hello world’)

TRY AND SEE THE OUTPUT


Creating a Database
Command Line:

CREATE DATABASE People DEFAULT CHARACTER SET utf8;


USE People;
Start Simple - A Single Table
• Let’s make a table of Users in our People database

• Two columns - name and email

CREATE TABLE Users(


name VARCHAR(128),
email VARCHAR(128)
);

DESCRIBE Users;
SQL: Insert
The INSERT statement inserts a row into a table

INSERT INTO Users (name, email) VALUES ('Chuck', '[email protected]') ;


INSERT INTO Users (name, email) VALUES ('Somesh', '[email protected]') ;
INSERT INTO Users (name, email) VALUES ('Caitlin', '[email protected]') ;
INSERT INTO Users (name, email) VALUES ('Ted', '[email protected]') ;
INSERT INTO Users (name, email) VALUES ('Sally', '[email protected]') ;
SQL: Delete
Deletes a row in a table based on selection criteria

DELETE FROM Users WHERE email='[email protected]'


SQL: Update
Allows the updating of a field with a WHERE clause

UPDATE Users SET name='Charles' WHERE email='[email protected]'


Retrieving Records: Select
Retrieves a group of records - you can either retrieve all the records
or a subset of the records with a WHERE clause

SELECT * FROM Users

SELECT * FROM Users WHERE email='[email protected]'


Sorting with ORDER BY
You can add an ORDER BY clause to SELECT statements to
get the results sorted in ascending or descending order

SELECT * FROM Users ORDER BY email


The LIKE Clause
We can do wildcard matching in a WHERE clause
using the LIKE operator

SELECT * FROM Users WHERE name LIKE '%e%'


The LIMIT Clause
• The LIMIT clause can request the first "n" rows, or the first "n" rows
after some starting row. Note: the first row is zero, not one.

• WHERE and ORDER BY clauses happen *before* the LIMIT is


applied.

• The limit can be a count or a starting row and count (starts from 0).

SELECT * FROM Users ORDER BY email DESC LIMIT 2;


SELECT * FROM Users ORDER BY email LIMIT 1,2;
Counting Rows with SELECT
You can request to receive the count of the rows that
would be retrieved instead of the rows

SELECT COUNT(*) FROM Users;


SELECT COUNT(*) FROM Users WHERE email='[email protected]'
SQL Summary
INSERT INTO Users (name, email) VALUES ('Ted', '[email protected]')

DELETE FROM Users WHERE email='[email protected]'

UPDATE Users SET name='Charles' WHERE email='[email protected]'

SELECT * FROM Users WHERE email='[email protected]'

SELECT * FROM Users ORDER BY email

SELECT * FROM Users WHERE name LIKE '%e%'

SELECT * FROM Users ORDER BY email LIMIT 1,2;

SELECT COUNT(*) FROM Users WHERE email='[email protected]'


This is not too exciting (so far)
• Tables pretty much look like big, fast programmable spreadsheets with
rows, columns, and commands.

• The power comes when we have more than one table and we can
exploit the relationships between the tables.
Table Schema
Looking at Data Types

• Text fields (small and large)

• Binary fields (small and large)

• Numeric fields

• AUTO_INCREMENT fields
String Fields

• Understand character sets and are indexable for searching

• CHAR allocates the entire space (faster for small strings where length
is known)

• VARCHAR allocates a variable amount of space depending on the data


length (less space)
Text Fields
• Have a character set - paragraphs or HTML pages

- TINYTEXT up to 255 characters

- TEXT up to 65K

- MEDIUMTEXT up to 16M

- LONGTEXT up to 4G

• Generally not used with indexing or sorting - and only then limited to a
prefix
Binary Types (rarely used)
• Character = 8 - 32 bits of information depending on character set

• Byte = 8 bits of information

- BYTE(n) up to 255 bytes

- VARBINARY(n) up to 65K bytes

• Small Images - data

• Not indexed or sorted


Integer Numbers
Integer numbers are very efficient, take little storage, and are easy to process
because CPUs can often compare them with a single instruction.

- TINYINT (-128, 128)

- SMALLINT (-32768, +32768)

- INT or INTEGER (2 Billion)

- BIGINT - (10**18 ish)


Floating Point Numbers
Floating point numbers can represent a wide range of values, but accuracy
is limited.

- FLOAT (32-bit) 10**38 with seven digits of accuracy

- DOUBLE (64-bit) 10**308 with 14 digits of accuracy


Dates
• TIMESTAMP - 'YYYY-MM-DD HH:MM:SS' (1970, 2037)

• DATETIME - 'YYYY-MM-DD HH:MM:SS'

• DATE - 'YYYY-MM-DD'

• TIME - 'HH:MM:SS'

• Built-in MySQL function NOW()


AUTO_INCREMENT
DROP TABLE Users;
Often as we make multiple
tables and need to JOIN them CREATE TABLE Users (
together we need an integer user_id INT UNSIGNED NOT NULL
AUTO_INCREMENT,
primary key for each row so we
name VARCHAR(128),
can efficiently add a reference to email VARCHAR(128),
a row in some other table as a PRIMARY KEY(user_id)
foreign key. )

DESCRIBE Users;
MySQL Functions
Many operations in MySQL need to use the built-in functions (like
NOW() for dates).

• http://dev.mysql.com/doc/refman/5.0/en/string-functions.html

• http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html
Indexes
• As a table gets large (they always do), scanning all the data to find a
single row becomes very costly

• When [email protected] logs into FaceBook, they must find my


password amongst 500 million users

• There are techniques to greatly shorten the scan as long as you create
data structures and maintain those structures - like shortcuts

• Hashes or Trees
MySQL Index Types

• PRIMARY KEY - Very little space, exact match, requires no


duplicates, extremely fast for integer fields

• INDEX - Good for individual row lookup and sorting / grouping


results - works best with exact matches or prefix lookups - can suggest
HASH or BTREE
The JOIN Operation
• The JOIN operation links across several tables as part of a SELECT
operation.

• You must tell the JOIN how to use the keys that make the connection
between the tables using an ON clause.
The tables that
hold the data

SELECT Album.title, Artist.name FROM Album JOIN Artist ON


What we want Album.artist_id = Artist.artist_id How the tables
to see are linked
Album.title Album.artist_id Artist.artist_id Artist.name

SELECT Album.title, Album.artist_id, Artist.artist_id,Artist.name


FROM Album JOIN Artist ON Album.artist_id = Artist.artist_id
SELECT Track.title,
Track.genre_id,
Genre.genre_id,
Genre.name
FROM Track JOIN Genre

Joining two tables without an ON clause gives all possible combinations of rows.
SELECT Track.title, Genre.name FROM Track JOIN Genre
ON Track.genre_id = Genre.genre_id
Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance (www.dr- Continue new Contributors and Translators here
chuck.com) as part of www.wa4e.com and made available under a
Creative Commons Attribution 4.0 License. Please maintain this
last slide in all copies of the document to comply with the
attribution requirements of the license. If you make a change, feel
free to add your name and organization to the list of contributors
on this page as you republish the materials.

Initial Development: Charles Severance, University of Michigan


School of Information

Insert new Contributors and Translators here including names and


dates

You might also like