0% found this document useful (0 votes)
7 views80 pages

Getting Started With SQL and Databases: Managing and Manipulating Data With SQL 1st Edition Mark Simon PDF Download

The document provides information about the book 'Getting Started with SQL and Databases: Managing and Manipulating Data with SQL' by Mark Simon, including its content structure and chapters. It also includes links to various related eBooks on SQL and databases, along with details about the publishing rights and distribution. The book aims to teach readers the fundamentals of SQL and database management through practical examples and explanations.

Uploaded by

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

Getting Started With SQL and Databases: Managing and Manipulating Data With SQL 1st Edition Mark Simon PDF Download

The document provides information about the book 'Getting Started with SQL and Databases: Managing and Manipulating Data with SQL' by Mark Simon, including its content structure and chapters. It also includes links to various related eBooks on SQL and databases, along with details about the publishing rights and distribution. The book aims to teach readers the fundamentals of SQL and database management through practical examples and explanations.

Uploaded by

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

Getting Started with SQL and Databases: Managing

and Manipulating Data with SQL 1st Edition Mark


Simon install download

https://ebookmeta.com/product/getting-started-with-sql-and-
databases-managing-and-manipulating-data-with-sql-1st-edition-
mark-simon/

Download more ebook from https://ebookmeta.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!

SQL QuickStart Guide The Simplified Beginner s Guide to


Managing Analyzing and Manipulating Data With SQL
Walter Shields

https://ebookmeta.com/product/sql-quickstart-guide-the-
simplified-beginner-s-guide-to-managing-analyzing-and-
manipulating-data-with-sql-walter-shields/

Python Data Persistence With SQL and NOSQL Databases


1st Edition Lathkar

https://ebookmeta.com/product/python-data-persistence-with-sql-
and-nosql-databases-1st-edition-lathkar/

Leveling Up with SQL: Advanced Techniques for


Transforming Data into Insights 1st Edition Mark Simon

https://ebookmeta.com/product/leveling-up-with-sql-advanced-
techniques-for-transforming-data-into-insights-1st-edition-mark-
simon/

Asian Development Bank Sustainability Report 2018


Investing for an Asia and the Pacific Free of Poverty
1st Edition Asian Development Bank

https://ebookmeta.com/product/asian-development-bank-
sustainability-report-2018-investing-for-an-asia-and-the-pacific-
free-of-poverty-1st-edition-asian-development-bank/
Friends with Benefits Goals Friends To Lovers Bad Boy
Sports Romance Romance Goals Book 4 1st Edition Barbi
Cox

https://ebookmeta.com/product/friends-with-benefits-goals-
friends-to-lovers-bad-boy-sports-romance-romance-goals-
book-4-1st-edition-barbi-cox/

Philosophical Trends in the Feminist Movement 2nd


Edition Anuradha Ghandy

https://ebookmeta.com/product/philosophical-trends-in-the-
feminist-movement-2nd-edition-anuradha-ghandy/

The Appraisal of Real Estate 15th Edition Appraisal


Institute

https://ebookmeta.com/product/the-appraisal-of-real-estate-15th-
edition-appraisal-institute/

THE WATCHER I spy with my little eye someone is going


to die 1st Edition Lisa Sell

https://ebookmeta.com/product/the-watcher-i-spy-with-my-little-
eye-someone-is-going-to-die-1st-edition-lisa-sell/

Handbook of Epigenetics : The New Molecular and Medical


Genetics 3rd Edition Trygve O. Tollefsbol

https://ebookmeta.com/product/handbook-of-epigenetics-the-new-
molecular-and-medical-genetics-3rd-edition-trygve-o-tollefsbol/
Management 12th Edition Ricky W. Griffin

https://ebookmeta.com/product/management-12th-edition-ricky-w-
griffin/
Getting Started
with SQL and
Databases
Managing and Manipulating Data
with SQL

Mark Simon
Getting Started with
SQL and Databases
Managing and Manipulating Data
with SQL

Mark Simon
Getting Started with SQL and Databases: Managing and Manipulating Data
with SQL

Mark Simon
Ivanhoe VIC, VIC, Australia

ISBN-13 (pbk): 978-1-4842-9492-5 ISBN-13 (electronic): 978-1-4842-9493-2


https://doi.org/10.1007/978-1-4842-9493-2
Copyright © 2023 by Mark Simon
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Smriti Srivastava
Development Editor: Laura Berendson
Editorial Assistant: Mark Powers
Cover image designed by eStudioCalamar
Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza,
Suite 4600, New York, NY 10004-1562, USA. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@
springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole
member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc
is a Delaware corporation.
For information on translations, please e-mail [email protected]; for reprint,
paperback, or audio rights, please e-mail [email protected].
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub. For more detailed information, please visit http://www.apress.com/source-code.
Printed on acid-free paper
To Sachiko. Thanks for your patience, forbearance, and trust.
Table of Contents
About the Author�����������������������������������������������������������������������������������������������������xv

About the Technical Reviewer�������������������������������������������������������������������������������xvii


Acknowledgments��������������������������������������������������������������������������������������������������xix

Introduction������������������������������������������������������������������������������������������������������������xxi

Chapter 1: Starting with SQL������������������������������������������������������������������������������������ 1


Basic SELECT Statement��������������������������������������������������������������������������������������������������������������� 2
Case Sensitivity����������������������������������������������������������������������������������������������������������������������� 3
Spacing������������������������������������������������������������������������������������������������������������������������������������ 3
Clause Ordering����������������������������������������������������������������������������������������������������������������������� 4
The Semicolon (;)��������������������������������������������������������������������������������������������������������������������� 4
Selecting Specific Columns���������������������������������������������������������������������������������������������������������� 5
Column Order�������������������������������������������������������������������������������������������������������������������������� 6
Layout�������������������������������������������������������������������������������������������������������������������������������������� 6
Using SELECT *������������������������������������������������������������������������������������������������������������������������ 7
Calculated Columns����������������������������������������������������������������������������������������������������������������� 7
Aliases������������������������������������������������������������������������������������������������������������������������������������� 8
Comments������������������������������������������������������������������������������������������������������������������������������������� 9
Block Comments������������������������������������������������������������������������������������������������������������������� 10
Uses of Comments���������������������������������������������������������������������������������������������������������������� 10
Filtering Rows����������������������������������������������������������������������������������������������������������������������������� 11
Clause Ordering��������������������������������������������������������������������������������������������������������������������� 12
Placing the Semicolon����������������������������������������������������������������������������������������������������������� 13
Ordering the Results������������������������������������������������������������������������������������������������������������������� 13
Clause Order�������������������������������������������������������������������������������������������������������������������������� 14
Distinct Rows������������������������������������������������������������������������������������������������������������������������������ 15

v
Table of Contents

Summary������������������������������������������������������������������������������������������������������������������������������������ 18
Writing SQL���������������������������������������������������������������������������������������������������������������������������� 19
Columns��������������������������������������������������������������������������������������������������������������������������������� 20
Comments����������������������������������������������������������������������������������������������������������������������������� 20
Filtering Data������������������������������������������������������������������������������������������������������������������������� 20
Row Order������������������������������������������������������������������������������������������������������������������������������ 21
Clause Order�������������������������������������������������������������������������������������������������������������������������� 21
Coming Up����������������������������������������������������������������������������������������������������������������������������������� 21

Chapter 2: Database����������������������������������������������������������������������������������������������� 23
About the Sample Database�������������������������������������������������������������������������������������������������������� 23
Database������������������������������������������������������������������������������������������������������������������������������� 24
Tables������������������������������������������������������������������������������������������������������������������������������������ 26
Normalized Tables����������������������������������������������������������������������������������������������������������������� 27
Multiple Values���������������������������������������������������������������������������������������������������������������������� 33
Summary������������������������������������������������������������������������������������������������������������������������������� 37
Coming Up����������������������������������������������������������������������������������������������������������������������������� 39

Chapter 3: Filtering Data���������������������������������������������������������������������������������������� 41


The WHERE Clause���������������������������������������������������������������������������������������������������������������������� 41
Unrelated Assertions������������������������������������������������������������������������������������������������������������� 44
All and Nothing���������������������������������������������������������������������������������������������������������������������� 44
Dealing with NULL����������������������������������������������������������������������������������������������������������������������� 45
Deliberately Ignoring NULLs�������������������������������������������������������������������������������������������������� 46
Finding NULLs������������������������������������������������������������������������������������������������������������������������ 47
Numbers������������������������������������������������������������������������������������������������������������������������������������� 49
Discrete vs. Continuous Values��������������������������������������������������������������������������������������������� 49
Strings����������������������������������������������������������������������������������������������������������������������������������������� 52
Quotes����������������������������������������������������������������������������������������������������������������������������������� 53
More on MySQL/MariaDB Modes������������������������������������������������������������������������������������������� 54
More on Double and Single Quotes��������������������������������������������������������������������������������������� 55
Case Sensitivity��������������������������������������������������������������������������������������������������������������������� 57
Trailing Spaces���������������������������������������������������������������������������������������������������������������������� 58

vi
Table of Contents

Filtering with String Functions���������������������������������������������������������������������������������������������� 59


