Relational Databases. Charles Severance



Similar documents
Relational Databases and SQLite

Financial Data Access with SQL, Excel & VBA

Advanced Online Media Dr. Cindy Royal Texas State University - San Marcos School of Journalism and Mass Communication

How to Move Object-Relational Mapping into the Database. David Wheeler Kineticode OSCON 2005

Web Development using PHP (WD_PHP) Duration 1.5 months

SQL Server An Overview

Process Automation Tools For Small Business

Using SQL Server Management Studio

A Guide to using egas Lead Applicant

Lecture 25: Database Notes

Oracle Database 10g Express

MS Access Lab 2. Topic: Tables

Microsoft Access Basics

NoSQL replacement for SQLite (for Beatstream) Antti-Jussi Kovalainen Seminar OHJ-1860: NoSQL databases

Instant SQL Programming

Physical Database Design Process. Physical Database Design Process. Major Inputs to Physical Database. Components of Physical Database Design

A Brief Introduction to MySQL

Oracle SQL. Course Summary. Duration. Objectives

f...-. I enterprise Amazon SimpIeDB Developer Guide Scale your application's database on the cloud using Amazon SimpIeDB Prabhakar Chaganti Rich Helms

Oracle Database: SQL and PL/SQL Fundamentals NEW

Database Design for the Uninitiated CDS Brownbag Series CDS

SQL Server. 1. What is RDBMS?

Database Administration with MySQL

Unit 5.1 The Database Concept

Tutorial 3. Maintaining and Querying a Database

Microsoft Office 2010

Online Database Management System

Oracle 10g PL/SQL Training

Oracle Database: SQL and PL/SQL Fundamentals

Serious Threat. Targets for Attack. Characterization of Attack. SQL Injection 4/9/2010 COMP On August 17, 2009, the United States Justice

12 File and Database Concepts 13 File and Database Concepts A many-to-many relationship means that one record in a particular record type can be relat

Creating Database Tables in Microsoft SQL Server

Role Based Access Control. Using PHP Sessions

Database Design and Normalization

Equipment Room Database and Web-Based Inventory Management

SQL Injection. SQL Injection. CSCI 4971 Secure Software Principles. Rensselaer Polytechnic Institute. Spring

Netezza Workbench Documentation

CSCI110 Exercise 4: Database - MySQL

Introduction to Microsoft Access 2010

Totally Internet Based Software. Getting Started. Strategy Systems, Inc. PO Box 2136 Rogers, AR (479)

Multimedia im Netz Online Multimedia Winter semester 2015/16

Demystified CONTENTS Acknowledgments xvii Introduction xix CHAPTER 1 Database Fundamentals CHAPTER 2 Exploring Relational Database Components

Unit 10: Microsoft Access Queries

Testing of the data access layer and the database itself

DIPLOMA IN WEBDEVELOPMENT

ANDROID APPS DEVELOPMENT FOR MOBILE GAME

Introduction to Microsoft Access 2013

Oracle Database 11g SQL

CS 145: NoSQL Activity Stanford University, Fall 2015 A Quick Introdution to Redis

ADO and SQL Server Security

Using Multiple Operations. Implementing Table Operations Using Structured Query Language (SQL)

MySQL for Beginners Ed 3

Oracle Database: SQL and PL/SQL Fundamentals

Experiment 5.1 How to measure performance of database applications?

Microsoft Access 2007

SAP Business Objects Business Intelligence platform Document Version: 4.1 Support Package Data Federation Administration Tool Guide

Use Find & Replace Commands under Home tab to search and replace data.

Performance Implications of Various Cursor Types in Microsoft SQL Server. By: Edward Whalen Performance Tuning Corporation

Gaz s Mac Notes. Startup


Online shopping store

Microsoft Access 3: Understanding and Creating Queries

Introduction to Microsoft Jet SQL

B.1 Database Design and Definition

Google App Engine Data Store

Execution Plans: The Secret to Query Tuning Success. MagicPASS January 2015

AUTHENTICATION... 2 Step 1:Set up your LDAP server... 2 Step 2: Set up your username... 4 WRITEBACK REPORT... 8 Step 1: Table structures...

e-administration your guide to using with TNT

SQL Server for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach

White Paper. Blindfolded SQL Injection

Introduction to Microsoft Access 2003

Information Systems SQL. Nikolaj Popov

e-invoicing your guide to using with TNT

