SQL. Draft Version. Head First. A Brain-Friendly Guide. Lynn Beighley. A learner s companion to database programming using SQL

Similar documents
Getting Started with Processing by Casey Reas and Ben Fry

BIG BOOK OF. Windows Hacks. Preston Gralla. Tips & Tools for unlocking the power of your Windows PC

Reactive Programming with RxJS 5

Intermediate Perl Table of Contents Intermediate Perl Foreword Preface Structure of This Book Conventions Used in This Book Using Code Examples

Java By Comparison. Extracted from: Become a Java Craftsman in 70 Examples. The Pragmatic Bookshelf

Jakarta Struts. Pocket Reference. Chuck Cavaness and Brian Keeton. Beijing Boston Farnham Sebastopol Tokyo

Want to read more? You can buy this book at oreilly.com in print and ebook format. Buy 2 books, get the 3rd FREE!

Build Database Apps in Elixir for Scalability and Performance

Pragmatic Guide to Git

More Relational Algebra

1 Robust Database Design. 2 Why is it so difficult? 3 Where does it all start? 3.1 Objects

2004 John Mylopoulos. The Entity-Relationship Model John Mylopoulos. The Entity-Relationship Model John Mylopoulos

CS352 Lecture - Data Models

Building Android Apps with HTML, CSS, and JavaScript

Java by Comparison. Extracted from: Become a Java Craftsman in 70 Examples. The Pragmatic Bookshelf

COMP Instructor: Dimitris Papadias WWW page:

SQL Antipatterns. Extracted from: Avoiding the Pitfalls of Database Programming. The Pragmatic Bookshelf

CSE 530A. ER Model to Relational Schema. Washington University Fall 2013

Creating Reports. There are several types of reports. We'll use Access Wizards and Tabs/Ribbons to design several simple reports.

Oracle Database 10g Express

COPYRIGHTED MATERIAL. Databases

In-Class Exercise: SQL #2 Putting Information into a Database

Cocoa Programming A Quick-Start Guide for Developers

Learn Functional Programming with Elixir

Practical Programming, 2nd Edition

XV. The Entity-Relationship Model

Web Design for Developers A Programmer s Guide to Design Tools and Techniques

CSE 530A. Inheritance and Partitioning. Washington University Fall 2013

SQL Data Definition Language: Create and Change the Database Ray Lockwood

Effective Testing with RSpec 3

5. Technology Applications

Copyright 2009 The Pragmatic Programmers, LLC.

Build Safe and Maintainable Front-End Applications

Amazon. Case study Digital Relationship Marketing (RM) Academy Extending the consumer journey with RM Amazon: Perfect personalization

SECTION 1 DBMS LAB 1.0 INTRODUCTION 1.1 OBJECTIVES 1.2 INTRODUCTION TO MS-ACCESS. Structure Page No.

CDR DICOM Quick Start Guide

The SQL Guide to Pervasive PSQL. Rick F. van der Lans

As your databases continue to evolve, you will need to incorporate advanced queries and reports. This chapter addresses how to create and use action

MIS2502: Data Analytics MySQL and SQL Workbench. Jing Gong

Unit 6A. SQL: Overview and Coding SQL Commands

CIS 45, The Introduction. What is a database? What is data? What is information?

Corticon Rule Modeling Challenge Jan 2018 Order Promotions

Lesson 14 Transcript: Triggers

SQL stands for Structured Query Language. SQL is the lingua franca

Bsc (Hons) Software Engineering. Examinations for / Semester 1. Resit Examinations for BSE/15A/FT & BSE/16A/FT

CIS 363 MySQL. Chapter 12 Joins Chapter 13 Subqueries

Practical Programming, Third Edition

Record-Level Access: Under the Hood

The DBMS accepts requests for data from the application program and instructs the operating system to transfer the appropriate data.

2. E/R Design Considerations

DC62 Database management system JUNE 2013

Microsoft Access 2007 Module 1

Consistency The DBMS must ensure the database will always be in a consistent state. Whenever data is modified, the database will change from one

INFORMATICS PRACTICES

Developing Android on Android

iphone SDK Development

PRIVACY. YOUR DATA. YOUR TRUST.

Reactive Programming with RxJS