Handling Quotes and Apostrophes���������������������������������������������������������������������������������������� 61
Before and After Strings�������������������������������������������������������������������������������������������������������� 62
Dates������������������������������������������������������������������������������������������������������������������������������������������� 63
Dates Are Not Strings������������������������������������������������������������������������������������������������������������ 64
Alternative Date Formats������������������������������������������������������������������������������������������������������� 65
Date Comparisons����������������������������������������������������������������������������������������������������������������� 66
Filtering with a Date Calculation������������������������������������������������������������������������������������������� 69
Multiple Assertions��������������������������������������������������������������������������������������������������������������������� 70
AND and OR��������������������������������������������������������������������������������������������������������������������������� 70
The IN Operator��������������������������������������������������������������������������������������������������������������������� 76
Derived Lists�������������������������������������������������������������������������������������������������������������������������� 78
Wildcard Matches����������������������������������������������������������������������������������������������������������������������� 81
Case Sensitivity and Patterns������������������������������������������������������������������������������������������������ 83
Pattern Characters���������������������������������������������������������������������������������������������������������������� 84
Wildcards with Non-strings��������������������������������������������������������������������������������������������������� 87
Extensions to Wildcards�������������������������������������������������������������������������������������������������������� 89
A Simple Pattern Match Example������������������������������������������������������������������������������������������ 91
Summary������������������������������������������������������������������������������������������������������������������������������������ 92
NULL�������������������������������������������������������������������������������������������������������������������������������������� 93
Numbers�������������������������������������������������������������������������������������������������������������������������������� 93
Strings����������������������������������������������������������������������������������������������������������������������������������� 93
Dates������������������������������������������������������������������������������������������������������������������������������������� 94
Multiple Assertions���������������������������������������������������������������������������������������������������������������� 94
The IN Operator��������������������������������������������������������������������������������������������������������������������� 94
Wildcard Matches������������������������������������������������������������������������������������������������������������������ 94
Coming Up����������������������������������������������������������������������������������������������������������������������������������� 95

Chapter 4: Ordering Results����������������������������������������������������������������������������������� 97


Using the ORDER BY Clause�������������������������������������������������������������������������������������������������������� 97
Sort Direction������������������������������������������������������������������������������������������������������������������������� 99
Missing Data (NULL)������������������������������������������������������������������������������������������������������������������ 100

vii
Table of Contents

Data Types��������������������������������������������������������������������������������������������������������������������������������� 102


Case Sensitivity and Collation��������������������������������������������������������������������������������������������� 106
Multiple Columns���������������������������������������������������������������������������������������������������������������������� 107
Interdependence of Columns����������������������������������������������������������������������������������������������� 109
Sort Direction on Multiple Columns������������������������������������������������������������������������������������� 110
Sorting by Calculated Columns������������������������������������������������������������������������������������������������� 112
Limiting the Number of Results������������������������������������������������������������������������������������������������ 115
Paging��������������������������������������������������������������������������������������������������������������������������������� 116
Using LIMIT … OFFSET … (MySQL/MariaDB, SQLite, and PostgreSQL)������������������������������ 117
Using TOP (MSSQL)�������������������������������������������������������������������������������������������������������������� 117
Fetching a Random Row����������������������������������������������������������������������������������������������������������� 118
Nonalphabetical String Order���������������������������������������������������������������������������������������������������� 119
Special Strings�������������������������������������������������������������������������������������������������������������������������� 120
Summary���������������������������������������������������������������������������������������������������������������������������������� 121
Sorting with ORDER BY�������������������������������������������������������������������������������������������������������� 121
Limiting Results������������������������������������������������������������������������������������������������������������������� 122
Sorting Strings��������������������������������������������������������������������������������������������������������������������� 122
Coming Up��������������������������������������������������������������������������������������������������������������������������������� 122

Chapter 5: Calculating Column Values������������������������������������������������������������������ 123


Testing Calculations������������������������������������������������������������������������������������������������������������������ 125
Emulating Variables������������������������������������������������������������������������������������������������������������������ 126
Some Basic Calculations����������������������������������������������������������������������������������������������������������� 127
Basic Number Calculations������������������������������������������������������������������������������������������������� 127
Basic String Calculations����������������������������������������������������������������������������������������������������� 128
Basic Date Calculations������������������������������������������������������������������������������������������������������� 129
Working with NULL�������������������������������������������������������������������������������������������������������������������� 129
Using Aliases����������������������������������������������������������������������������������������������������������������������������� 135
Aliases Without AS��������������������������������������������������������������������������������������������������������������� 136
Awkward Aliases����������������������������������������������������������������������������������������������������������������� 138
Calculating with Numbers��������������������������������������������������������������������������������������������������������� 140

viii
Table of Contents

Arithmetic Operators����������������������������������������������������������������������������������������������������������� 140


Integers������������������������������������������������������������������������������������������������������������������������������� 141
Remainder��������������������������������������������������������������������������������������������������������������������������� 143
Extra Decimals��������������������������������������������������������������������������������������������������������������������� 144
Mathematical Functions������������������������������������������������������������������������������������������������������ 145
Approximation Functions����������������������������������������������������������������������������������������������������� 146
Formatting Functions���������������������������������������������������������������������������������������������������������� 147
Calculating with Dates�������������������������������������������������������������������������������������������������������������� 149
Simple Calculations������������������������������������������������������������������������������������������������������������� 149
Age Calculations������������������������������������������������������������������������������������������������������������������ 151
Extracting Parts of a Date���������������������������������������������������������������������������������������������������� 153
Formatting a Date���������������������������������������������������������������������������������������������������������������� 155
Strings��������������������������������������������������������������������������������������������������������������������������������������� 160
Character Functions������������������������������������������������������������������������������������������������������������ 161
Subqueries�������������������������������������������������������������������������������������������������������������������������������� 165
The CASE Expression���������������������������������������������������������������������������������������������������������������� 169
Casting to Different Data Types������������������������������������������������������������������������������������������������� 173
The cast( ) Function������������������������������������������������������������������������������������������������������������� 174
Casting to a String��������������������������������������������������������������������������������������������������������������� 175
Casting Date Literals����������������������������������������������������������������������������������������������������������� 177
Creating a View������������������������������������������������������������������������������������������������������������������������� 177
Using Views in Microsoft SQL���������������������������������������������������������������������������������������������� 180
Summary���������������������������������������������������������������������������������������������������������������������������������� 181
Data Types��������������������������������������������������������������������������������������������������������������������������� 181
NULLs���������������������������������������������������������������������������������������������������������������������������������� 181
Aliases��������������������������������������������������������������������������������������������������������������������������������� 182
Subqueries�������������������������������������������������������������������������������������������������������������������������� 182
The CASE Expression����������������������������������������������������������������������������������������������������������� 182
Casting a Value�������������������������������������������������������������������������������������������������������������������� 182
Views����������������������������������������������������������������������������������������������������������������������������������� 183
Coming Up��������������������������������������������������������������������������������������������������������������������������������� 183

ix
Table of Contents

Chapter 6: Joining Tables������������������������������������������������������������������������������������� 185


How a Join Works��������������������������������������������������������������������������������������������������������������������� 186
Joining the Tables���������������������������������������������������������������������������������������������������������������� 189
Alternative Syntax��������������������������������������������������������������������������������������������������������������� 189
Selecting the Results����������������������������������������������������������������������������������������������������������� 191
Table Aliases������������������������������������������������������������������������������������������������������������������������ 193
Developing a Price List������������������������������������������������������������������������������������������������������������� 194
Join Types��������������������������������������������������������������������������������������������������������������������������������� 195
The INNER JOIN������������������������������������������������������������������������������������������������������������������� 197
The LEFT OUTER JOIN and RIGHT OUTER JOIN�������������������������������������������������������������������� 197
The “Preferred” Outer Join�������������������������������������������������������������������������������������������������� 199
Some Recommendations on JOINS������������������������������������������������������������������������������������� 200
Finishing the Price List�������������������������������������������������������������������������������������������������������������� 201
Joining Many Tables������������������������������������������������������������������������������������������������������������������ 202
Building a Larger JOIN��������������������������������������������������������������������������������������������������������� 204
Revisiting Some Subqueries������������������������������������������������������������������������������������������������ 209
A More Complex Join���������������������������������������������������������������������������������������������������������������� 211
Using a Self-Join����������������������������������������������������������������������������������������������������������������������� 216
Summary���������������������������������������������������������������������������������������������������������������������������������� 220
Syntax���������������������������������������������������������������������������������������������������������������������������������� 220
Table Aliases������������������������������������������������������������������������������������������������������������������������ 220
The ON Clause��������������������������������������������������������������������������������������������������������������������� 220
Join Types���������������������������������������������������������������������������������������������������������������������������� 221
Coming Up��������������������������������������������������������������������������������������������������������������������������� 221

Chapter 7: Aggregating Data�������������������������������������������������������������������������������� 223


Counting Data��������������������������������������������������������������������������������������������������������������������������� 224
Counting Values������������������������������������������������������������������������������������������������������������������� 224
How Aggregates Work��������������������������������������������������������������������������������������������������������������� 225
Counting Selectively����������������������������������������������������������������������������������������������������������������� 226
Distinct Values�������������������������������������������������������������������������������������������������������������������������� 232

x
Table of Contents

Summarizing Numbers������������������������������������������������������������������������������������������������������������� 233


Bad Examples���������������������������������������������������������������������������������������������������������������������� 235
Scales of Measurement������������������������������������������������������������������������������������������������������� 236
Aggregating Calculated Data���������������������������������������������������������������������������������������������������� 237
Other Aggregate Functions������������������������������������������������������������������������������������������������������� 239
Using Aggregates As Filters������������������������������������������������������������������������������������������������������ 240
Grouping����������������������������������������������������������������������������������������������������������������������������������� 243
Using the GROUP BY Clause������������������������������������������������������������������������������������������������ 245
GROUP BY vs. DISTINCT������������������������������������������������������������������������������������������������������� 250
Grouping with Multiple Tables��������������������������������������������������������������������������������������������������� 251
Redundant Groups�������������������������������������������������������������������������������������������������������������������� 254
Preparing Data for Aggregating������������������������������������������������������������������������������������������������ 256
Using CASE in a CTE������������������������������������������������������������������������������������������������������������ 259
Using a Join in the CTE�������������������������������������������������������������������������������������������������������� 260
Summarizing Strings����������������������������������������������������������������������������������������������������������� 262
Filtering Grouped Results with HAVING������������������������������������������������������������������������������������� 264
Using Results in a CTE��������������������������������������������������������������������������������������������������������� 268
Finding Duplicates��������������������������������������������������������������������������������������������������������������� 269
Using Aggregates on Aggregates���������������������������������������������������������������������������������������� 272
Summary���������������������������������������������������������������������������������������������������������������������������������� 275
Coming Up��������������������������������������������������������������������������������������������������������������������������� 276

