Relational Databases Charles Severance Relational Databases Relational databases model data by storing.

Slides:



Advertisements
Similar presentations
What is a Database By: Cristian Dubon.
Advertisements

Keys, Referential Integrity and PHP One to Many on the Web.
Python Crash Course Databases 3 rd year Bachelors V1.0 dd Hour 3.
Introduction to Structured Query Language (SQL)
Concepts of Database Management Sixth Edition
Relational Database Design and MySQL
Chapter 4 Relational Databases Copyright © 2012 Pearson Education, Inc. publishing as Prentice Hall 4-1.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 2: Single-Table Selections.
Chapter 7 Managing Data Sources. ASP.NET 2.0, Third Edition2.
Chapter 4 Relational Databases Copyright © 2012 Pearson Education 4-1.
Introduction To Databases IDIA 618 Fall 2014 Bridget M. Blodgett.
MS Access: Database Concepts Instructor: Vicki Weidler.
Page 1 ISMT E-120 Desktop Applications for Managers Introduction to Microsoft Access.
Session 5: Working with MySQL iNET Academy Open Source Web Development.
Database Types of database programs Charles w. Bachman Well- Designed Databases Database Management Systems Types of database programs Daabase Techniques.
Copyright © 2003 by Prentice Hall Module 4 Database Management Systems 1.What is a database? Data hierarchy and data organization Field, record, file,
Copyright © 2003 by Prentice Hall Computers: Tools for an Information Age Chapter 13 Database Management Systems: Getting Data Together.
ASP.NET Programming with C# and SQL Server First Edition
Copyright © 2003 Pearson Education, Inc. Slide 8-1 The Web Wizard’s Guide to PHP by David Lash.
PHP Programming with MySQL Slide 8-1 CHAPTER 8 Working with Databases and MySQL.
DAY 14: ACCESS CHAPTER 1 Tazin Afrin October 03,
Chapter 4 The Relational Model 3: Advanced Topics Concepts of Database Management Seventh Edition.
INLS 560 – R ELATIONAL DATABASES Instructor: Jason Carter.
Physical Database Design Chapter 6. Physical Design and implementation 1.Translate global logical data model for target DBMS  1.1Design base relations.
MIS 301 Information Systems in Organizations Dave Salisbury ( )
INFO 344 Web Tools And Development CK Wang University of Washington Spring 2014.
Chapter 7 Working with Databases and MySQL PHP Programming with MySQL 2 nd Edition.
1 Working with MS SQL Server Textbook Chapter 14.
PHP and MySQL CS How Web Site Architectures Work  User’s browser sends HTTP request.  The request may be a form where the action is to call PHP.
Access 2013 Microsoft Access 2013 is a database application that is ideal for gathering and understanding data that’s been collected on just about anything.
Relational Databases Database Driven Applications Retrieving Data Changing Data Analysing Data What is a DBMS An application that holds the data manages.
DAY 12: DATABASE CONCEPT Tazin Afrin September 26,
Database Essentials. Key Terms Big Data Describes a dataset that cannot be stored or processed using traditional database software. Examples: Google search.
Introduction to Databases Trisha Cummings. What is a database? A database is a tool for collecting and organizing information. Databases can store information.
Object Persistence Design Chapter 13. Key Definitions Object persistence involves the selection of a storage format and optimization for performance.
Database Design and Management CPTG /23/2015Chapter 12 of 38 Functions of a Database Store data Store data School: student records, class schedules,
INFO1408 Database Design Concepts Week 15: Introduction to Database Management Systems.
Microsoft Access. Microsoft access is a database programs that allows you to store retrieve, analyze and print information. Companies use databases for.
Introduction to Information Technology Applications.
Database Management Supplement 1. 2 I. The Hierarchy of Data Database File (Entity, Table) Record (info for a specific entity, Row) Field (Attribute,
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 22 - SQL, MySQL, DBI and ADO Outline 22.1 Introduction 22.2 Relational Database Model 22.3 Relational.
Relational Databases Charles Severance. Unless otherwise noted, the content of this course material is licensed under a Creative Commons Attribution 3.0.
Chapter 10 Database Management. Data and Information How are data and information related? p Fig Next processing data stored on disk Step.
Relational Databases: Basic Concepts BCHB Lecture 21 By Edwards & Li Slides:
Relational Databases and MySQL. Relational Databases Relational databases model data by storing rows and columns in tables. The power of the relational.
Relational Databases and SQLite
Relational Databases and MySQL Charles Severance
Relational Database Design and MySQL Charles Severance
Chapter 3: Relational Databases
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
CSC314 DAY 8 Introduction to SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall SQL OVERVIEW  Structured Query Language  The.
DAY 9: DATABASES Rohit February 17,
SQL Basics Review Reviewing what we’ve learned so far…….
Introduction to Database Programming with Python Gary Stewart
Chapter 12 Introducing Databases. Objectives What a database is and which databases are typically used with ASP.NET pages What SQL is, how it looks, and.
Understanding Core Database Concepts Lesson 1. Objectives.
Fundamentals of DBMS Notes-1.
Databases.
CS320 Web and Internet Programming SQL and MySQL
INLS 623– Database Systems II– File Structures, Indexing, and Hashing
Relational Databases and SQLite
Relational Databases and MySQL
Structured Query Language
Chapter 8 Working with Databases and MySQL
Teaching slides Chapter 8.
Chapter 22 - SQL, MySQL, DBI and ADO
Developing a Model-View-Controller Component for Joomla Part 3
Charles Severance Single Table SQL.
Understanding Core Database Concepts
Presentation transcript:

Relational Databases Charles Severance

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 and in particular where there are multiple tables and the relatinships between those tables involved in the query.

SQLite Database Browser SQLite is a very popular browser - it is free and fast and small We have a program to manipulate SQLite databases SQLite is embedded in Python and a number of other languages

SQLite is in lots of software... Symbian Python Philips Skype GE Microsoft McAfee Apple Adobe Firefox PHP Toshiba Sun Microsystems Google

Source: SQLite Terminal

Start Simple - A Single Table Lets make a table of People - with a Name and an

Our first table with two columns Source: SQLite Terminal

Our table with four rows Source: SQLite Terminal

SQL Structured Query Language is the language we use to issue commands to the database Create a table Retieve some data Insert data Delete data

SQL Insert The Insert statement inserts a row into a table insert into Users (name, ) values (‘Ted’,

Sources: SQLite Terminal

SQL Delete Deletes a row in a table based on a selection criteria delete from Users where

Sources: SQLite Terminal

SQL: Update Allows the updating of a field with a where clause update Users set name="Charles" where

Sources: SQLite Terminal

Retrieving Records: Select The select statement 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

Sources: SQLite Terminal

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 select * from Users order by name

Sources: SQLite Terminal

SQL Summary select * from Users select * from Users where update Users set name="Charles" where insert into Users (name, ) values (‘Ted’, delete from Users where select * from Users order by

This is not too exciting (so far) Tables pretty much look like big fast programmable spreadsheet with rows, columns, and commands The power comes when we have more than one table and we can exploit the relationships between the tables

Complex Data Models and Relationships

Database Design Database design is an art form of its own with particular skills and experience Our goal is to avoid the really bad mistakes and design clean and easily understood databases Others may performance tune things later Database design starts with a picture...

Building a Data Model Drawing a picture of the data objects for our application and then figuring out how to represent the objects and their relationships Basic Rule: Don’t put the same string data in twice - use a relationship instead When there is one thing in the “real world” there should be one copy of that thing in the database

TrackLenArtistAlbumGenreRatingCount Source: Apple iTunes Terminal

For each “piece of info”... Is the column an object or an attribute of another object? Once we define objects we need to define the relationships between objects. Track Len Artist Album Genre Rating Count Source: Apple iTunes Terminal

Track Len Artist Album Genre Rating Count belongs-to Source: Apple iTunes Terminal

Track Len Artist Album Genre Rating Count belongs-to Source: Apple iTunes Terminal

Representing Relationships in a Database

We want to keep track of who is the “owner” of each chat message... Who does this chat message “belong to”??? Source: CTools

Database Normalization (3NF) There is *tons* of database theory - way too much to understand without excessive predicate calculus Do not replicate data - reference data - point at data Use integers for keys and for references Add a special “key” to each table which we will reference - by convention many programmers call this “id”

Better Reference Pattern We use integers to reference rows in another table. Sources: SQLite Terminal

Keys Finding our way around....

Three Kinds of Keys Primary key - generally an integer auto-inrcement field Logical key - What the outside world uses for lookup Foreign key - generally an integer key point to a row in another table Site id title user_id...

Primary Key Rules Rails enourages you to follow best practices Never use your logical key as the primary key Logical keys can and do change albeit slowly Relationships that are based on matching string fields are far less efficient than integers performance-wise User id login password name created_at modified_at login_at

Foreign Keys A foreign key is when a table has a column that contains a key which points the primary key of another table. When all primary keys are integers, then all foreign keys are integers - this is good - very good If you use strings as foreign keys - you show yourself to be an uncultured swine User id login... Site id title user_id...

Relationship Building (in tables)

Track Len Artist Album Genre Rating Count belongs-to Source: Apple iTunes Terminal

Track Len AlbumRating Count belongs-to Album id title Track id title rating len count album_id Table Primary key Logical key Foreign key

Album id title Track id title rating len count album_id Table Primary key Logical key Foreign key Artist id name artist_id Genre id name genre_id Naming FK artist_id is a convention.

Sources: SQLite Terminal

insert into Artist (name) values ('Led Zepplin') insert into Artist (name) values ('AC/DC') Sources: SQLite Terminal

insert into Genre (name) values ('Rock') insert into Genre (name) values ('Metal') Source: SQLite Terminal

insert into Album (title, artist_id) values ('Who Made Who', 2) insert into Album (title, artist_id) values ('IV', 1) Source: SQLite Terminal

insert into Track (title, rating, len, count, album_id, genre_id) values ('Black Dog', 5, 297, 0, 1, 1) insert into Track (title, rating, len, count, album_id, genre_id) values ('Stairway', 5, 482, 0, 1, 1) insert into Track (title, rating, len, count, album_id, genre_id) values ('About to Rock', 5, 313, 0, 2, 2) insert into Track (title, rating, len, count, album_id, genre_id) values ('Who Made Who', 5, 207, 0, 2, 2) Source: SQLite Terminal

We have relationships! Sources: SQLite Terminal

Using Join Across Tables

Relational Power By removing the replicated data and replacing it with references to a single copy of each bit of data we build a “web” of information that the relational database can read through very quickly - even for very large amounts of data Often when you want some data it comes from a number of tables linked by these foreign keys

The JOIN Operation The JOIN operation links across several tables as part of a select operation You must tell the JOIN the keys which make the connection between the tables using an ON clause

select Track.title, Genre.name from Track join Genre on Track.genre_id = Genre.id What we want to see The tables which hold the data How the tables are linked Sources: SQLite Terminal

It can get complex... select Track.title, Artist.name, Album.title, Genre.name from Track join Genre join Album join Artist on Track.genre_id = Genre.id and Track.album_id = Album.id and Album.artist_id = Artist.id What we want to see The tables which hold the data How the tables are linked Sources: SQLite Terminal

Complexity enables Speed Complexity makes speed possible and allows you to get very fast results as the data size grows. By normalizing the data and linking it with integer keys, the overall amount of data which the relational database must scan is far lower than if the data were simply flattened out. It might seem like a tradeoff - spend some time designing your database so it continues to be fast when your application is a success

Python and SQLite3

SQLite3 is built into Python Since SQLite is simple and small and designed to be “embedded” - Python decided to embed SQLite into Python You simply “import sqlite3” and open a connection to the database and start doing SQL commands

SQLite3 is built into Python import sqlite3 # Open up the database file and get a cursor conn = sqlite3.connect('music.db') c = conn.cursor() print "Genre Rows" c.execute('select * from Genre') for row in c : print row $ python sql1.py Genre Rows (1, u'Rock') (2, u'Metal') $ ls music.db sql1.py sql2.py SQLite stores all tables and data in a single file.

import sqlite3 # Open up the database file and get a cursor conn = sqlite3.connect('music.db') c = conn.cursor() print "Inserting Country" c.execute('insert into Genre (name) values ( ? )', ( 'Country', ) ) print "Genre Rows" c.execute('select * from Genre') for row in c : print row print "Deleting Country" c.execute("delete from Genre where name='Country'") print "Genre Rows" c.execute('select * from Genre') for row in c : print row $ python sql2.py Inserting Country Genre Rows (1, u'Rock') (2, u'Metal') (3, u'Country') Deleting Country Genre Rows (1, u'Rock') (2, u'Metal')

Additional SQL Topics Indexes improve access performance for things like string fields Constraints on data - (cannot be NULL, etc..) Transactions - allow SQL operations to be grouped and done as a unit See SI572 - Database Design

Summary Relational databases allow us to scale to very large amounts of data The key is to have one copy of any data element and use relations and joins to link the data to multiple places This greatly reduces the amount of data which much be scanned when doing complex operations across large amounts of data Database and SQL design is a bit of an art-form