All-In-One-Designer SEO Handbook

SOCIAL PROOF to drive online sales and engagement

MIS2502: Data Analytics Relational Data Modeling. Jing Gong

VISUAL QUICKSTART GUIDE QUICKTIME PRO 4. Judith Stern Robert Lettieri. Peachpit Press

FACULTY AND STAFF COMPUTER FOOTHILL-DE ANZA. FileMaker Pro. Relational Databases

COMM 391. Objectives. Introduction to Microsoft Access. What is in an Access database file? Introduction to Microsoft Access 2010

MIS2502: Data Analytics Relational Data Modeling. Jing Gong

Database Programming with SQL

Build ios Games with Sprite Kit

System Structure. Steven M. Bellovin December 14,

THE 18 POINT CHECKLIST TO BUILDING THE PERFECT LANDING PAGE

Build Reactive Websites with RxJS

Instructor: Craig Duckett. Lecture 03: Tuesday, April 3, 2018 SQL Sorting, Aggregates and Joining Tables

Complex Network Analysis in Python

THIRD EDITION CSS. Pocket Reference. Eric A. Meyer. Beijing Cambridge Farnham Köln Paris Sebastopol Taipei Tokyo

PS-80 Storing Data in the Right Place in Deltek Vision

relational Key-value Graph Object Document

Graphical Joins in More Detail

Keys are fields in a table which participate in below activities in RDBMS systems:

Designing Tables for an Oracle Database System. From theory to practice

Create and Modify Queries 7

crm-now/ps Webforms Webdesigner Manual Second Edition

Chapter 6: Entity-Relationship Model. The Next Step: Designing DB Schema. Identifying Entities and their Attributes. The E-R Model.

CHAPTER4 CONSTRAINTS

Handling hierarchical data

Agile Web Development with Rails 5.1

Access Intermediate

Content Curation Mistakes

Powered by. How did trying to give apples away for free change the world?

CS352 Lecture - Data Models

c r e at i N g yo u r F i r S t d ata b a S e a N d ta b l e

Beginning Mac Programming

Modern Vim. Extracted from: Craft Your Development Environment with Vim 8 and Neovim. The Pragmatic Bookshelf

FROM A RELATIONAL TO A MULTI-DIMENSIONAL DATA BASE

Microsoft Exam

The Next Step: Designing DB Schema. Chapter 6: Entity-Relationship Model. The E-R Model. Identifying Entities and their Attributes.

DUE: 9. Create a query that will return the average order total for all Global Fast Foods orders from January 1, 2002, to December 21, 2002.

Chapter. Relational Database Concepts COPYRIGHTED MATERIAL

Mastering the Actuarial Tool Kit

SYSTEM 2000 Essentials

Introduction to Relational Database Concepts. Copyright 2011, Oracle. All rights reserved.

Craigslist Quick Tricks Manual helping you get your ads on Craigslist and getting people to click through to your site or product offer

Transcription:

A Brain-Friendly Guide Load important concepts directly into your brain Head First SQL A learner s companion to database programming using SQL Avoid embarrassing mistakes Master out of this world concepts Learn what matters, when it matters Bend your mind around dozens of puzzles and exercises this is a new chapter # Lynn Beighley

Head First SQL by Lynn Beighley Copyright 2007 O Reilly Media, Inc. All rights reserved. Printed in the United States of America. Published by O Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O Reilly Media books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com. Printing History: August 2007: First Edition. The O Reilly logo is a registered trademark of O Reilly Media, Inc. The Head First series designations, Head First SQL, and related trade dress are trademarks of O Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and the authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. ISBN-10: 0-596-52684-9 ISBN-13: 978-0-596-52684-9 [M]

7 multi-table database design Outgrowing your table My little man is growing up. Maybe he ll finally move out. Sometimes your single table isn t big enough anymore. Your need for data has grown, and that one table you ve been using just isn t cutting it. Your SELECTs are getting messy and harder to write. You ve gone as far as you can go. It s a big world out there, and sometimes you need more than one table to to contain your data, control it, and ultimately, be the master of your own database. this is a new chapter 1