Chapter 8: Working with Tables���������������������������������������������������������������������������� 277


How Tables Are Created������������������������������������������������������������������������������������������������������������ 278
Creating a Table������������������������������������������������������������������������������������������������������������������� 279
Column Names�������������������������������������������������������������������������������������������������������������������� 280
Data Type����������������������������������������������������������������������������������������������������������������������������� 281
Primary Keys����������������������������������������������������������������������������������������������������������������������� 282
Constraints�������������������������������������������������������������������������������������������������������������������������������� 284
NOT NULL����������������������������������������������������������������������������������������������������������������������������� 285
UNIQUE�������������������������������������������������������������������������������������������������������������������������������� 286
DEFAULT������������������������������������������������������������������������������������������������������������������������������� 286

xi
Table of Contents

CHECK���������������������������������������������������������������������������������������������������������������������������������� 287
Foreign Keys������������������������������������������������������������������������������������������������������������������������ 287
Indexes�������������������������������������������������������������������������������������������������������������������������������� 289
Adding Rows to a Table������������������������������������������������������������������������������������������������������������� 290
Deleting Rows from a Table������������������������������������������������������������������������������������������������������ 292
Adding More Rows�������������������������������������������������������������������������������������������������������������������� 294
Updating Rows�������������������������������������������������������������������������������������������������������������������������� 295
Altering the Table���������������������������������������������������������������������������������������������������������������������� 297
DML in Real Life������������������������������������������������������������������������������������������������������������������������ 299
Security������������������������������������������������������������������������������������������������������������������������������� 299
Front-End Software������������������������������������������������������������������������������������������������������������� 300
Summary���������������������������������������������������������������������������������������������������������������������������������� 301
Data Types��������������������������������������������������������������������������������������������������������������������������� 301
Constraints�������������������������������������������������������������������������������������������������������������������������� 301
Foreign Keys������������������������������������������������������������������������������������������������������������������������ 302
Indexes�������������������������������������������������������������������������������������������������������������������������������� 302
Manipulating Data��������������������������������������������������������������������������������������������������������������� 302

Chapter 9: Set Operations������������������������������������������������������������������������������������� 303


Unions��������������������������������������������������������������������������������������������������������������������������������������� 303
Selective Unions������������������������������������������������������������������������������������������������������������������ 307
SELECT Clauses Must Be Compatible���������������������������������������������������������������������������������� 309
Only Column Names from the First SELECT Statement Are Used���������������������������������������� 311
Sorting Results�������������������������������������������������������������������������������������������������������������������� 312
Intersections����������������������������������������������������������������������������������������������������������������������������� 314
Differences�������������������������������������������������������������������������������������������������������������������������������� 317
Some Tricks with Set Operations���������������������������������������������������������������������������������������������� 321
Comparing Results�������������������������������������������������������������������������������������������������������������� 321
Virtual Tables����������������������������������������������������������������������������������������������������������������������� 323
Mixing Aggregates��������������������������������������������������������������������������������������������������������������� 326
Summary���������������������������������������������������������������������������������������������������������������������������������� 330

xii
Table of Contents

Appendix 1: Differences Between SQL Dialects���������������������������������������������������� 333

Appendix 2: A Crash Course in PDO���������������������������������������������������������������������� 341

Appendix 3: Additional Notes������������������������������������������������������������������������������� 357

Index��������������������������������������������������������������������������������������������������������������������� 369

xiii
About the Author
Mark Simon has been involved in training and education
since the beginning of his career. He started as a teacher
of mathematics but soon moved into IT consultancy and
training because computers are much easier to work
with than high school students. He has worked with and
trained in several programming and coding languages and
currently focuses mainly on web development and database
languages. When not involved in work, you will generally
find him listening to or playing music, reading, or just
wandering about.

xv
About the Technical Reviewer
Atul Tyagi is a database developer who has worked
extensively in the field of data analytics for over eight years.
He has worked with various industries, including general
insurance and banking domains, and has contributed
significantly to several projects involving reporting,
datamarts, automation, data model development, and
project migration.
Atul is skilled in SQL, SAS, Python, and ETL tools such as
Informatica, SAS DI, Datastage, and SAS Visual Analytics. His
expertise in these areas has helped numerous organizations
effectively manage and analyze their data, leading to
improved decision-making and business outcomes. Atul has worked with leading
companies such as Accenture Solutions, Wipro Pvt Ltd, Acxiom Technologies, and EXL
Services.
Apart from his professional work, Atul is also passionate about sharing his
knowledge, cloud platforms, and data analytics. In his free time, he enjoys reading,
traveling, and exploring new cuisines.

xvii
Acknowledgments
The sample data includes information about classical paintings and their artists. This
information is an extract of the hard work that went into the WebMuseum ­
(www.ibiblio.org/wm/).

xix
Introduction
In the distant past, data was managed by computers in all sorts of ways, and there was
no one way to do this. There still isn’t, which isn’t a bad thing, because not all data can
be handled the same way. There is, however, a large body of data which can be handled
in a common way, and the early 1970s saw the development of a set of mathematical
principles in the relational model.
Starting in a lab at IBM, software was developed to handle relational data, and a
language was developed to manage it. The language eventually became the Structured
Query Language. In the early days, different vendors had their own idea of how the
language should work, but this was eventually rolled into a standard. The standard has
grown over the decades, which means that the language is also growing.
Not all database vendors follow the standard to the same degree. Some standards
were late in coming, and database vendors filled in some gaps with their imagination.
Other standards are harder to implement than it looks, and some vendors are “still
working on it.” And sometimes, the vendor just wants to do something differently.
This book looks at using SQL for basic tasks. Mostly that means fetching data and
possibly processing it. There are many database packages available, all with their own
quirks, and all with their own variations of the SQL standard. This book covers a few of
the most popular packages and makes a point of showing not only what the standard
says but also how the individual packages do things.
We’ll also look at how databases are designed, but not because we’ll be designing
any. One of the big mysteries to any new SQL user is why do we do things this way or
that, and why is the data the way it is. By understanding some design principles, you’ll be
in a better position to know why.
In this book, we make no assumptions about your prior knowledge, except that you
have an idea what a table is. You have probably had some experience with spreadsheets
as well.
As to what you might do afterward, that depends. It might be your job to fetch data to
feed it into some sort of analysis or reporting software. You might do all of your analysis
in SQL directly, or you might write queries in a specialized database application. Or you
might be a web developer looking to manage a blog or an ecommerce site.

xxi
Introduction

The Sample Data


We’ll talk more about the sample data later in the book, but the book is based on a
sample database. You can sit in an armchair and read the book as it is if you like, but
you’ll probably want to work through the exercises.
To work through the exercises, you’ll need the following:

• A database server and a suitable database client.


• Permissions to do anything you like on the database. If you’ve
installed the software locally, you probably have all the permissions
you need, but if you’re doing this on somebody else’s system, you
need to check.

• The script which produces the sample database.

You can get a fresh copy of the script from


https://sample-db.net
and choose your options.
If that’s too much like hard work, you can use the following links to download
a script:

• PostgreSQL: https://sample-db.net/?dbmss[]=pgsql-10&db=prin
ts&br=crlf&refresh&download

• SQLite: https://sample-db.net?dbmss[]=sqlite-script&db=print
s&br=crlf&refresh&download

• MySQL/MariaDB: https://sample-db.net/?dbmss[]=mysql-ansi&d
b=prints&br=crlf&refresh&download

• Microsoft SQL: https://sample-db.net/?dbmss[]=mssql-16&db=pr


ints&br=crlf&refresh&download

• Oracle: https://sample-db.net/?dbmss[]=oracle-12&db=prints&b
r=crlf&refresh&download

These links are for current versions of the software. If you want older versions, visit
the preceding site.

xxii
Introduction

Notes
Throughout the book, you’ll come across a few terms and a few expectations:

• MySQL and MariaDB are essentially the same; MariaDB is an


increasingly popular spin-off. With very few exceptions (as noted),
the code is interchangeable.

• The book makes a great deal of using MySQL/MariaDB in so-called


ANSI mode. This is easily done, as you’ll see in the book, and makes
working with standard SQL much easier.

• The Microsoft product will sometimes be referred to as Microsoft SQL


Server and sometimes as MSSQL for short. If you’re looking for T-SQL
(Transact SQL), it’s also the same thing.

xxiii
CHAPTER 1

Starting with SQL


If you’re new to database in general, and to SQL in particular, it can be a little daunting at first.
In this chapter, we’ll have a taste of SQL by looking at how we fetch data from a simple table.
In principle, you can choose to manage your data any way you want, and some
people do just that in spreadsheets or even in word processors. For serious data, that’s
not organized enough, so we rely on something more structured.
There is no one way to organize data, and not all data can be organized in the same
way. However, for much of the time, there is a popular way of organizing the data for
which the SQL language has been developed. Software that manages a database is often
referred to as Database Management System that’s quite a lot to say every time, so we’ll
refer to it as DBMS.
An SQL database is a collection of one or more tables. Each table is a collection of
one type of data. Some of the tables in the sample database are

• Customers

• Paintings

• Artists
We will have a closer look at the structure of the database later, but the important
thing at this point is that the data is not mixed up. For example, the customers table has
all of the information about customers, and nothing else.
Each table contains rows and columns. A row is one instance of the data. For
example, each row in the customers table represents one customer. A column has
a detail of the row. For example, the customers table has separate columns for the
customer’s email address, phone number, and so on.
Of course, there’s more to a database than that, and Chapter 2 will focus on these
ideas more thoroughly.
In this chapter, we will explore the contents of one table, the customers table, using
the SELECT statement, which is the basic command to fetch data. Along the way, you’ll
see how the results can be filtered, recalculated, and sorted.
1
© Mark Simon 2023
M. Simon, Getting Started with SQL and Databases, https://doi.org/10.1007/978-1-4842-9493-2_1
Chapter 1 Starting with SQL