ACCESS Importing and Exporting Data Files. Information Technology. MS Access 2007 Users Guide. IT Training & Development (818)

CS2Bh: Current Technologies. Introduction to XML and Relational Databases. Introduction to Databases. Why databases? Why not use XML?

Human Computer Interaction Final Project Tutorial. Hardware Inventory Management System (HIMS) By M. Michael Nourai

SQL Injection for newbie

1Z0-117 Oracle Database 11g Release 2: SQL Tuning. Oracle

Database: SQL, MySQL

Database Query 1: SQL Basics

A basic create statement for a simple student table would look like the following.

Oracle Database 12c: Introduction to SQL Ed 1.1

Higher National Unit specification: general information. Relational Database Management Systems

Performance Tuning for the Teradata Database

Ken Goldberg Database Lab Notes. There are three types of relationships: One-to-One (1:1) One-to-Many (1:N) Many-to-Many (M:N).

SQL Server Database Coding Standards and Guidelines

Maintaining Stored Procedures in Database Application

Once the schema has been designed, it can be implemented in the RDBMS.

ICE for Eclipse. Release 9.0.1

Database 10g Edition: All possible 10g features, either bundled or available at additional cost.

Database Design Patterns. Winter Lecture 24

SECURING APACHE : THE BASICS - III

Developing Web Applications for Microsoft SQL Server Databases - What you need to know

NoSQL, But Even Less Security Bryan Sullivan, Senior Security Researcher, Adobe Secure Software Engineering Team

DBMS / Business Intelligence, SQL Server

SoftwarePlanner Active Directory Authentication

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

Micro Focus Database Connectors

IENG2004 Industrial Database and Systems Design. Microsoft Access I. What is Microsoft Access? Architecture of Microsoft Access

D61830GC30. MySQL for Developers. Summary. Introduction. Prerequisites. At Course completion After completing this course, students will be able to:

Transcription:

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. http://en.wikipedia.org/wiki/relational_database

SQLite Database Browser SQLite is a very popular browser - it is free and fast and small We have a program to manipulate SQLite databases http://sqlitebrowser.sourceforge.net/ SQLite is embedded in Python and a number of other languages

SQLite is in lots of software... Symbian GE Adobe Python Microsoft Firefox PHP Philips Skype McAfee Apple Toshiba Google http://www.sqlite.org/famous.html Sun Microsystems

http://sqlitebrowser.sourceforge.net/ Source: SQLite Terminal

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

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 http://en.wikipedia.org/wiki/sql

SQL Insert The Insert statement inserts a row into a table insert into Users (name, email) values ( Ted, ted@umich.edu )

Sources: SQLite Terminal

SQL Delete Deletes a row in a table based on a selection criteria delete from Users where email='ted@umich.edu'

Sources: SQLite Terminal

SQL: Update Allows the updating of a feld with a where clause update Users set name="charles" where email='csev@umich.edu'

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 email='csev@umich.edu'

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

Sources: SQLite Terminal

SQL Summary insert into Users (name, email) values ( Ted, ted@umich.edu ) delete from Users where email='ted@umich.edu' update Users set name="charles" where email='csev@umich.edu' select * from Users select * from Users where email='csev@umich.edu' select * from Users order by email

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 http://en.wikipedia.org/wiki/relational_model

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

Track Len Artist Album Source: Apple itunes Terminal Genre Rating Count

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

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

Artist Track Rating belongs-to Album Len belongs-to Count belongs-to Genre 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 http://ctools.umich.edu

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 http://en.wikipedia.org/wiki/database_normalization

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 autoinrcement feld 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 Logical keys can and do change albeit slowly Never use your logical key as the primary key Relationships that are based on matching string felds are far less effcient than integers performance-wise User id login password name email 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)

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

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

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

Sources: SQLite Terminal

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 http://en.wikipedia.org/wiki/join_(sql)

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 Sources: SQLite Terminal The tables which hold the data How the tables are linked

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

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 fattened 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 http://www.python.org/doc/2.5.2/lib/module-sqlite3.html

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 http://www.python.org/doc/2.5.2/lib/module-sqlite3.html

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 SQLite stores all tables and data in a single file. $ python sql1.py Genre Rows (1, u'rock') (2, u'metal') $ ls music.db sql1.py sql2.py

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 felds 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 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 The key is to have one copy of any data element and use relations and joins to link the data to multiple places