one-to-one relationships Relationships between tables We know how to connect the tables through foreign keys now, but we still need to consider how the tables relate to each other. In the my_contacts table, our problem is that we need to associate lots of people with lots of interests. This is one of three possible patterns you ll see again and again with your data: one to one, one to many, and many to many and once you identify the pattern your data matches, coming up with the design of multiple tables your schema becomes simple. Patterns of data: one to one Let s look at the first pattern, one to one, and see how it applies. In this pattern a record in Table A can have at most ONE matching record in Table B. So, say Table A contains your name, and Table B contains your salary details and Social Security Numbers, to isolate them from the rest of the table to keep them more secure. Both tables will contain your ID number so you get the right paycheck. Table A ONE matches up TO Table B ONE Each person in employees can only have one Social Security number, and each SSN maps to only one person. One person, one SSN, makes this a one-to-one relationship. employees employee_id first_name last_name 1 Beyonce Knowles 2 Shawn Carter 3 Shakira Ripoll salary ssn salary_level employee_id 234567891 2 6 345678912 5 35 123456789 7 1 These tables also have a one to one relationship, since the primary key of the employee table, employee_id, is being used as the foreign key of the salary table. 2 Chapter 7

multi-table database design Patterns of data: when to use one to one tables So we should be putting all our one to one columns in new tables? Actually, no. We won t use one-to-one tables all that often. There are only a few reasons why you might connect your tables in a one-to-one relationship. When to use one-to-one tables It generally makes more sense to leave those rare one-to-one columns in your main table, but there are a few advantages you can get from pulling those columns out at times: 1. Pulling the data out may allow you to write faster queries. For example, if most of the time you needed to query the SSN and not much else, you could query just the smaller table. 2. If you have a column containing values you don t yet know, you can isolate it and avoid NULL values in your main table. 3. You may wish to make some of your data less accessible. Isolating it can allow you to restrict access to it. For example, if you have a table of employees, you might want to keep their salary information out of the main table. One-to-One: a single table, or (sometimes) two tables related with primary and foreign keys. you are here 4 3

one-to-many relationships Patterns of data: one to many One-to-many means that a record in Table A can have many matching in Table B, but a record in Table B can only match one record in Table A. Table A ONE matches up TO Table B MANY One record in Table A can match MANY in Table B, but any one record of Table B can only match ONE record in Table A. One-to-Many: split the data into two tables related with primary and foreign keys. The state column in my_contacts is a good example of a one-to-many relationship. Each person has only one state in the state column for his address, but more than one person in my_contacts may live in any given state. In this example, we ve moved the state column to a new child table, and changed the state column in the parent table to a foreign key, the state_id column. Since it s a one to many relationship, we can use the state_id in both tables to allow us to connect them. The connecting line has a black arrow at the end to show that we re linking one thing to many things. Each row in the states table can have many matching rows in my_contacts, but each row in my_contacts has only one matching row in the states table. For example, the state_id for California may show up more than once in my_contacts, but each person in my_contacts will only have one state_id. states state_id state Because the state_id can repeat, this can t be a primary key. This is a foreign key because it references a key from another table.. my_contacts contact_id last_name first_name phone email gender birthday profession city state_id status seeking 4 Chapter 7

multi-table database design Patterns of data: getting to many to many Many women own many pairs of shoes. If we created a table containing women and another table containing shoes to keep track of them all, we d need to link many to many since more than one woman can own a particular make of shoe. Suppose Carrie and Miranda buy both the Old Navy Flops and Prada boots, and Samantha and Miranda both have the Manolo Strappies, and Charlotte has one of each. Here s how the links between the women and shoes tables would look. woman_id woman shoe_id shoe_name 1 Carrie 2 Samantha 3 Charlotte 4 Miranda 1 Manolo Strappies 2 Crocs Clogs 3 Old Navy Flops 4 Prada Boots woman_id woman shoe_id Imagine they loved the shoes so much, the women all bought a pair of the shoes they didn t already own. Here s how the links from women to each shoe names would look then. shoe_name 1 Carrie 2 Samantha 3 Charlotte 4 Miranda 1 Manolo Strappies 2 Crocs Clogs 3 Old Navy Flops 4 Prada Boots Can you say: Duplicate? How can we fix the tables without putting more than one value in a column and winding up like Greg did with his queries for Regis? you are here 4 5