Everything we cover here will be covered in more detail in later chapters, so you can
take a fairly relaxed approach to what we’re doing in this chapter.

If you run the following sample code, your results may not be exactly the same.
This is because the sample data, which is randomized, may not be the same as
the data used in the book. You may also find differences in the way DBMSs present
unsorted data.

Basic SELECT Statement


To read data from a table, you use SELECT:

SELECT * FROM customers;

You’ll get a result similar to Table 1-1.

Table 1-1. Results


id familyname givenname email registered

474 Free Judy [email protected] … 2022-06-12


186 Gunn Ray [email protected] … 2021-11-15
144 King Ray [email protected] … 2021-10-18
179 Inkling Ivan [email protected] … 2021-11-08
475 Blood Drew [email protected] … 2022-06-13
523 Sights Seymour [email protected] … 2022-07-11

~ 304 rows ~

This is called a SELECT statement and will fetch all the rows from the
customers table.
Statements usually comprise two or more clauses. In this case, they are the SELECT
clause and the FROM clause.

2
Chapter 1 Starting with SQL

Note
• SELECT doesn’t mean display, although the database client doesn’t know what
else to do with the results. Other software might simply fetch the data to be
further processed.

• The * doesn’t mean all rows. It is a shorthand for all columns of the table.

• Most of what we’ll be doing will involve a SELECT statement.

Case Sensitivity
The SQL language is case insensitive, meaning that you can type the statement in upper
or lower case:

select * from customers;

• It is traditional to use UPPER CASE for keywords (SELECT and FROM)


to highlight them, but it’s not so important when you have color
highlighting.
• It is also traditional that table and column names be entered in lower
case, but most DBMSs don’t really care.

This book will use UPPER CASE for keywords, but you don’t have to.

Spacing
Although a simple statement might easily fit on one line, you can add as many line
breaks and extra spaces or tabs as you like:

SELECT
    *
FROM customers;

The most important thing is to keep your code readable and to use spacing to help in
managing the statement.
As the book progresses, there will be more recommendations on layout. However,
these are recommendations only, as SQL will work just as well with minimal spacing.
3
Chapter 1 Starting with SQL

Clause Ordering
The original proposed name for SQL was SEQUEL, Structured English Query Language.
The idea was that the syntax would resemble the English language.
This has led to a syntax quirk. For example, if you say

Get the Milk


From the Refrigerator

you first go to the refrigerator and then get the milk. That is, From is processed
before Get.
Similarly, in the SELECT statement, the FROM clause is processed before the
SELECT clause.
However, you cannot write the statement that way:

• You must write SELECT … FROM … ;.

• It means FROM … SELECT … ;.

Later, you will see additional clauses and where they fit in.
In this simple example, the fact of the clause order is not important. However, later,
the clause order will explain why some more complex examples don’t work the way you
would expect.

The Semicolon (;)


The SQL standard requires a semicolon ; at the end of each statement. You can break
up the statement over many lines, but the semicolon then marks the eventual end of the
statement.

• Most DBMSs will allow you to ignore the semicolon if there is a single
statement. However, you will at least need a semicolon between
multiple statements.

• Microsoft SQL will also allow you to omit semicolons for multiple
statements, unless you have them on one line, but even Microsoft
doesn’t think that’s a good idea (see https://docs.microsoft.com/
en-us/sql/t-sql/language-elements/transact-sql-syntax-
conventions-transact-sql#transact-sql-syntax-conventions-
transact-sql).

4
Chapter 1 Starting with SQL

We recommend that you always use semicolons, even for a single statement or for
Microsoft SQL. This way, you make sure that your code is less prone to errors.

Selecting Specific Columns


The star character * is a shorthand for selecting all columns from the table. You can
specify one or more columns instead:

SELECT id, givenname, familyname


FROM customers;

This gives you Table 1-2.

Table 1-2. Results


id givenname familyname

474 Judy Free


186 Ray Gunn
144 Ray King
179 Ivan Inkling
475 Drew Blood
523 Seymour Sights

~ 304 rows ~

This selects three columns; it still selects all rows.


The column list is separated by commas:

• The columns do not have to be in the original order.

• You can skip any columns you like.

• Note that in this case the givenname and familyname order is reversed
and that the email column is omitted.
• The space after the comma is optional: include it if you think it makes
it more readable.

5
Chapter 1 Starting with SQL

• The comma is a separator: don’t put a column after the last column,
as SQL will expect another column.

This is a common mistake:

SELECT id, givenname, familyname, -- extra comma


FROM customers;

It’s a good idea to always specify the columns, even if it’s all of them.

Column Order
The default column order, which you see with SELECT *, is defined when the table is
created. You may not be able to change it, even if you have permission.
In SQL, there is no correct column order, and there is no performance difference if
you select in a different order. That is, there is no preferred column order, so you choose
the order which best suits your needs, either for presentation or to feed into another
application.

Layout
With a growing column list, it makes sense to lay the columns out more creatively:

SELECT
    id,
    givenname, familyname
FROM customers;

As mentioned before, the actual spacing is insignificant, so the preceding example


uses spacing to make the statement more readable.

• The column list is vertical rather than inline.

• The column list is indented from the SELECT command to show that
they are part of the same clause.
• givenname and familyname are on the same line to show that
conceptually they are related to each other.

You will find layout easier to maintain if you remember to use the tab key.

6
Chapter 1 Starting with SQL

Also, as mentioned before, you can use any spacing you like; just make sure that the
statement is as readable as possible.

Using SELECT *
It is considered bad practice to use SELECT * in real life, even if you really want all of the
columns; always specify all of the columns. This is because

• You get no control over the column order of the results.

• A change in the underlying table structure might lead to different


results next time.

However, in this book, you will see SELECT * used very often:

• SELECT * is a good way of exploring a table.

• Many examples will focus on new clauses, so the actual columns


selected are not relevant.

Just remember that when using SQL in earnest, you should always list the actual
column names.

Calculated Columns
The selected columns don’t have to be the original columns. They can be derived from
one or more columns. Among other things, this means that the table never needs to keep
variations on a value since it can always be recalculated when the time comes.
For example:

SELECT
    id, givenname, familyname,
    height,         --  height in centimetres
    height/2.54     --  height in inches
FROM customers;

Table 1-3 shows the results.

7
Chapter 1 Starting with SQL

Table 1-3. Results


474 Judy Free

186 Ray Gunn 163.8 64.488…


144 Ray King 176.8 69.606…
179 Ivan Inkling 170.3 67.047…
475 Drew Blood 171.0 67.323…
523 Seymour Sights 167.3 65.866…

~ 304 rows ~

In the customers table, height is measured in centimeters. For those who prefer a
legacy measurement, you can convert to inches by dividing by 2.54.1
It would have been a mistake to design a table with both centimeters and inches.
Tables should never have a column which is basically the same as another in disguise. As
you see, you can always recalculate the other value.

Aliases
When experimenting with a SELECT statement, you can leave calculations as they are, but
you will notice that the result will have a missing or dummy name.
When taking your SELECT statement seriously, you will need to give calculated
columns a distinct name:

SELECT
    id, givenname, familyname,
    height as centimetres,
    height/2.54 as inches
FROM customers;

Now you have the results in Table 1-4.

1
Apparently, only three countries haven’t yet officially adopted the metric system: Myanmar,
Liberia, and the United States. However, the United States has long adopted the metric system as
the basis for customary units. In this case, the old inch is now fixed at exactly 2.54 cm.

8
Chapter 1 Starting with SQL

Table 1-4. Results


id givenname familyname centimetres inches

474 Judy Free [NULL] [NULL]


186 Ray Gunn 163.8 64.488…
144 Ray King 176.8 69.606…
179 Ivan Inkling 170.3 67.047…
475 Drew Blood 171.0 67.323…
523 Seymour Sights 167.3 65.866…

~ 304 rows ~

As you see, you can also alias uncalculated columns if you feel the need to make the
point clearer.
You will see more on calculated columns and aliases later.

Comments
In an elaborate script, it is useful to include comments about what is going on. A
comment is any text which will be ignored by SQL, but is meant for humans to read.
You’ve already seen a few comments in the previous examples. The standard
comment is text following the -- characters, until the end of the line:

SELECT
    id, givenname, familyname,
    height/2.54 as inches   -- 1in = 2.54cm
FROM customers;

The preceding comment is to explain why we are dividing by 2.54.


Strictly speaking, the -- must be followed by a space. However, most, but not all,
DBMSs will allow a tab instead of a space, and some, but not all, DBMSs don’t require
spacing character:

-- This is a standard comment (space)


--  This uses a tab, and will probably work, but not necessarily (tab)
--This may also work
9
Chapter 1 Starting with SQL

You will find out soon enough which variations work for your DBMS. Usually,
comments are highlighted in a different color.

Block Comments
Most DBMSs also support an unofficial block comment:

/* block comment */

This style is also known as the C-style comment because of its use in the C
programming language.
The block comment begins with the /* combination and ends with the reverse */
combination. It can span multiple lines or take up just part of a line.

/*  This is an introductory SELECT statement


    The rest of the book will go into more detail */
    SELECT
        id,
        /* name: */ givenname, familyname
    FROM customers;

Normally, you should avoid non-standard SQL features, since you never know what
the future holds. However, this one is so widely supported that you can regard it as
simply a missing feature supplied unofficially.

Uses of Comments
Since SQL completely ignores comment text, you can write anything you like, even if it
amounts to gibberish. However, the following are common uses of comments:

• Explain something which is not obvious in code

• Act as section headers in complex scripts

• Temporarily disable some code


Here is an example with different uses of comments:

/*  SQL Sampler

10
Chapter 1 Starting with SQL

    ================================================
    This is an introductory SELECT statement
    The rest of the book will go into more detail
    ================================================ */
    SELECT
        id,
        --  email,
        givenname, familyname,
        height/2.54 as inches   -- 2.54 cm = 1 inch
    FROM customers;

In the preceding example, the email column is disabled, the inches column is
explained, and the whole script is preceded by a header comment block. The actual
query is also indented for good measure.
Normally, if you want to disable code, you simply delete it. Using a comment
instead is called commenting the code out. The reasons why you would comment code
out include

• Testing or troubleshooting

• Leaving it there as an option, subject to further consultation

• Using it as an alternative to other code

As regards explanatory code, don’t overcomment. Only explain what isn’t obvious.
Saying too much is like the boy who cried wolf. As a rule, others will simply tune out.

Filtering Rows
Often, you don’t want all rows of a table, but only some of them. The WHERE clause is used
to decide which rows to select:

SELECT
    id,
    givenname,familyname,
    height/2.54 AS inches
FROM customers
WHERE state='NSW';

11
Chapter 1 Starting with SQL

This time, you get what’s in Table 1-5.

Table 1-5. Results


id givenname familyname inches

474 Judy Free [NULL]


144 Ray King 69.606…
341 Val Idate 69.724…
351 Dick Tate 66.063…
429 Tom Morrow 61.772…
234 Nat Ering 67.638…

~ 67 rows ~

The expression state='NSW' is called an assertion and is either true or false. The
WHERE clause selects only those rows where the assertion is true.
Note the single quotes ' … ' around the NSW. In SQL, text values are called strings
and are enclosed in single quotes. Don’t use double quotes " … " because most DBMSs
will interpret double quotes differently. Also, note that the string is in UPPER CASE,
which matches the data in the customers table. In some DBMSs, you can also use lower
case, but not in others.
You will learn more about strings later in the book.

Clause Ordering
The WHERE clause is evaluated after FROM, but before SELECT:

SELECT …
FROM …
--  SELECT processed here!
WHERE … ;

In English, this reads as


1. Start with the table.

2. Filter some rows.

12
Chapter 1 Starting with SQL

3. Select some columns.

Remember, however, that you must write the SQL in the preceding order.

Placing the Semicolon


When developing your code, it is easy to make the following mistake:

SELECT *
FROM customers;
WHERE state='NSW'   --  oops

This is because you have correctly ended the previous version with a semicolon and
simply added a new clause after it. While you are developing your code, it may be helpful
to put the semicolon on a separate line:

SELECT *
FROM customers
WHERE state='NSW'
;

This makes it easier to add the additional clauses as you go. You can always tidy up
the semicolon when you have finished everything.

Ordering the Results


Mathematically speaking, a table is a set of rows. Among other things, this means that
row order is insignificant.
Some DBMSs will output the results in the same order they were added. Some
DBMSs will output them in a seemingly random order, depending on how the data is
managed internally.
The SQL standard makes a point of not telling a DBMS how to do its job, and the only
guarantee is that row order is not guaranteed, that is, unless you force the issue.
The ORDER BY clause puts the results in a specified order:

SELECT
    id,
    givenname, familyname,

13
Chapter 1 Starting with SQL

    height/2.54 as inches
FROM customers
WHERE state='NSW'
ORDER BY familyname, givenname;

The results will appear in Table 1-6.

Table 1-6. Results


id givenname familyname inches

44 Helen Back 67.913…


162 Ginger Beer 70.039…
99 Minnie Bus 65.315…
270 Mary Christmas 65.118…
487 Horace Cope 68.622…
419 Barbie Cue 62.520…

~ 67 rows ~

In this example, you order the results by familyname and, in the event of a tie, by the
givenname.
You can order by one or more columns, in ascending or descending order.
Strictly speaking, the result is no longer a set, as a set is unordered. In some cases,
you won’t be able to do any more processing once the ORDER BY clause is used.
You will learn more about the ORDER BY clause later.

Clause Order
The ORDER BY is both written and evaluated last:

SELECT …
FROM …
WHERE …
--  SELECT processed here
ORDER BY … ;

14
Chapter 1 Starting with SQL

In English, this reads as

1. Start with the table.

2. Filter some rows.

3. Select some columns.

4. Finally, sort the results.

Remember, however, that you must still write the SQL in the preceding order.

Distinct Rows
Sometimes, you will need to interpret what somebody asks for. For example, if you want
a list of email addresses, the following would do the job:

SELECT email FROM customers;

The results in Table 1-7 are reasonable enough.

Table 1-7. Results


email

[email protected]

[email protected]

[email protected]

[email protected]

[email protected]

[email protected]

~ 304 rows ~

On the other hand, if you want a list of states, the following is probably not what
you want:

SELECT state FROM customers;

The results in Table 1-8 are not so reasonable.


15
Chapter 1 Starting with SQL

Table 1-8. Results


state

NSW

VIC

NSW

WA

QLD

VIC

NSW

NSW

QLD

TAS
~ 304 rows ~

You will, of course, get a list of all of the state values (as well as a few NULLs which
represent missing values). However, you probably don’t want the duplicates. If you want
one of each, you will need to use DISTINCT:

SELECT DISTINCT state FROM customers;   --  one of each

The results in Table 1-9 are probably more reasonable.

16
Chapter 1 Starting with SQL

Table 1-9. Results


state

WA

[NULL]

TAS

VIC

NSW

NT

QLD

SA
~ 8 rows ~

Using DISTINCT treats each value not as an individual value but as a group. You can
say that you now have the state groups.
Note that one of the groups is NULL, meaning that you also have some missing states.
The DISTINCT operator acts only on what is in the SELECT clause. If you add the town
column as well:

SELECT DISTINCT state, town FROM customers; --  one of each

You’ll get results like Table 1-10.

17
Chapter 1 Starting with SQL

Table 1-10. Results


state town

SA Windsor
[NULL] [NULL]
VIC Belmont
SA Alberton
NSW Hamilton
WA Wattle Grove
VIC Stirling
VIC Gordon
TAS Beaconsfield
SA Richmond

~ 79 rows ~

Here, you will get distinct combinations of state and town. In the result set, it’s not
the state which is distinct nor the town—it’s the combination. We can say that we now
have state/town groups.
Again, you will see the NULL as a separate group. In this set of data, there is no state
without a town and vice versa, which is why there’s only one group with NULLs.

Summary
Here is a sample of the SQL we have been developing:

/*  SQL Sampler
    ================================================
    This is an introductory SELECT statement
    The rest of the book will go into more detail
    ================================================ */

18
Chapter 1 Starting with SQL

    SELECT
        id,
        --  email,
        givenname, familyname,
        height/2.54 as inches   -- 2.54 cm = 1 inch
    FROM customers
    WHERE state='NSW'
    ORDER BY familyname,givenname;

This illustrates the main parts of an SQL SELECT statement, as well as the use of
comments and layout.
The basic SELECT statement is

SELECT columns
FROM table;

Note that SELECT is evaluated after FROM.

Writing SQL
SQL is a simple language which has a few rules and a few recommendations for
readability.

• SQL is relaxed about using extra spacing. You should use as much
spacing as required to make your SQL more readable.

• Each SQL statement ends with a semicolon (;).

• The SQL language is case insensitive, as are the column names. Table
names may be case sensitive, depending on the operating system.

Remember, some parts of the language are flexible, but there is still a strict syntax to
be followed.

19
Chapter 1 Starting with SQL

Columns
The SELECT statement will select one or more columns of data from a table.

• You can select columns in any order.

• The SELECT * expression is used to select all columns.

• Columns may be calculated.

• Calculated columns should be named with an alias; noncalculated


columns can also be aliased.

Remember that in well-written SQL statements, you shouldn’t use SELECT * for your
columns. However, in this book we’ll use it to focus on the new clauses.

Comments
A comment is additional text for the human reader which is ignored by SQL.

• SQL has a standard single-line comment: -- etc

• Most DBMSs also support the non-standard block comment: /* … */

• Comments can be used to explain something or to act as section


headers. They can also be used to disable some code as you might
when troubleshooting or testing.

Remember to use comments sparingly, only when they actually tell the reader what
they need to know.

Filtering Data
Rows can be filtered with a WHERE clause.

• Sometimes, the filter results in no rows at all; this is not an error.

• When filtering strings, the values may or may not be case sensitive,
depending on the DBMS and the actual database.
The WHERE clause can be used to return a single row, which is known to be unique, or
a subset of rows. Occasionally, you’ll get nothing which matches the criterion.

20
Chapter 1 Starting with SQL

Row Order
SQL tables are unordered collections of rows.

• Row order is insignificant and may be unexpected.

• You can sort the results using an ORDER BY clause.

Technically, once you use ORDER BY, the result is not a true set. Often, that doesn’t
matter, but some operations can’t be performed after ORDER BY.

Clause Order
The four main clauses so far are written in this order:

SELECT columns
FROM table
WHERE conditions
--  SELECT is evaluated here
ORDER BY columns

The SELECT clause is the last to be evaluated before the ORDER BY clause.

Coming Up
This has been a simple sampler of how SQL works. In the following chapters, you’ll see
more details on the individual clauses as well as how to work with multiple tables, how
to calculate and summarize data, and how to make simple changes to the data.
Before that, however, we’ll have a look at how SQL databases are structured.

21
CHAPTER 2

Database
In Chapter 1, you had a taste of using SQL to extract data from a database. We were
a little bit in the dark there, since we weren’t fully informed about what was in the
database. Sadly, that’s often the case in real life, but here we’ll get a better look at the
databases itself.
In this chapter, we’ll look at what’s going on. This will be on two fronts:
• You’ll learn a little about the theory and practice of database design:
Why is it the way it is?
• You’ll also learn about the details of the sample database itself: What
specifically is in this database?

The theory part won’t be too heavy. You’ll learn about tables, which are the basic
structure of all data, and the rules of so-called normal tables: how data is structured to
be as simple and reliable as possible. You’ll also look at how we manage working with
multiple values.
The sample database follows a typical design, even if it’s quite a small database. It
will have enough to make it worth searching and analyzing. More to the point, it will
have a bit of everything we need to explore.

About the Sample Database


For the sample database, we will imagine an online store selling printed copies of
famous artworks.
To manage the store, we will need (at least) the following tables:
• A table of customers which will hold the customer details.

• A table of paintings with some details of the paintings available. This


is not a stock table, since the paintings will be printed on demand.

23
© Mark Simon 2023
M. Simon, Getting Started with SQL and Databases, https://doi.org/10.1007/978-1-4842-9493-2_2
Chapter 2 Database

• One detail of the paintings is the artist. We do not store the artist’s
details in the paintings table. Instead, there is a separate table, and
the painting has a reference to the artist.

• A table of artists, referred to in the preceding paintings table.

• Two tables to manage the sales: a sales table to manage a customer


purchase and a saleitems table to manage the individual items
in a sale.

Figure 2-1 will give you a good idea of how the database is structured.

Figure 2-1. The Sample Database

In this chapter, we’ll have a look at some of the ideas that go into designing a
database, and we will also get a closer look at the sample database for the exercises.

Database
SQL databases are based on the theory of Relational Database. In turn, this is based on
some important mathematical concepts, including Sets and Logic.
An important principle of Relational Database is this:
There is one unique place for each item of data.
In particular, this means

• Data is never repeated.

24
Chapter 2 Database

• There is never any ambiguity as to where to place or find an item


of data.

In theory, SQL databases are a limited version of “pure” Relational Databases. For
this reason, we will refer to them more specifically as SQL databases.

Database Terminology
We’ll try not to get too pedantic on terminology, but some terms are important to make
things clear.
A database is a collection of data. In theory, this data can be managed any way you
like, such as in word processing documents or record cards or on notches on pieces of
wood. Here, of course, we’re talking about managing the data on a computer system.
A DBMS is the software that manages the data. There are, of course, many DBMSs
available, and this book accommodates some of the more popular ones.
SQL, or Structured Query Language (officially, it is pronounced as it is spelled), is the
language used to communicate with the database. There is an official ISO standard, but
all DBMSs have variations on this standard.
Some users try to pronounce it as SeQueL, which was earlier proposed as its official
name. Due to a naming conflict with other software, in the end it was just called SQL. If
you like, you can also pronounce it as SQuaLl, SQueaL, SQueLch, or SQuaLlid.

Data vs. Value


What is your given name? We will refer to your given name as an item of data. The
answer to the question, however, will be referred to as its value.
Think of data as a placeholder (such as a box on a form) and a value as the contents
of the placeholder.
To say that data is never repeated means that there is only one placeholder for your
name: there are no duplicates.
On the other hand, values may be duplicated. There is nothing stopping another
person from having the same name as you. However, that would be regarded as a
coincidence in its technical, nonmysterious sense.
More importantly, changing the value of your name places no obligation on the
other person to do the same. Values are independent of each other.

25
Chapter 2 Database

Tables
An SQL database is a collection of distinct tables. Each table describes a type of data,
such as a customer or a painting.
For example:

SELECT * FROM customers;


SELECT * FROM paintings;

When you run the preceding code, you will find that the customer table has nothing
to say about paintings, and vice versa.

Table Terminology
SQL uses the language of tables, and tables have rows and columns.

• A table is a collection, such as a collection of customers.

• A row is an instance or member of that collection, such as one of the


customers.

• A column is a detail of the members, such as the date of birth of the


customer.

You will sometimes see some other words used to describe the data, but they are not
the language of SQL. Table 2-1 shows some of the alternative terminology used for some
of the concepts.

Table 2-1. Alternative Names


Relational Database SQL Other

Collection Relation Table File


Instance Tuple Row Record
Detail Attribute Column Field

In particular, avoid using the terms Record and Field in the company of other SQL
developers, as they will tend to look down their noses at you. On the other hand, the word
Field in particular does sometimes appear in official documentation, so it’s not quite so bad.
In this book, we will use the standard SQL terminology. You will sometimes see the
word record used in its original sense, that of saving information.
26
Chapter 2 Database

Normalized Tables
In principle, you could organize your data table any way you want, but if you want your
data to be as maintainable as possible, it needs to follow some rules.
The following rules are not there just to make the game more interesting. The rules
will result in tables where data is in its simplest, most dependable form. Mathematicians
refer to this form as its normal form.
Overall, the goal of normalization is to ensure that every piece of data has exactly one
place. There should be no repetitions and no ambiguity.
As you’ll see, this often results in creating additional tables, so the data you’re
looking for may be spread all over the place. That can be inconvenient. Later, when we
look at joining tables, we’ll see how we can manage this inconvenience.
Database theory defines a number of levels of normalization, but most of the
principles are covered in the following text.
In real life, you’ll find that database developers often relax some of these principles
to avoid spreading the data in too many places, making even the simplest query a
challenge. However, that always risks making the data less reliable.

Data Is Atomic
If you select

SELECT
    id,
    givenname, familyname
FROM customers;

you will note that the given name and family name are in separate columns. This
makes it easier to sort the data and to search for it.
Data should be in its smallest practical unit. If it is, we say that the data is atomic,
from a Greek word meaning that it can’t get any smaller.
Note the word “practical” earlier. You could try the same thing with the email
address:

SELECT
    id,
    email
FROM customers;

27
Another Random Scribd Document
with Unrelated Content
neither Hercules nor Osiris are solar myths, save in one of
their seven aspects.
1794. The Hyperboreans, now regarded as mythical, are
described (Herod., iv. 33-35; Pausanius, i. 31, 32; v. 7, 8; x.
5, 7, 8) as the beloved priests and servants of the Gods,
and of Apollo chiefly.
1795. The Cyclopes are not the only “one-eyed” representatives in
tradition. The Arimaspes were a Scythian people, and were
also credited with but one eye. (Géographie Ancienne, ii.
321.) It is they whom Apollo destroyed with his shafts.
1796. Ulysses was wrecked on the isle of Ææa, where Circe
changed all his companions into pigs for their
voluptuousness; and after that he was thrown into Ogygia,
the island of Calypso, where for some seven years he lived
with the nymph in illicit connection. Now Calypso was a
daughter of Atlas (Odys., xii.), and all the traditional ancient
versions, when speaking of the Isle of Ogygia, say that it
was very distant from Greece, and right in the middle of the
Ocean; thus identifying it with Atlantis.
1797. Hygin., Astron. Poétique, ii. 15.
1798. Nineteenth Century, July, 1887.
1799. Diod. Sic., ii. 307.
1800. To make a difference between Lemuria and Atlantis, the
ancient writers referred to the latter as the Northern or
Hyperborean Atlantis, and to the former as the Southern.
Thus Apollodorus says (Mythology, Book ii): “The golden
apples carried away by Hercules are not, as some think, in
Lybia; they are in the Hyperborean Atlantis.” The Greeks
naturalized all the Gods they borrowed and made Hellenes
of them, and the moderns helped them. Thus also the
Mythologists have tried to make of Eridanus the river Po, in
Italy. In the myth of Phaeton it is said that at his death his
sisters dropped hot tears which fell into Eridanus and were
changed into amber! Now amber is found only in the
northern seas, in the Baltic. Phaeton, meeting with his
death while carrying heat to the frozen stars of the boreal
regions, awakening at the Pole the Dragon made rigid by
cold, and being hurled down into the Eridanus, is an
allegory referring directly to the changes of climate in those
distant times when, from a frigid zone, the polar lands had
become a country with a moderate and warm climate. The
usurper of the functions of the Sun, Phaeton, being hurled
into the Eridanus by Jupiter's thunderbolt, is an allusion to
the second change that took place in those regions when,
once more, the land where “the magnolia blossomed”
became the desolate forbidding land of the farthest north
and eternal ice. This allegory covers then the events of two
Pralayas; and if well understood, ought to be a
demonstration of the enormous antiquity of the human
races.
1801. Iliad, xvii. 431-453.
1802. Ibid., 322-336.
1803. See Apollodorus for this number.
1804. See “The Sons of God and the Sacred Island.”
1805. So occult and mystic is one of the aspects of Latona that
she is made to reappear even in Revelation (xii), as the
woman clothed with the Sun (Apollo) and the Moon (Diana)
under her feet, who being with child “cried, travailing in
birth, and pained to be delivered.” A great red Dragon
stands before the woman ready to devour the child. She
brings forth the man-child who was to rule all nations with
a rod of iron, and who was caught unto the throne of God
—the Sun. The woman fled to the wilderness still pursued
by the Dragon, who flees again, and casts out of his mouth
water as a flood, when the Earth helped the woman and
swallowed the flood; and the Dragon went to make war
with the remnant of her seed who kept the commandments
of God. (See xii. 1, 17.) Anyone who reads the allegory of
Latona pursued by the revenge of jealous Juno, will
recognize the identity of the two versions. Juno sends
Python, the Dragon, to persecute and destroy Latona and
devour her babe. The latter is Apollo, the Sun, for the man-
child of Revelation, “who was to rule all nations with a rod
of iron” is surely not the meek “Son of God,” Jesus, but the
physical Sun, “who rules all nations”; the Dragon being the
North Pole, gradually chasing the early Lemurians from the
lands which became more and more Hyperborean and unfit
to be inhabited by those who were fast developing into
physical men, for they now had to deal with the climatic
variations. The Dragon will not allow Latona “to bring
forth”—the Sun to appear. “She is driven from heaven, and
finds no place where she can bring forth,” until Neptune,
the Ocean, in pity, makes immovable the floating isle of
Delos—the nymph Asteria, hitherto hiding from Jupiter
under the waves of the Ocean—on which Latona finds
refuge, and where the bright God Delius is born, the God,
who no sooner appears than he kills Python, the cold and
frost of the Arctic region, in whose deadly coils all life
becomes extinct. In other words, Latona-Lemuria is
transformed into Niobe-Atlantis, over which her son Apollo,
or the Sun, reigns—with an iron rod, truly, since Herodotus
makes the Atlantes curse his too great heat. This allegory is
reproduced in its other mystic meaning (another of the
seven keys) in the just cited chapter of Revelation. Latona
became a powerful Goddess indeed, and saw her son
receive worship (solar worship) in almost every fane of
antiquity. In his Occult aspect Apollo is patron of number
Seven. He is born on the seventh of the month, and the
swans of Myorica swim seven times round Delos singing
that event; he is given seven chords to his Lyre—the seven
rays of the Sun and the seven forces of Nature. But this is
only in the astronomical meaning, whereas the above is
purely geological.
1806. See Ovid, Metamorphoses, vi.
1807. Lettres sur l'Atlantide, p. 137.
1808. Hesiod, Opera et Dies, 143.
1809. Hist. Nat., iv. 12.
1810. Marius.
1811. Op. cit., c. 16.
1812. Isaac Myer's Qabbalah, p. 139.
1813. Diod., ii. 225.
1814. Op. cit., xxxvii. 2.
1815. Vol. i. pp. 462-464.
1816. These islands were “found strewn with fossils of horses,
sheep, oxen, etc., among gigantic bones of elephants,
mammoths, rhinoceroses,” etc. If there was no man on
Earth at that period “how came horses and sheep to be
found in company with the huge antediluvians?”—asks a
Master in a letter. (Esoteric Buddhism, p. 67.) The reply is
given above in the text.
1817. Op. cit., iv. 239-262.
1818. A good proof that all the Gods, and religious beliefs, and
myths have come from the North, which was also the
cradle of physical man, lies in several suggestive words
which have originated and remain to this day among the
northern tribes in their primeval significance; but, although
there was a time when all the nations were of “one lip,”
these words have received a different meaning with the
Greeks and Latins. One such word is mann, man, a living
being, and manes, dead men. The Laplanders call their
corpses to this day manee (Voyage de Rénard en Laponie,
i. 184). Mannus is the ancestor of the German race; the
Hindû Manu, the thinking being, from man; the Egyptian
Menes; and Minos, the King of Crete, judge of the infernal
regions after his death—all proceed from the same word or
root.
1819. Thus, for instance, Gyges is a hundred-armed and fifty-
headed monster, a Demi-god in one case, and a Lydian, the
successor of Candaules, king of the country, in another
version. The same is found in the Indian Pantheon, where
Rishis and the Sons of Brahmâ are reborn as mortals.
1820. Op. cit., viii. 13.
1821. The continents perish in turn by fire and water; either
through earthquakes and volcanic eruptions, or by sinking
and the great displacement of waters. Our continents have
to perish by the former cataclysmal process. The incessant
earthquakes of the past years may be a warning.
1822. See Decharme's Mythologie de la Grèce Antique.
1823. Denis, the Geographer, tells us that the great sea north of
Asia was called glacial, or Saturnine (v. 35). Orpheus (v.
1077) and Pliny (iv. 16) corroborate the statement by
showing that it was its giant inhabitants who gave it the
name. And the Secret Doctrine explains both assertions by
telling us that all the continents were formed from North to
South; and that as the sudden change of climate dwarfed
the race that had been born on it, arresting its growth, so,
several degrees southward, various conditions had always
produced the tallest men in every new humanity, or race.
We see it to this day. The tallest men now found are those
in Northern countries, while the smallest are Southern
Asiatics, Hindûs, Chinamen, Japanese, etc. Compare the tall
Sikhs and Punjabees, the Afghans, Norwegians, Russians,
Northern Germans, Scotchmen, and English, with the
inhabitants of Central India and the average European on
the continent. Thus also the Giants of Atlantis, and hence
the Titans of Hesiod, are all Northerners.
1824. Having already given several instances of the vagaries of
Science, it is delightful to find such agreement in this
particular case. Read in connection with the scientific
admission (cited elsewhere) of the Geologists' ignorance of
even the approximate duration of periods, the following
passage is highly instructive: “We are not yet able to assign
an approximate date for the most recent epoch at which
our northern hemisphere was covered with glaciers.
According to Mr. Wallace, this epoch may have occurred no
more than seventy thousand years ago, while others would
assign to it an antiquity of at least two hundred thousand
years, and there are yet others who urge strong arguments
on behalf of the opinion that a million of years is barely
enough to have produced the changes which have taken
place since that event.” (Fiske, Cosmic Philosophy, i. 304,
Ed. 1874.) Prof. Lefèvre, again, gives us as his estimate one
hundred thousand years. Clearly, then, if Modern Science is
unable to estimate the date of so comparatively recent an
era as the Glacial Epoch, it can hardly impeach the Esoteric
Chronology of Race-Periods and Geological Ages.
1825. Cited in Schmidt's Doctrine of Descent and Darwinism, pp.
300, 301.
1826. Philosophy Historical and Critical, p. 508.
1827. Human Species, pp. 428, et seqq.
1828. Art., “The First Volume of the Publications of the
'Challenger,'” p. 2, Nov. 4th, 1880.
1829. Op. cit., Art., “Australia and Europe formerly one Continent”
(v. 19, 25). Undoubtedly a fact, and a confirmation of the
Esoteric conception of Lemuria, which originally not only
embraced great areas in the Indian and Pacific Oceans, but
projected round South Africa into the North Atlantic. Its
Atlantic portion subsequently became the geological basis
of the future home of the Fourth Race Atlanteans.
1830. Ibid., i. 143.
1831. Cf., the published reports of the “Challenger” expedition;
also Donnelly's Atlantis, p. 468 and pp. 46-56, Chap., “The
Testimony of the Sea.”
1832. Even the cautious Lefèvre speaks of the existence of
Tertiary men on “upheaved lands, islands and continents
then flourishing, but since submerged beneath the waters,”
and elsewhere introduces a “possible Atlantis” to explain
ethnological facts. Cf., his Philosophy Historical and Critical,
pp. 478 and 504. Mr. Donnelly remarks with rare intuition
that “modern civilization is Atlantean ... the inventive
faculty of the present age is taking up the great delegated
work of creation where Atlantis left it thousands of years
ago” (Atlantis, p. 177. Twenty-fourth Ed.). He also refers
the origin of culture to the Miocene times. It is, however, to
be sought for in the teachings given to the Third Race men
by their Divine Rulers—at a vastly earlier period.
1833. An equally “curious” similarity may be traced between some
of the West Indian and West African fauna.
1834. The Pacific portion of the giant Lemurian Continent
christened by Dr. Carter Blake, the Anthropologist,
“Pacificus.”
1835. “Subsidence and Elevation,” Geological Magazine, pp. 241,
245, June, 1881.
1836. Antiquity of Man, p. 492.
1837. When Howard read, before the Royal Society of London, a
paper on the first serious researches that were made on
the aerolites, the Geneva Naturalist Pictet, who was
present, communicated, on his return to Paris, the facts
reported to the French Academy of Sciences. But he was
forthwith interrupted by Laplace, the great Astronomer,
who cried: “Stop! we have had enough of such fables, and
know all about them,” thus making Pictet feel very small.
Globular-shaped lightnings or thunder-bolts have been
admitted by Science only since Arago demonstrated their
existence. Says de Rochat (Forces Non-definies, p. 4):
“Every one remembers Dr. Bouilland's misadventure at the
Academy of Medicine when he had declared Edison's
phonograph ‘a trick of ventriloquism’!”
1838. Principles of Geology, i. 9, 10.
1839. Ibid.
1840. The Cyclic Law of Race-Evolution is most unwelcome to
Scientists. It is sufficient to mention the fact of “primeval
civilization” to excite the frenzy of Darwinians; it being
obvious that the further culture and science is pushed back,
the more precarious becomes the basis of the ape-ancestor
theory. But as Jacolliot says: “Whatever there may be in
these traditions [submerged continents, etc.], and whatever
may have been the place where a civilization more ancient
than that of Rome, of Greece, of Egypt, and of India, was
developed, it is certain that this civilization did exist, and it
is highly important for science to recover its traces,
however feeble and fugitive they be.” (Histoire des Vièrges;
les Peuples et les Continents Disparus, p. 15.) Donnelly has
proved the fact from the clearest premises, but the
Evolutionists will not listen. A Miocene civilization upsets the
“universal Stone age” theory, and that of a continuous
ascent of man from animalism. And yet Egypt, at least,
runs counter to current hypotheses. There is no Stone age
visible there, but a more glorious culture is apparent the
further back we are enabled to carry our retrospect.
1841. Myths and Myth-Makers, p. 21.
1842.
Violent minor cataclysms and colossal earthquakes are
recorded in the annals of most nations—if not of all.
Elevation and subsidence of continents is always in
progress. The whole coast of South America has been
raised up 10 to 15 feet and settled down again in an hour.
Huxley has shown that the British Islands have been four
times depressed beneath the ocean and subsequently
raised again and peopled. The Alps, Himâlayas and
Cordilleras were all the result of depositions drifted on to
sea-bottoms and upheaved by Titanic forces to their
present elevation. The Sahara was the basin of a Miocene
sea. Within the last five or six thousand years the shores of
Sweden, Denmark and Norway, have risen from 200 to 600
feet; in Scotland there are raised beaches with outlying
stacks and skerries surmounting the shore now eroded by
the hungry wave. The North of Europe is still rising from
the sea, and South America presents the phenomenon of
raised beaches of over 1,000 miles in length, now at a
height varying from 100 to 1,300 feet above the sea-level.
On the other hand, the coast of Greenland is sinking fast,
so much so that the Greenlander will not build by the
shore. All these phenomena are certain. Why then may not
a gradual change have given place to a violent cataclysm in
remote epochs—such cataclysms occurring on a minor scale
even now, e.g., the case of Sunda Island with the
destruction of 80,000 Malays?
1843. For the opinions of Jacolliot, after long travels through the
Polynesian Islands, and his proofs of a former great
geological cataclysm in the Pacific Ocean, see his Histoire
des Vièrges; les Peuples et les Continents Disparus, p. 308.
1844. August, 1880.
1845. Doctrine of Descent and Darwinism, pp. 236, 237. Cf. also
his lengthy arguments on the subject, pp. 231-235.
1846. Op. cit., i. 22, 23, Ed. 1869.
1847. Pedigree of Man, p. 73.
1848. Cited in Schmidt's Doctrine of Descent and Darwinism, p.
238.
1849. For further facts as to the isolation of the Basques in
Europe and their ethnological relations, see Joly, Man
before Metals, p. 316. B. Davis is disposed to concede, from
an examination of the skulls of the Guanches of the Canary
Islands and modern Basques, that both belong to a race
proper to those ancient islands, of which the Canaries are
the remains! This is a step in advance indeed. De
Quatrefages and Hamy also both assign the Cro-Magnon
men of South France and the Guanches to one type—a
proposition which involves a certain corollary which both
these writers may not care to father.
1850. Families of Speech.
1851. Cf., Benjamin, The Atlantic Islands, p. 130.
1852. Westminster Review, Jan., 1872.
1853. Schmidt, Doctrine of Descent and Darwinism, p. 223.
1854. Professor Retzius, Smithsonian Report, 1859, p. 266.
1855. See the investigations of United States ship “Dolphin” and
others.
1856. Scientific American, July 28th, 1877.
1857. See his chart, Atlantis, p. 46, though he deals with only a
fragment of the real Continent.
1858. Donnelly, Atlantis, p. 480.
1859. Maçonnerie Occulte, p. 44.
1860. Vide Sir William Thompson and Mr. Huxley.
*** END OF THE PROJECT GUTENBERG EBOOK THE SECRET
DOCTRINE, VOL. 2 OF 4 ***

Updated editions will replace the previous one—the old editions


will be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States
copyright in these works, so the Foundation (and you!) can copy
and distribute it in the United States without permission and
without paying copyright royalties. Special rules, set forth in the
General Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the


free distribution of electronic works, by using or distributing this
work (or any other work associated in any way with the phrase
“Project Gutenberg”), you agree to comply with all the terms of
the Full Project Gutenberg™ License available with this file or
online at www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand,
agree to and accept all the terms of this license and intellectual
property (trademark/copyright) agreement. If you do not agree
to abide by all the terms of this agreement, you must cease
using and return or destroy all copies of Project Gutenberg™
electronic works in your possession. If you paid a fee for
obtaining a copy of or access to a Project Gutenberg™
electronic work and you do not agree to be bound by the terms
of this agreement, you may obtain a refund from the person or
entity to whom you paid the fee as set forth in paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only


be used on or associated in any way with an electronic work by
people who agree to be bound by the terms of this agreement.
There are a few things that you can do with most Project
Gutenberg™ electronic works even without complying with the
full terms of this agreement. See paragraph 1.C below. There
are a lot of things you can do with Project Gutenberg™
electronic works if you follow the terms of this agreement and
help preserve free future access to Project Gutenberg™
electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright
law in the United States and you are located in the United
States, we do not claim a right to prevent you from copying,
distributing, performing, displaying or creating derivative works
based on the work as long as all references to Project
Gutenberg are removed. Of course, we hope that you will
support the Project Gutenberg™ mission of promoting free
access to electronic works by freely sharing Project Gutenberg™
works in compliance with the terms of this agreement for
keeping the Project Gutenberg™ name associated with the
work. You can easily comply with the terms of this agreement
by keeping this work in the same format with its attached full
Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.

1.E. Unless you have removed all references to Project


Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project
Gutenberg™ work (any work on which the phrase “Project
Gutenberg” appears, or with which the phrase “Project
Gutenberg” is associated) is accessed, displayed, performed,
viewed, copied or distributed:

This eBook is for the use of anyone anywhere in the United


States and most other parts of the world at no cost and
with almost no restrictions whatsoever. You may copy it,
give it away or re-use it under the terms of the Project
Gutenberg License included with this eBook or online at
www.gutenberg.org. If you are not located in the United
States, you will have to check the laws of the country
where you are located before using this eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is


derived from texts not protected by U.S. copyright law (does not
contain a notice indicating that it is posted with permission of
the copyright holder), the work can be copied and distributed to
anyone in the United States without paying any fees or charges.
If you are redistributing or providing access to a work with the
phrase “Project Gutenberg” associated with or appearing on the
work, you must comply either with the requirements of
paragraphs 1.E.1 through 1.E.7 or obtain permission for the use
of the work and the Project Gutenberg™ trademark as set forth
in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is


posted with the permission of the copyright holder, your use and
distribution must comply with both paragraphs 1.E.1 through
1.E.7 and any additional terms imposed by the copyright holder.
Additional terms will be linked to the Project Gutenberg™
License for all works posted with the permission of the copyright
holder found at the beginning of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files
containing a part of this work or any other work associated with
Project Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute


this electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the
Project Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™
works unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or


providing access to or distributing Project Gutenberg™
electronic works provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project


Gutenberg™ electronic work or group of works on different
terms than are set forth in this agreement, you must obtain
permission in writing from the Project Gutenberg Literary
Archive Foundation, the manager of the Project Gutenberg™
trademark. Contact the Foundation as set forth in Section 3
below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on,
transcribe and proofread works not protected by U.S. copyright
law in creating the Project Gutenberg™ collection. Despite these
efforts, Project Gutenberg™ electronic works, and the medium
on which they may be stored, may contain “Defects,” such as,
but not limited to, incomplete, inaccurate or corrupt data,
transcription errors, a copyright or other intellectual property
infringement, a defective or damaged disk or other medium, a
computer virus, or computer codes that damage or cannot be
read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except


for the “Right of Replacement or Refund” described in
paragraph 1.F.3, the Project Gutenberg Literary Archive
Foundation, the owner of the Project Gutenberg™ trademark,
and any other party distributing a Project Gutenberg™ electronic
work under this agreement, disclaim all liability to you for
damages, costs and expenses, including legal fees. YOU AGREE
THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT
LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT
EXCEPT THOSE PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE
THAT THE FOUNDATION, THE TRADEMARK OWNER, AND ANY
DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE LIABLE
TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL,
PUNITIVE OR INCIDENTAL DAMAGES EVEN IF YOU GIVE
NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of
receiving it, you can receive a refund of the money (if any) you
paid for it by sending a written explanation to the person you
received the work from. If you received the work on a physical
medium, you must return the medium with your written
explanation. The person or entity that provided you with the
defective work may elect to provide a replacement copy in lieu
of a refund. If you received the work electronically, the person
or entity providing it to you may choose to give you a second
opportunity to receive the work electronically in lieu of a refund.
If the second copy is also defective, you may demand a refund
in writing without further opportunities to fix the problem.

1.F.4. Except for the limited right of replacement or refund set


forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’,
WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of
damages. If any disclaimer or limitation set forth in this
agreement violates the law of the state applicable to this
agreement, the agreement shall be interpreted to make the
maximum disclaimer or limitation permitted by the applicable
state law. The invalidity or unenforceability of any provision of
this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the


Foundation, the trademark owner, any agent or employee of the
Foundation, anyone providing copies of Project Gutenberg™
electronic works in accordance with this agreement, and any
volunteers associated with the production, promotion and
distribution of Project Gutenberg™ electronic works, harmless
from all liability, costs and expenses, including legal fees, that
arise directly or indirectly from any of the following which you
do or cause to occur: (a) distribution of this or any Project
Gutenberg™ work, (b) alteration, modification, or additions or
deletions to any Project Gutenberg™ work, and (c) any Defect
you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new
computers. It exists because of the efforts of hundreds of
volunteers and donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project
Gutenberg™’s goals and ensuring that the Project Gutenberg™
collection will remain freely available for generations to come. In
2001, the Project Gutenberg Literary Archive Foundation was
created to provide a secure and permanent future for Project
Gutenberg™ and future generations. To learn more about the
Project Gutenberg Literary Archive Foundation and how your
efforts and donations can help, see Sections 3 and 4 and the
Foundation information page at www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-
profit 501(c)(3) educational corporation organized under the
laws of the state of Mississippi and granted tax exempt status
by the Internal Revenue Service. The Foundation’s EIN or
federal tax identification number is 64-6221541. Contributions
to the Project Gutenberg Literary Archive Foundation are tax
deductible to the full extent permitted by U.S. federal laws and
your state’s laws.

The Foundation’s business office is located at 809 North 1500


West, Salt Lake City, UT 84116, (801) 596-1887. Email contact
links and up to date contact information can be found at the
Foundation’s website and official page at
www.gutenberg.org/contact
Section 4. Information about Donations to
the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission
of increasing the number of public domain and licensed works
that can be freely distributed in machine-readable form
accessible by the widest array of equipment including outdated
equipment. Many small donations ($1 to $5,000) are particularly
important to maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws


regulating charities and charitable donations in all 50 states of
the United States. Compliance requirements are not uniform
and it takes a considerable effort, much paperwork and many
fees to meet and keep up with these requirements. We do not
solicit donations in locations where we have not received written
confirmation of compliance. To SEND DONATIONS or determine
the status of compliance for any particular state visit
www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states


where we have not met the solicitation requirements, we know
of no prohibition against accepting unsolicited donations from
donors in such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot


make any statements concerning tax treatment of donations
received from outside the United States. U.S. laws alone swamp
our small staff.

Please check the Project Gutenberg web pages for current


donation methods and addresses. Donations are accepted in a
number of other ways including checks, online payments and
credit card donations. To donate, please visit:
www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could
be freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose
network of volunteer support.

Project Gutenberg™ eBooks are often created from several


printed editions, all of which are confirmed as not protected by
copyright in the U.S. unless a copyright notice is included. Thus,
we do not necessarily keep eBooks in compliance with any
particular paper edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg
Literary Archive Foundation, how to help produce our new
eBooks, and how to subscribe to our email newsletter to hear
about new eBooks.
back
back
back
back
back
back
back

You might also like