SlideShare a Scribd company logo
Practical SQL A Beginner s Guide to Storytelling
with Data 2nd Edition Anthony Debarros install
download
https://ebookmeta.com/product/practical-sql-a-beginner-s-guide-
to-storytelling-with-data-2nd-edition-anthony-debarros/
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!
Practical SQL A Beginner s Guide to Storytelling with
Data 2nd Edition Anthony Debarros
https://ebookmeta.com/product/practical-sql-a-beginner-s-guide-
to-storytelling-with-data-2nd-edition-anthony-debarros/
Practical SQL: A Beginner's Guide to Storytelling with
Data, 2nd Edition Anthony Debarros
https://ebookmeta.com/product/practical-sql-a-beginners-guide-to-
storytelling-with-data-2nd-edition-anthony-debarros/
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/
Mathematics Mathematics HL Option Discrete Mathematics
1st Edition Catherine Quinn Peter Blythe Chris Sangwin
Robert Haese Michael Haese
https://ebookmeta.com/product/mathematics-mathematics-hl-option-
discrete-mathematics-1st-edition-catherine-quinn-peter-blythe-
chris-sangwin-robert-haese-michael-haese/
Nothing s Worse Than A Clown Gone Bad 1st Edition Ponk
Vonsydow
https://ebookmeta.com/product/nothing-s-worse-than-a-clown-gone-
bad-1st-edition-ponk-vonsydow/
Revenge Of Her Wolves Tara West
https://ebookmeta.com/product/revenge-of-her-wolves-tara-west/
Demystifying the Order from Above 1st Edition Lubogo
Isaac Christopher
https://ebookmeta.com/product/demystifying-the-order-from-
above-1st-edition-lubogo-isaac-christopher/
Blockchain and the Supply Chain: Concepts, Strategies
and Practical Applications, 2nd Edition Nick Vyas
https://ebookmeta.com/product/blockchain-and-the-supply-chain-
concepts-strategies-and-practical-applications-2nd-edition-nick-
vyas/
A Warning for Fair Women Adultery and Murder in
Shakespeare s Theater 1st Edition Ann C Christensen
https://ebookmeta.com/product/a-warning-for-fair-women-adultery-
and-murder-in-shakespeare-s-theater-1st-edition-ann-c-
christensen/
Contemporary Strategy : Theories and Policies 1st
Edition John Baylis
https://ebookmeta.com/product/contemporary-strategy-theories-and-
policies-1st-edition-john-baylis/
Practical SQL A Beginner s Guide to Storytelling with Data 2nd Edition Anthony Debarros
CONTENTS IN DETAIL
TITLE PAGE
COPYRIGHT
ABOUT THE AUTHOR
PREFACE TO THE SECOND EDITION
ACKNOWLEDGMENTS
INTRODUCTION
What Is SQL?
Why SQL?
Who Is This Book For?
What You’ll Learn
CHAPTER 1: SETTING UP YOUR CODING ENVIRONMENT
Installing a Text Editor
Downloading Code and Data from GitHub
Installing PostgreSQL and pgAdmin
Windows Installation
macOS Installation
Linux Installation
Working with pgAdmin
Launching pgAdmin and Setting a Master Password
Connecting to the Default postgres Database
Exploring the Query Tool
Customizing pgAdmin
Alternatives to pgAdmin
Wrapping Up
CHAPTER 2: CREATING YOUR FIRST DATABASE AND
TABLE
Understanding Tables
Creating a Database
Executing SQL in pgAdmin
Connecting to the analysis Database
Creating a Table
Using the CREATE TABLE Statement
Making the teachers Table
Inserting Rows into a Table
Using the INSERT Statement
Viewing the Data
Getting Help When Code Goes Bad
Formatting SQL for Readability
Wrapping Up
CHAPTER 3: BEGINNING DATA EXPLORATION WITH
SELECT
Basic SELECT Syntax
Querying a Subset of Columns
Sorting Data with ORDER BY
Using DISTINCT to Find Unique Values
Filtering Rows with WHERE
Using LIKE and ILIKE with WHERE
Combining Operators with AND and OR
Putting It All Together
Wrapping Up
CHAPTER 4: UNDERSTANDING DATA TYPES
Understanding Characters
Understanding Numbers
Using Integers
Auto-Incrementing Integers
Using Decimal Numbers
Choosing Your Number Data Type
Understanding Dates and Times
Using the interval Data Type in Calculations
Understanding JSON and JSONB
Using Miscellaneous Types
Transforming Values from One Type to Another with CAST
Using CAST Shortcut Notation
Wrapping Up
CHAPTER 5: IMPORTING AND EXPORTING DATA
Working with Delimited Text Files
Handling Header Rows
Quoting Columns That Contain Delimiters
Using COPY to Import Data
Importing Census Data Describing Counties
Creating the us_counties_pop_est_2019 Table
Understanding Census Columns and Data Types
Performing the Census Import with COPY
Inspecting the Import
Importing a Subset of Columns with COPY
Importing a Subset of Rows with COPY
Adding a Value to a Column During Import
Using COPY to Export Data
Exporting All Data
Exporting Particular Columns
Exporting Query Results
Importing and Exporting Through pgAdmin
Wrapping Up
CHAPTER 6: BASIC MATH AND STATS WITH SQL
Understanding Math Operators and Functions
Understanding Math and Data Types
Adding, Subtracting, and Multiplying
Performing Division and Modulo
Using Exponents, Roots, and Factorials
Minding the Order of Operations
Doing Math Across Census Table Columns
Adding and Subtracting Columns
Finding Percentages of the Whole
Tracking Percent Change
Using Aggregate Functions for Averages and Sums
Finding the Median
Finding the Median with Percentile Functions
Finding Median and Percentiles with Census Data
Finding Other Quantiles with Percentile Functions
Finding the Mode
Wrapping Up
CHAPTER 7: JOINING TABLES IN A RELATIONAL
DATABASE
Linking Tables Using JOIN
Relating Tables with Key Columns
Querying Multiple Tables Using JOIN
Understanding JOIN Types
JOIN
LEFT JOIN and RIGHT JOIN
FULL OUTER JOIN
CROSS JOIN
Using NULL to Find Rows with Missing Values
Understanding the Three Types of Table Relationships
One-to-One Relationship
One-to-Many Relationship
Many-to-Many Relationship
Selecting Specific Columns in a Join
Simplifying JOIN Syntax with Table Aliases
Joining Multiple Tables
Combining Query Results with Set Operators
UNION and UNION ALL
INTERSECT and EXCEPT
Performing Math on Joined Table Columns
Wrapping Up
CHAPTER 8: TABLE DESIGN THAT WORKS FOR YOU
Following Naming Conventions
Quoting Identifiers Enables Mixed Case
Pitfalls with Quoting Identifiers
Guidelines for Naming Identifiers
Controlling Column Values with Constraints
Primary Keys: Natural vs. Surrogate
Foreign Keys
How to Automatically Delete Related Records with
CASCADE
The CHECK Constraint
The UNIQUE Constraint
The NOT NULL Constraint
How to Remove Constraints or Add Them Later
Speeding Up Queries with Indexes
B-Tree: PostgreSQL’s Default Index
Considerations When Using Indexes
Wrapping Up
CHAPTER 9: EXTRACTING INFORMATION BY GROUPING
AND SUMMARIZING
Creating the Library Survey Tables
Creating the 2018 Library Data Table
Creating the 2017 and 2016 Library Data Tables
Exploring the Library Data Using Aggregate Functions
Counting Rows and Values Using count()
Finding Maximum and Minimum Values Using max() and
min()
Aggregating Data Using GROUP BY
Wrapping Up
CHAPTER 10: INSPECTING AND MODIFYING DATA
Importing Data on Meat, Poultry, and Egg Producers
Interviewing the Dataset
Checking for Missing Values
Checking for Inconsistent Data Values
Checking for Malformed Values Using length()
Modifying Tables, Columns, and Data
Modifying Tables with ALTER TABLE
Modifying Values with UPDATE
Viewing Modified Data with RETURNING
Creating Backup Tables
Restoring Missing Column Values
Updating Values for Consistency
Repairing ZIP Codes Using Concatenation
Updating Values Across Tables
Deleting Unneeded Data
Deleting Rows from a Table
Deleting a Column from a Table
Deleting a Table from a Database
Using Transactions to Save or Revert Changes
Improving Performance When Updating Large Tables
Wrapping Up
CHAPTER 11: STATISTICAL FUNCTIONS IN SQL
Creating a Census Stats Table
Measuring Correlation with corr(Y, X)
Checking Additional Correlations
Predicting Values with Regression Analysis
Finding the Effect of an Independent Variable with r-
Squared
Finding Variance and Standard Deviation
Creating Rankings with SQL
Ranking with rank() and dense_rank()
Ranking Within Subgroups with PARTITION BY
Calculating Rates for Meaningful Comparisons
Finding Rates of Tourism-Related Businesses
Smoothing Uneven Data
Wrapping Up
CHAPTER 12: WORKING WITH DATES AND TIMES
Understanding Data Types and Functions for Dates and Times
Manipulating Dates and Times
Extracting the Components of a timestamp Value
Creating Datetime Values from timestamp Components
Retrieving the Current Date and Time
Working with Time Zones
Finding Your Time Zone Setting
Setting the Time Zone
Performing Calculations with Dates and Times
Finding Patterns in New York City Taxi Data
Finding Patterns in Amtrak Data
Wrapping Up
CHAPTER 13: ADVANCED QUERY TECHNIQUES
Using Subqueries
Filtering with Subqueries in a WHERE Clause
Creating Derived Tables with Subqueries
Joining Derived Tables
Generating Columns with Subqueries
Understanding Subquery Expressions
Using Subqueries with LATERAL
Using Common Table Expressions
Performing Cross Tabulations
Installing the crosstab() Function
Tabulating Survey Results
Tabulating City Temperature Readings
Reclassifying Values with CASE
Using CASE in a Common Table Expression
Wrapping Up
CHAPTER 14: MINING TEXT TO FIND MEANINGFUL DATA
Formatting Text Using String Functions
Case Formatting
Character Information
Removing Characters
Extracting and Replacing Characters
Matching Text Patterns with Regular Expressions
Regular Expression Notation
Using Regular Expressions with WHERE
Regular Expression Functions to Replace or Split Text
Turning Text to Data with Regular Expression Functions
Full-Text Search in PostgreSQL
Text Search Data Types
Creating a Table for Full-Text Search
Searching Speech Text
Ranking Query Matches by Relevance
Wrapping Up
CHAPTER 15: ANALYZING SPATIAL DATA WITH POSTGIS
Enabling PostGIS and Creating a Spatial Database
Understanding the Building Blocks of Spatial Data
Understanding Two-Dimensional Geometries
Well-Known Text Formats
Projections and Coordinate Systems
Spatial Reference System Identifier
Understanding PostGIS Data Types
Creating Spatial Objects with PostGIS Functions
Creating a Geometry Type from Well-Known Text
Creating a Geography Type from Well-Known Text
Using Point Functions
Using LineString Functions
Using Polygon Functions
Analyzing Farmers’ Markets Data
Creating and Filling a Geography Column
Adding a Spatial Index
Finding Geographies Within a Given Distance
Finding the Distance Between Geographies
Finding the Nearest Geographies
Working with Census Shapefiles
Understanding the Contents of a Shapefile
Loading Shapefiles
Exploring the Census 2019 Counties Shapefile
Examining Demographics Within a Distance
Performing Spatial Joins
Exploring Roads and Waterways Data
Joining the Census Roads and Water Tables
Finding the Location Where Objects Intersect
Wrapping Up
CHAPTER 16: WORKING WITH JSON DATA
Understanding JSON Structure
Considering When to Use JSON with SQL
Using json and jsonb Data Types
Importing and Indexing JSON Data
Using json and jsonb Extraction Operators
Key Value Extraction
Array Element Extraction
Path Extraction
Containment and Existence
Analyzing Earthquake Data
Exploring and Loading the Earthquake Data
Working with Earthquake Times
Finding the Largest and Most-Reported Earthquakes
Converting Earthquake JSON to Spatial Data
Generating and Manipulating JSON
Turning Query Results into JSON
Adding, Updating, and Deleting Keys and Values
Using JSON Processing Functions
Finding the Length of an Array
Returning Array Elements as Rows
Wrapping Up
CHAPTER 17: SAVING TIME WITH VIEWS, FUNCTIONS,
AND TRIGGERS
Using Views to Simplify Queries
Creating and Querying Views
Creating and Refreshing a Materialized View
Inserting, Updating, and Deleting Data Using a View
Creating Your Own Functions and Procedures
Creating the percent_change() Function
Using the percent_change() Function
Updating Data with a Procedure
Using the Python Language in a Function
Automating Database Actions with Triggers
Logging Grade Updates to a Table
Automatically Classifying Temperatures
Wrapping Up
CHAPTER 18: USING POSTGRESQL FROM THE COMMAND
LINE
Setting Up the Command Line for psql
Windows psql Setup
macOS psql Setup
Linux psql Setup
Working with psql
Launching psql and Connecting to a Database
Running SQL Queries on psql
Navigating and Formatting Results
Meta-Commands for Database Information
Importing, Exporting, and Using Files
Additional Command Line Utilities to Expedite Tasks
Adding a Database with createdb
Loading Shapefiles with shp2pgsql
Wrapping Up
CHAPTER 19: MAINTAINING YOUR DATABASE
Recovering Unused Space with VACUUM
Tracking Table Size
Monitoring the Autovacuum Process
Running VACUUM Manually
Reducing Table Size with VACUUM FULL
Changing Server Settings
Locating and Editing postgresql.conf
Reloading Settings with pg_ctl
Backing Up and Restoring Your Database
Using pg_dump to Export a Database or Table
Restoring a Database Export with pg_restore
Exploring Additional Backup and Restore Options
Wrapping Up
CHAPTER 20: TELLING YOUR DATA’S STORY
Start with a Question
Document Your Process
Gather Your Data
No Data? Build Your Own Database
Assess the Data’s Origins
Interview the Data with Queries
Consult the Data’s Owner
Identify Key Indicators and Trends over Time
Ask Why
Communicate Your Findings
Wrapping Up
APPENDIX: ADDITIONAL POSTGRESQL RESOURCES
PostgreSQL Development Environments
PostgreSQL Utilities, Tools, and Extensions
PostgreSQL News and Community
Documentation
INDEX
PRACTICAL SQL
2nd Edition
A Beginner’s Guide to Storytelling
with Data
by Anthony DeBarros
PRACTICAL SQL, 2ND EDITION. Copyright © 2022 by Anthony DeBarros.
All rights reserved. No part of this work may be reproduced or transmitted in any
form or by any means, electronic or mechanical, including photocopying,
recording, or by any information storage or retrieval system, without the prior
written permission of the copyright owner and the publisher.
Printed in the United States of America
First printing
25 24 23 22 21 1 2 3 4 5 6 7 8 9
ISBN-13: 978-1-7185-0106-5 (print)
ISBN-13: 978-1-7185-0107-2 (ebook)
Publisher: William Pollock
Managing Editor: Jill Franklin
Production Manager: Rachel Monaghan
Production Editors: Jennifer Kepler and Paula Williamson
Developmental Editor: Liz Chadwick
Cover Illustrator: Josh Ellingson
Interior Design: Octopod Studios
Technical Reviewer: Stephen Frost
Copyeditor: Kim Wimpsett
Compositor: Maureen Forys, Happenstance Type-O-Rama
Proofreader: Liz Wheeler
For information on book distributors or translations, please contact No Starch
Press, Inc. directly:
No Starch Press, Inc.
245 8th Street, San Francisco, CA 94103
phone: 1.415.863.9900; info@nostarch.com
www.nostarch.com
The Library of Congress has catalogued the first edition as follows:
Names: DeBarros, Anthony, author.
Title: Practical SQL : a beginner's guide to storytelling with data / Anthony
DeBarros.
Description: San Francisco : No Starch Press, 2018. | Includes index.
Identifiers: LCCN 2018000030 (print) | LCCN 2017043947 (ebook) | ISBN 9781593278458
(epub) | ISBN
1593278454 (epub) | ISBN 9781593278274 (paperback) | ISBN 1593278276 (paperback)
| ISBN 9781593278458
(ebook)
Subjects: LCSH: SQL (Computer program language) | Database design. | BISAC:
COMPUTERS / Programming
Languages / SQL. | COMPUTERS / Database Management / General. | COMPUTERS /
Database Management
/ Data Mining.
Classification: LCC QA76.73.S67 (print) | LCC QA76.73.S67 D44 2018 (ebook) | DDC
005.75/6--dc23
LC record available at https://lccn.loc.gov/2018000030
No Starch Press and the No Starch Press logo are registered trademarks of No
Starch Press, Inc. Other product and company names mentioned herein may be
the trademarks of their respective owners. Rather than use a trademark symbol
with every occurrence of a trademarked name, we are using the names only in an
editorial fashion and to the benefit of the trademark owner, with no intention of
infringement of the trademark.
The information in this book is distributed on an “As Is” basis, without warranty.
While every precaution has been taken in the preparation of this work, neither the
author nor No Starch Press, Inc. shall have any liability to any person or entity
with respect to any loss or damage caused or alleged to be caused directly or
indirectly by the information contained in it.
About the Author
Anthony DeBarros is a longtime journalist and early adopter of “data
journalism,” the use of spreadsheets, databases, and code to find
news in data. He’s currently a data editor for the Wall Street
Journal, where he covers topics including the economy, trade,
demographics, and the Covid-19 pandemic. Previously, he worked
for the Gannett company at USA Today and the Poughkeepsie
Journal and held product development and content strategy roles for
Questex and DocumentCloud.
About the Technical Reviewer
Stephen Frost is the chief technology officer at Crunchy Data. He has
been working with PostgreSQL since 2003 and general database
technology since before then. Stephen began contributing to
PostgreSQL development in 2004 and has been involved in the
development of the role system, column-level privileges, row-level
security, GSSAPI encryption, and the predefined roles system. He
has also served on the board of the United States PostgreSQL
Association and Software in the Public Interest, regularly speaks at
PostgreSQL Community conferences and events, and works as a
member of various PostgreSQL community teams.
PREFACE TO THE SECOND EDITION
Since the publication of the first edition of Practical
SQL, I’ve received kind notes about the book from
readers around the world. One happy reader said it
helped him ace SQL questions on a job interview.
Another, a teacher, wrote to say that his students
remarked favorably about having the book assigned
for class. Others just wanted to say thanks because
they found the book helpful and a good read, two
pieces of feedback that will warm the heart of most
any author.
I also sometimes heard from readers who hit a roadblock while
working through an exercise or who had trouble with software or
data files. I paid close attention to those emails, especially when the
same question seemed to crop up more than once. Meanwhile,
during my own journey of learning SQL—I use it every day at work—
I’d often discover a technique and wish that I’d included it in the
book.
With all that in mind, I approached the team at No Starch Press
with the idea of updating and expanding Practical SQL into a second
edition. I’m thankful they said yes. This new version of the book is
more complete, offers stronger guidance for readers related to
software and code, and clarifies information that wasn’t as clear or
presented as accurately as it could have been. The book has been
thoroughly enjoyable to revisit, and I’ve learned much along the way.
This second edition includes numerous updates, expansions, and
clarifications in every chapter. Throughout, I’ve been careful to note
when code syntax adheres to the SQL standard—meaning you can
generally use it across database systems—or when the syntax is
specific to the database used in the book, PostgreSQL.
The following are among the most substantial changes:
Two chapters are new. Chapter 1, “Setting Up Your Coding
Environment,” details how to install PostgreSQL, pgAdmin, and
additional PostgreSQL components on multiple operating
systems. It also shows how to obtain the code listings and data
from GitHub. In the first edition, this information was located in
the introduction and occasionally missed by readers. Chapter 16,
“Working with JSON Data,” covers PostgreSQL’s support for the
JavaScript Object Notation data format, using datasets about
movies and earthquakes.
In Chapter 4 on data types, I’ve added a section on IDENTITY, the
ANSI SQL standard implementation for auto-incrementing
integer columns. Throughout the book, IDENTITY replaces the
PostgreSQL-specific serial auto-incrementing integer type so that
code examples more closely reflect the SQL standard.
Chapter 5 on importing and exporting data now includes a
section about using the WHERE keyword with the COPY command to
filter which rows are imported from a source file to a table.
I’ve removed the user-created median() function from Chapter 6 on
basic math in favor of focusing exclusively on the SQL standard
percentile_cont() function for calculating medians.
In Chapter 7 on table joins, I’ve added a section covering the set
operators UNION, UNION ALL, INTERSECT, and EXCEPT. Additionally, I’ve
added a section covering the USING clause in joins to reduce
redundant output and simplify query syntax.
Chapter 10 on inspecting and modifying data includes a new
section on using the RETURNING keyword in an UPDATE statement to
display the data that the statement modified. I’ve also added a
section that describes how to use the TRUNCATE command to remove
all rows from a table and restart an IDENTITY sequence.
In Chapter 11 on statistical functions, a new section demonstrates
how to create a rolling average to smooth uneven data to get a
better sense of trends over time. I’ve also added information on
functions for calculating standard deviation and variance.
Chapter 13 on advanced query techniques now shows how to use
the LATERAL keyword with subqueries. One benefit is that, by
combining LATERAL with JOIN, you get functionality similar to a for
loop in a programming language.
In Chapter 15 on analyzing spatial data, I demonstrate how to use
the Geometry Viewer in pgAdmin to see geographies placed on a
map. This feature was added to pgAdmin after publication of the
first edition.
In Chapter 17 on views, functions, and triggers, I’ve added
information about materialized views and showed how their
behavior differs from standard views. I also cover procedures,
which PostgreSQL now supports in addition to functions.
Finally, where practical, datasets have been updated to the most
recent available at the time of writing. This primarily applies to
US Census population statistics but also includes the text of
presidential speeches and library usage statistics.
Thank you for reading Practical SQL! If you have any questions or
feedback, please get in touch by emailing
practicalsqlbook@gmail.com.
ACKNOWLEDGMENTS
This second edition of Practical SQL is the work of many hands. My
thanks, first, go to the team at No Starch Press. Thanks to Bill
Pollock for capturing the vision and sharpening the initial concept
for the book—and for agreeing to let me have another go at it. Special
thanks and appreciation to senior editor Liz Chadwick, who
improved each chapter with her insightful suggestions and deft
editing, and to copyeditor Kim Wimpsett and the production team of
Paula Williamson and Jennifer Kepler.
Stephen Frost, chief technology officer at Crunchy Data and
longtime contributor to the PostgreSQL community, served as the
technical reviewer for this edition. I deeply appreciate the time
Stephen took to explain the inner workings of PostgreSQL and SQL
concepts. This book is better, more thorough, and more accurate
thanks to his detailed eye. I’d also like to acknowledge Josh Berkus,
whose many contributions as technical reviewer for the first edition
persist in this new version.
Thank you to Investigative Reporters and Editors (IRE) and its
members and staff past and present for training journalists to find
stories in data. IRE is where I got my start with SQL and data
journalism.
Many of my colleagues have not only imparted memorable lessons
on data analysis, they’ve also made my workdays brighter. Special
thanks to Paul Overberg for sharing his vast knowledge of
demographics and the US Census, to Lou Schilling for many
technical lessons, to Christopher Schnaars for his SQL expertise, to
Peter Matseykanets for his encouragement, and to Chad Day, John
West, and Maureen Linke and the WSJ DC visuals team for continual
inspiration.
My deepest appreciation goes to my dear wife, Elizabeth, and our
sons. You are the brightest lights in my day. As we are fond of saying,
“To the journey . . .”
INTRODUCTION
Shortly after joining the staff of USA
Today, I received a dataset that I would
analyze almost every week for the next
decade. It was the weekly Best-Selling
Books list, which ranked the nation’s top-selling titles
based on confidential sales data. Not only did the list
produce an endless stream of story ideas to pitch, it
also captured the zeitgeist of America in a singular
way.
Did you know that cookbooks sell a bit more during the week of
Mother’s Day or that Oprah Winfrey turned many obscure writers
into number-one best-selling authors just by having them on her
show? Every week, the book list editor and I pored over the sales
figures and book genres, ranking the data in search of a new
headline. Rarely did we come up empty: we chronicled everything
from the rocket-rise of the blockbuster Harry Potter series to the
fact that Oh, the Places You’ll Go! by Dr. Seuss had become a
perennial gift for new graduates.
My technical companion in that time was the database
programming language SQL (for Structured Query Language). Early
on, I convinced USA Today’s IT department to grant me access to the
SQL-based database system that powered our book list application.
Using SQL, I was able to discover the stories hidden in the database,
which contained sales data related to titles, authors, genres, and the
codes that defined the publishing world.
SQL has been useful to me ever since, whether my role was in
product development, in content strategy, or, lately, as a data editor
for the Wall Street Journal. In each case, SQL has helped me find
interesting stories in data—and that’s exactly what you’ll learn to do
using this book.
What Is SQL?
SQL is a widely used programming language for managing data and
database systems. Whether you’re a marketing analyst, a journalist,
or a researcher mapping neurons in the brain of a fruit fly, you’ll
benefit from using SQL to collect, modify, explore, and summarize
data.
Because SQL is a mature language that’s been around for decades,
it’s ingrained in many modern systems. A pair of IBM researchers
first outlined the syntax for SQL (then called SEQUEL) in a 1974
paper, building on the theoretical work of the British computer
scientist Edgar F. Codd. In 1979, a precursor to the database
company Oracle (then called Relational Software) became the first to
use the language in a commercial product. Today, SQL still ranks as
one of the most-used computer languages in the world, and that’s
unlikely to change soon.
Each database system, such as PostgreSQL, MySQL or Microsoft
SQL Server, implements its own variant of SQL, so you’ll notice
subtle—or sometimes significant—differences in syntax if you jump
from one system to another. There are several reasons behind this.
The American National Standards Institute (ANSI) adopted a
standard for SQL in 1986, followed by the International Organization
for Standardization (ISO) in 1987. But the standard doesn’t cover all
aspects of SQL that are required for a database implementation—for
example, it has no entry for creating indexes. That leaves each
database system maker to choose how to implement features the
standard doesn’t cover—and no database maker currently claims to
conform to the entire standard.
Meanwhile, business considerations can lead commercial database
vendors to create nonstandard SQL features for both competitive
advantage and as a way to keep users in their ecosystem. For
example, Microsoft’s SQL Server uses the proprietary Transact-SQL
(T-SQL) that includes a number of features not in the SQL standard,
such as its syntax for declaring local variables. Migrating code
written using T-SQL to another database system may not be trivial,
therefore.
In this book, the examples and code use the PostgreSQL database
system. PostgreSQL, or simply Postgres, is a robust application that
can handle large amounts of data. Here are some reasons
PostgreSQL is a great choice to use with this book:
It’s free.
It’s available for Windows, macOS, and Linux operating systems.
Its SQL implementation aims to closely follow the SQL standard.
It’s widely used, so finding help online is easy.
Its geospatial extension, PostGIS, lets you analyze geometric data
and perform mapping functions and is often used with mapping
software such as QGIS.
It’s available in cloud computing environments such as Amazon
Web Services and Google Cloud.
It’s a common choice as a data store for web applications,
including those powered by the popular web framework Django.
The good news is that the fundamental concepts and much of the
core SQL syntactical conventions of PostgreSQL will work across
databases. So, if you’re using MySQL at work, you can employ much
of what you learn here—or easily find parallel code concepts. When
syntax is PostgreSQL-specific, I make sure to point that out. If you
need to learn the SQL syntax of a system with features that deviate
from the standard, such as Microsoft SQL Server’s T-SQL, you may
want to further explore a resource focusing on that system.
Why SQL?
SQL certainly isn’t the only option for crunching data. Many people
start with Microsoft Excel spreadsheets and their assortment of
analytic functions. After working with Excel, they might graduate to
Access, the database system built into some versions of Microsoft
Office, which has a graphical query interface that makes it easy to get
work done. So why learn SQL?
One reason is that Excel and Access have their limits. Excel
currently allows 1,048,576 rows maximum per worksheet. Access
limits database size to two gigabytes and limits columns to 255 per
table. It’s not uncommon for datasets to surpass those limits. The
last obstacle you want to discover while facing a deadline is that your
database system doesn’t have the capacity to get the job done.
Using a robust SQL database system allows you to work with
terabytes of data, multiple related tables, and thousands of columns.
It gives you fine-grained control over the structure of your data,
leading to efficiency, speed, and—most important—accuracy.
SQL is also an excellent adjunct to programming languages used in
the data sciences, such as R and Python. If you use either language,
you can connect to SQL databases and, in some cases, even
incorporate SQL syntax directly into the language. For people with
no background in programming languages, SQL often serves as an
easy-to-understand introduction into concepts related to data
structures and programming logic.
Finally, SQL is useful beyond data analysis. If you delve into
building online applications, you’ll find that databases provide the
backend power for many common web frameworks, interactive
maps, and content management systems. When you need to dig
beneath the surface of these applications, the ability to manage data
and databases with SQL will come in very handy.
Who Is This Book For?
Practical SQL is for people who encounter data in their everyday
lives and want to learn how to analyze, manage, and transform it.
With that in mind, we cover real-world data and scenarios, such as
US Census demographics, crime reports, and data about taxi rides in
New York City. We aim to understand not only how SQL works but
how we can use it to find valuable insights.
This book was written with people new to programming in mind,
so the early chapters cover key basics about databases, data, and SQL
syntax. Readers with some SQL experience should benefit from later
chapters that cover more advanced topics, such as Geographical
Information Systems (GIS). I assume that you know your way
around your computer, including how to install programs, navigate
your hard drive, and download files from the internet, but I don’t
assume you have any experience with programming or data analysis.
What You’ll Learn
Practical SQL starts with a chapter on setting up your system and
getting the code and data examples and then moves through the
basics of databases, queries, tables, and data that are common to
SQL across many database systems. Chapters 14 to 19 cover topics
more specific to PostgreSQL, such as full-text search, functions, and
GIS. Although many chapters in this book can stand alone, you
should work through the book sequentially to build on the
fundamentals. Datasets presented in early chapters often reappear
later, so following the book in order will help you stay on track.
The following summary provides more detail about each chapter:
Chapter 1: Setting Up Your Coding Environment walks
through setting up PostgreSQL, the pgAdmin user interface, and a
text editor, plus how to download example code and data.
Chapter 2: Creating Your First Database and Table
provides step-by-step instructions for the process of loading a simple
dataset about teachers into a new database.
Chapter 3: Beginning Data Exploration with SELECT
explores basic SQL query syntax, including how to sort and filter
data.
Chapter 4: Understanding Data Types explains the
definitions for setting columns in a table to hold specific types of
data, from text to dates to various forms of numbers.
Chapter 5: Importing and Exporting Data explains how to
use SQL commands to load data from external files and then export
it. You’ll load a table of US Census population data that you’ll use
throughout the book.
Chapter 6: Basic Math and Stats with SQL covers arithmetic
operations and introduces aggregate functions for finding sums,
averages, and medians.
Chapter 7: Joining Tables in a Relational Database
explains how to query multiple, related tables by joining them on key
columns. You’ll learn how and when to use different types of joins.
Chapter 8: Table Design that Works for You covers how to
set up tables to improve the organization and integrity of your data
as well as how to speed up queries using indexes.
Chapter 9: Extracting Information by Grouping and
Summarizing explains how to use aggregate functions to find
trends in US library usage based on annual surveys.
Chapter 10: Inspecting and Modifying Data explores how to
find and fix incomplete or inaccurate data using a collection of
records about meat, egg, and poultry producers as an example.
Chapter 11: Statistical Functions in SQL introduces
correlation, regression, ranking, and other functions to help you
derive more meaning from datasets.
Chapter 12: Working with Dates and Times explains how to
create, manipulate, and query dates and times in your database,
including working with time zones and with data about New York
City taxi trips and Amtrak train schedules.
Chapter 13: Advanced Query Techniques explains how to
use more complex SQL operations such as subqueries and cross
tabulations, plus the CASE statement, to reclassify values in a dataset
on temperature readings.
Chapter 14: Mining Text to Find Meaningful Data covers
how to use PostgreSQL’s full-text search engine and regular
expressions to extract data from unstructured text, using police
reports and a collection of speeches by US presidents as examples.
Chapter 15: Analyzing Spatial Data with PostGIS
introduces data types and queries related to spatial objects, which
will let you analyze geographical features such as counties, roads,
and rivers.
Chapter 16: Working with JSON Data introduces the
JavaScript Object Notation (JSON) data format and uses data about
movies and earthquakes to explore PostgreSQL JSON support.
Chapter 17: Saving Time with Views, Functions, and
Triggers explains how to automate database tasks so you can avoid
repeating routine work.
Chapter 18: Using PostgreSQL from the Command Line
covers how to use text commands at your computer’s command
prompt to connect to your database and run queries.
Chapter 19: Maintaining Your Database provides tips and
procedures for tracking the size of your database, customizing
settings, and backing up data.
Chapter 20: Telling Your Data’s Story provides guidelines for
generating ideas for analysis, vetting data, drawing sound
conclusions, and presenting your findings clearly.
Appendix: Additional PostgreSQL Resources lists software
and documentation to help you grow your skills.
Each chapter ends with a “Try It Yourself” section that contains
exercises to help you reinforce the topics you learned.
Ready? Let’s begin with Chapter 1, “Setting Up Your Coding
Environment.”
1
SETTING UP YOUR CODING
ENVIRONMENT
Let’s begin by installing the resources
you’ll need to complete the exercises in
the book. In this chapter, you’ll install a
text editor, download the example code
and data, and then install the PostgreSQL database
system and its companion graphical user interface,
pgAdmin. I’ll also tell you how to get help if you need
it. When you’re finished, your computer will have a
robust environment for you to learn how to analyze
data with SQL.
Avoid the temptation to skip ahead to the next chapter. My high
school teacher (clearly a fan of alliteration) used to tell us that
“proper planning prevents poor performance.” If you follow all the
steps in this chapter, you’ll avoid headaches later.
Our first task is to set up a text editor suitable for working with
data.
Installing a Text Editor
The source data you’ll add to a SQL database is typically stored in
multiple text files, often in a format called comma-separated values
(CSV). You’ll learn more about the CSV format in Chapter 5, in the
section “Working with Delimited Text Files,” but for now let’s make
sure you have a text editor that will let you open those files without
inadvertently harming the data.
Common business applications—word processors and spreadsheet
programs—tend to introduce styles or hidden characters into files
without asking, and that makes using them for data work
problematic, as data software expects data in precise formats. For
example, if you open a CSV file with Microsoft Excel, the program
will automatically alter some data to make it more human-readable;
it will assume, for example, that an item code of 3-09 is a date and
format it as 9-Mar. Text editors deal exclusively with plain text with no
embellishments such as formatting, and for that reason
programmers use them to edit files that hold source code, data, and
software configurations—all cases where you want your text to be
treated as text, and nothing more.
Any text editor should work for the book’s purposes, so if you have
a favorite, feel free to use it. Here are some I have used and
recommend. Except where noted, they are free and available for
macOS, Windows, and Linux.
Visual Studio Code by Microsoft: https://code.visualstudio.com/
Atom by GitHub: https://atom.io/
Sublime Text by Sublime HQ (free to evaluate but requires
purchase for continued use): https://www.sublimetext.com/
Notepad++ by author Don Ho (Windows only): https://notepad-
plus-plus.org/ (note that this is a different application than
Notepad.exe, which comes with Windows)
More advanced users who prefer to work in the command line may
want to use one of these two text editors, which are installed by
default in macOS and Linux:
vim by author Bram Moolenaar and the open source community:
https://www.vim.org/
GNU nano by author Chris Allegretta and the open source
community: https://www.nano-editor.org/
If you don’t have a text editor, download and install one and get
familiar with the basics of opening folders and working with files.
Next, let’s get the book’s example code and data.
Downloading Code and Data from GitHub
All of the code and data you’ll need for working through the book’s
exercises are available for download. To get it, follow these steps:
1. Visit the book’s page on the No Starch Press website at
https://nostarch.com/practical-sql-2nd-edition/.
2. On the page, click Download the code from GitHub to visit
the repository on https://github.com/ that holds the material.
3. On the Practical SQL 2nd Edition page at GitHub, you should see
a Code button. Click it, and then select Download ZIP to save
the ZIP file to your computer. Place it in a location where you can
easily find it, such as your desktop. (If you’re a GitHub user, you
can also clone or fork the repository.)
4. Unzip the file. You should then see a folder named practical-sql-
2-master that contains the various files and subfolders for the
book. Again, place this folder where you can easily find it.
NOTE
Windows users will need to provide permission for the
PostgreSQL database you will install to read and write to the
contents of the practical-sql-2-master folder. To do so, right-
click the folder, click Properties, and click the Security
tab. Click Edit and then Add. Type the name Everyone into
the object names box and click OK. Highlight Everyone in
the user list, select all boxes under Allow, and then click
Apply and OK.
Inside the practical-sql-2-master folder, for each chapter you’ll
find a subfolder named Chapter_XX (XX is the chapter number).
Inside subfolders, each chapter that includes code examples will also
have a file named Chapter_XX that ends with a .sql extension. This
is a SQL code file that you can open with your text editor or with the
PostgreSQL administrative tool you’ll install later in this chapter.
Note that in the book several code examples are truncated to save
space, but you’ll need the full listing from the .sql file to complete the
exercise. You’ll know an example is truncated when you see --snip--
in the listing.
The chapter folders also contain the public data you’ll use in the
exercises, stored in CSV and other text-based files. As noted, it’s fine
to view CSV files with a true text editor, but don’t open these files
with Excel or a word processor.
Now, with the prerequisites complete, let’s load the database
software.
Installing PostgreSQL and pgAdmin
In this section, you’ll install both the PostgreSQL database system
and a companion graphical administrative tool, pgAdmin. Think of
pgAdmin as a helpful visual workspace for managing your
PostgreSQL database. Its interface lets you see your database objects,
manage settings, import and export data, and write queries, which is
the code that retrieves data from your database.
One benefit of using PostgreSQL is that the open source
community has provided excellent guidelines that make it easy to get
PostgreSQL up and running. The following sections outline
installation for Windows, macOS, and Linux as of this writing, but
the steps might change as new versions of the software or operating
systems are released. Check the documentation noted in each section
as well as the GitHub repository with the book’s resources; I’ll
maintain files there with updates and answers to frequently asked
questions.
NOTE
I recommend you install the latest available version of
PostgreSQL for your operating system to ensure that it’s up-
to-date on security patches and new features. For this book,
I’ll assume you’re using version 11.0 or later.
Windows Installation
For Windows, I recommend using the installer provided by the
company EDB (formerly EnterpriseDB), which offers support and
services for PostgreSQL users. When you download the PostgreSQL
package bundle from EDB, you also get pgAdmin and Stack Builder,
which includes a few other tools you’ll use in this book and
throughout your SQL career.
To get the software, visit
https://www.postgresql.org/download/windows/ and click
Download the installer in the EDB section. This should lead to a
downloads page on the EDB site. Select the latest available 64-bit
Windows version of PostgreSQL unless you’re using an older PC with
32-bit Windows.
NOTE
The following section covers installation for Windows 10. If
you’re using Windows 11, please check the GitHub repository
with the book’s resources for notes about any adjustments to
these instructions.
After you download the installer, follow these steps to install
PostgreSQL, pgAdmin, and additional components:
1. Right-click the installer and select Run as administrator.
Answer Yes to the question about allowing the program to make
changes to your computer. The program will perform a setup task
and then present an initial welcome screen. Click through it.
2. Choose your installation directory, accepting the default.
3. On the Select Components screen, select the boxes to install
PostgreSQL Server, the pgAdmin tool, Stack Builder, and the
command line tools.
4. Choose the location to store data. You can choose the default,
which is in a data subdirectory in the PostgreSQL directory.
5. Choose a password. PostgreSQL is robust with security and
permissions. This password is for the default initial database
superuser account, which is called postgres.
6. Select the default port number where the server will listen. Unless
you have another database or application using it, use the default,
which should be 5432. You can substitute 5433 or another number if
you already have an application using the default port.
7. Select your locale. Using the default is fine. Then click through
the summary screen to begin the installation, which will take
several minutes.
8. When the installation is done, you’ll be asked whether you want
to launch EnterpriseDB’s Stack Builder to obtain additional
packages. Make sure the box is checked and click Finish.
9. When Stack Builder launches, choose the PostgreSQL installation
on the drop-down menu and click Next. A list of additional
applications should download.
10. Expand the Spatial Extensions menu and select the PostGIS
Bundle for the version of PostgreSQL you installed. You may see
more than one listed; if so, choose the newest version. Also,
expand the Add-ons, tools and utilities menu and select EDB
Language Pack, which installs support for programming
languages including Python. Click through several times; you’ll
need to wait while the installer downloads the additional
components.
11. When installation files have been downloaded, click Next to
install the language and PostGIS components. For PostGIS, you’ll
need to agree to the license terms; click through until you’re
asked to Choose Components. Make sure PostGIS and Create
spatial database are selected. Click Next, accept the default
install location, and click Next again.
12. Enter your database password when prompted and continue
through the prompts to install PostGIS.
13. Answer Yes when asked to register the PROJ_LIB and GDAL_DATA
environment variables. Also, answer Yes to the questions about
setting POSTGIS_ENABLED_DRIVERS and enabling the
POSTGIS_ENABLE_OUTDB_RASTERS environment variable. Finally, click
through the final Finish steps to complete the installation and
exit the installers. Depending on the version, you may be
prompted to restart your computer.
When finished, you should have two new folders in your Windows
Start menu: one for PostgreSQL and another for PostGIS.
If you’d like to get started right away, you can skip ahead to the
section “Working with pgAdmin.” Otherwise, follow the steps in the
next section to set environment variables for optional Python
language support. We cover using Python with PostgreSQL in
Chapter 17; you can wait until then to set up Python if you’d like to
move ahead now.
Configuring Python Language Support
In Chapter 17, you’ll learn how to use the Python programming
language with PostgreSQL. In the previous section, you installed the
EDB Language Pack, which provides Python support. Follow these
steps to add the location of the Language Pack files to your Windows
system’s environment variables:
1. Open the Windows Control Panel by clicking the Search icon on
the Windows taskbar, entering Control Panel, and then clicking
the Control Panel icon.
2. In the Control Panel app, enter Environment in the search box.
In the list of search results displayed, click Edit the System
Environment Variables. A System Properties dialog will
appear.
3. In the System Properties dialog, on the Advanced tab, click
Environment Variables. The dialog that opens has two
sections: User variables and System variables. In the System
variables section, if you don’t see a PATH variable, continue to step
a to create a new one. If you do see an existing PATH variable,
continue to step b to modify it.
a. If you don’t see PATH in the System variables section, click New
to open a New System Variable dialog, shown in Figure 1-1.
Figure 1-1: Creating a new PATH environment variable in Windows 10
In the Variable name box, enter PATH. In the Variable value
box, enter C:edblanguagepackv2Python-3.9.
(Instead of typing, you can click Browse Directory and
navigate to the directory in the Browse For Folder dialog.)
When you’ve either entered the path manually or browsed to
it, click OK on the dialog to close it.
b. If you do see an existing PATH variable in the System variables
section, highlight it and click Edit. In the list of variables that
displays, click New and enter
C:edblanguagepackv2Python-3.9. (Instead of typing,
you can click Browse Directory and navigate to the directory
in the Browse For Folder dialog.)
Once you’ve added the Language Pack path, highlight it in the
list of variables and click Move Up until the path is at the top
of the variables list. That way, PostgreSQL will find the correct
Python version if you have additional Python installations.
The result should look like the highlighted line in Figure 1-2.
Click OK to close the dialog.
Figure 1-2: Editing existing PATH environment variables in Windows 10
4. Finally, in the System variables section, click New. In the New
System Variable dialog, enter PYTHONHOME in the Variable
name box. In the Variable value box, enter
C:edblanguagepackv2Python-3.9. When you’re finished,
click OK in all dialogs to close them. Note that these Python path
settings will take effect the next time you restart your system.
If you experience any hiccups during the PostgreSQL install, check
the resources for the book, where I will note changes that occur as
the software is developed and can also answer questions. If you’re
unable to install PostGIS via Stack Builder, try downloading a
separate installer from the PostGIS site at
https://postgis.net/windows_downloads/ and consult the guides at
https://postgis.net/documentation/.
Now, you can move ahead to the section “Working with pgAdmin.”
macOS Installation
For macOS users, I recommend obtaining Postgres.app, an open
source macOS application that includes PostgreSQL as well as the
PostGIS extension and a few other goodies. Separately, you’ll need to
install the pgAdmin GUI and the Python language for use in
functions.
Installing Postgres.app and pgAdmin
Follow these steps:
1. Visit https://postgresapp.com/ and download the latest release
of the app. This will be a Disk Image file that ends in .dmg.
2. Double-click the .dmg file to open it, and then drag and drop the
app icon into your Applications folder.
3. In your Applications folder, double-click the app icon to launch
Postgres.app. (If you see a dialog that says the app cannot be
opened because the developer cannot be verified, click Cancel.
Then right-click the app icon and choose Open.) When
Postgres.app opens, click Initialize to create and start a
PostgreSQL database server.
A small elephant icon will appear in your menu bar to indicate that
you now have a database running. To set up the included PostgreSQL
command line tools so you’re able to use them in future, open your
Terminal application and run the following single line of code at the
prompt (you can copy the code as a single line from the Postgres.app
site at https://postgresapp.com/documentation/install.html):
sudo mkdir -p /etc/paths.d &&echo
/Applications/Postgres.app/Contents/Versions/latest/bin | sudo tee
/etc/paths.d/postgresapp
You may be prompted for the password you use to log in to your
Mac. Enter that. The commands should execute without providing
any output.
Next, because Postgres.app doesn’t include pgAdmin, follow these
steps to install pgAdmin:
1. Visit the pgAdmin site’s page for macOS downloads at
https://www.pgadmin.org/download/pgadmin-4-macos/.
2. Select the latest version and download the installer (look for a
Disk Image file that ends in .dmg).
3. Double-click the .dmg file, click through the prompt to accept the
terms, and then drag pgAdmin’s elephant app icon into your
Applications folder.
Installation on macOS is relatively simple, but if you encounter
any issues, review the documentation for Postgres.app at
https://postgresapp.com/documentation/ and for pgAdmin at
https://www.pgadmin.org/docs/.
Installing Python
In Chapter 17, you’ll learn how to use the Python programming
language with PostgreSQL. To use Python with Postgres.app, you
must install a specific version of the language even though macOS
comes with Python pre-installed (and you might have set up an
additional Python environment). To enable Postgres.app’s optional
Python language support, follow these steps:
1. Visit the official Python site at https://www.python.org/ and
click the Downloads menu.
2. In the list of releases, find and download the latest version of
Python 3.9. Choose the appropriate installer for your Mac’s
processor—an Intel chip on older Macs or Apple Silicon for newer
models. The download is an Apple software package file that ends
in .pkg.
3. Double-click the package file to install Python, clicking through
license agreements. Close the installer when finished.
Python requirements for Postgres.app may change over time.
Check its Python documentation at
https://postgresapp.com/documentation/plpython.html as well as
the resources for this book for updates.
You’re now ready to move ahead to the section “Working with
pgAdmin.”
Linux Installation
If you’re a Linux user, installing PostgreSQL becomes simultaneously
easy and difficult, which in my experience is very much the way it is
in the Linux universe. Most times you can accomplish an installation
with a few commands, but finding those commands requires some
Internet sleuth work. Thankfully, most popular Linux distributions—
including Ubuntu, Debian, and CentOS—bundle PostgreSQL in their
standard package. However, some distributions stay on top of
updates more than others, so there’s a chance the PostgreSQL you
have downloaded may not be the latest. The best path is to consult
your distribution’s documentation for the best way to install
PostgreSQL if it’s not already included or if you want to upgrade to a
more recent version.
Alternatively, the PostgreSQL project maintains complete up-to-
date package repositories for Red Hat variants, Debian, and Ubuntu.
Visit https://yum.postgresql.org/ and
https://wiki.postgresql.org/wiki/Apt for details. The packages
you’ll want to install include the client and server for PostgreSQL,
pgAdmin (if available), PostGIS, and PL/Python. The exact names of
these packages will vary according to your Linux distribution. You
might also need to manually start the PostgreSQL database server.
The pgAdmin app is rarely part of Linux distributions. To install it,
refer to the pgAdmin site at https://www.pgadmin.org/download/
for the latest instructions and to see whether your platform is
supported. If you’re feeling adventurous, you can find instructions on
building the app from source code at
https://www.pgadmin.org/download/pgadmin-4-source-code/.
Once finished, you can move ahead to the section “Working with
pgAdmin.”
Ubuntu Installation Example
To give you a sense of what a PostgreSQL Linux install looks like,
here are the steps I took to load PostgreSQL, pgAdmin, PostGIS, and
PL/Python on Ubuntu 21.04, codenamed Hirsute Hippo. It’s a
combination of the directions found at
https://wiki.postgresql.org/wiki/Apt plus the “Basic Server Setup”
section at https://help.ubuntu.com/community/PostgreSQL/. You
can follow along if you’re on Ubuntu.
Open your Terminal by pressing CTRL-ALT-T. Then, at the
prompt, enter the following lines to import a key for the PostgreSQL
APT repository:
sudo apt-get install curl ca-certificates gnupgcurl
https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
Next, run this single line to create the file
/etc/apt/sources.list.d/pgdg.list:
sudo sh -c 'echo "deb https://apt.postgresql.org/pub/repos/apt
$(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
Once that’s done, update the package lists and install PostgreSQL
and pgAdmin with the next two lines. Here, I installed PostgreSQL
13; you can choose a newer version if available.
sudo apt-get updatesudo apt-get install postgresql-13
You should now have PostgreSQL running. At the Terminal, enter
the next line, which allows you to log in to the server and connect as
the default postgres user to the postgres database using the psql
interactive terminal, which we’ll cover in depth in Chapter 18:
sudo -u postgres psql postgres
When psql launches, it displays version information as well as a
postgres=# prompt. Enter the following at the prompt to set a
password:
postgres=# password postgres
I also like to create a user account with a name that matches my
Ubuntu username. To do this, at the postgres=# prompt, enter the
following line, substituting your Ubuntu username where you see
anthony:
postgres=# CREATE USER anthony SUPERUSER;
Exit psql by entering q at the prompt. You should be back at your
Terminal prompt once again.
To install pgAdmin, first import a key for the repository:
curl https://www.pgadmin.org/static/packages_pgadmin_org.pub | sudo apt-
key add
Next, run this single line to create the file
/etc/apt/sources.list.d/pgadmin4.list and update package lists:
sudo sh -c 'echo "deb
https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/$(lsb_release -cs)
pgadmin4 main" > /etc/apt/sources.list.d/pgadmin4.list && apt update'
Then you can install pgAdmin 4:
sudo apt-get install pgadmin4-desktop
Finally, to install the PostGIS and PL/Python extensions, run the
following lines in your terminal (substituting the version numbers of
your PostgreSQL version):
sudo apt install postgresql-13-postgis-3sudo apt install postgresql-
Other documents randomly have
different content
Neck and Throat.
Body and Back.
Fore Legs and Front Feet.
driving and handling.
Then give a thought to the glands while here. Enlarged glands
may indicate some scrofulous or glanderous condition of the system.
—A beautiful neck and throat is an absolute
beauty in the horse or cow. The skin should be thin, mellow, and
soft, and the hair not over thick nor coarse. Look for poll-evil at the
top of the neck and head. See if swellings, lumps or hard places are
to be found at the sides of the neck, or underneath joining the
throat. I have found such very frequent with dairy cattle; and cases
are not unusual with horses.
Frequently scars are to be found on the sides or bottom of the
neck. These may be due to scratches caused by nails, barb-wire or
some similar accident, and again they may have been caused by
sores, tumors, or other bad quality of the blood.
—Passing the side, look over the withers for galls
or fistulæ, the shoulders for tumors, collar puffs, and swellings.
Observe at the same time if there is any wasting of the muscles on
the outside along the shoulder.
Now the back. Is it right as to shape? Do you find any evidence of
sores or tumors? Look for these along the sides and belly. Now stoop
a bit and look under; do you find anything different from what is
natural? In males look for tumor or disease of the penis; do the
same with the scrotum, and, in case of geldings scrutinize carefully
to see if they be ridgelings.
While making this examination, if the animal is nervous and
fretful, you can help matters along if an assistant holds up a fore
leg. Take the same precaution when examining the hind quarters
and legs. By doing so, you will avoid being kicked and can run over
the parts more quickly and satisfactorily.
Before leaving the body observe if the hips are equally developed,
and the animal evenly balanced in this region. Both horses and cattle
are liable to hip injury, one of the hips being frequently knocked
down. Make sure that both are sound and natural.
—Now step to the front again for a
careful examination of the front legs and feet. Starting with the
elbow, examine for capped elbow; now the knee. It should be wide,
ANATOMY OF THE
FOOT
Examine for Corns.
Hind Legs and Feet.
long, and deep, and at the same time free from any bony
enlargements. The knees must stand strong, too. Is the leg straight?
Do you observe any tendency of the knee to lean forward out of line,
showing or indicating a “knee sprung” condition? Just below the
knee, do you find any cuts or bunches or scars due to interference
of the other foot in travel? Look here also for splints; follow along
with the fingers to see if splints are present—on the inside of the
leg.
Be particular about the cannon. The front should be smooth—you
want no bunches or scars. Just above the fetlock feel for wind puffs;
and note if about the fetlock and pastern joints there are any
indications of either ringbones, bunches, or puffs. Now look for side
bones; if present, you will find them just at the top of the hoof. They
may be on either side. Sidebones are objectionable, and are the
lateral cartilages changed into a bony structure.
Give the foot considerable attention. The
old law of the ancients, “no feet, no horse,”
is certainly true in our day. You can overlook
many other imperfections and troubles in
the horse, but if the feet are bad you do not
have much of a horse. A good foot is well
shaped, with a healthy-looking hoof and no
indication of disease either now or ever
before.
See that the shape is agreeable. A
concave wall is not to be desired, and the
heels are not to be contracted. The wall
should be perfect—no sand cracks, quarter
crack, or softening of the wall at the toe of
the foot.
—These are both
troublesome and cause much lameness. A
healthy frog, uninjured by the knife or the
blacksmith or other cause is very much to
be preferred.
The delicate nature of
the foot is readily
recognized when the
various parts are
considered in their
relation to each other.
—In examining these regions give the hocks
of the horse special attention. No defect is
more serious than bone spavin. You can, as
a rule, detect this by standing in front of the
horse just a little to the side. If there is any
question about the matter, step around to
the other side and view the opposite leg. This comparison will let
you out of the difficulty, as it is very unusual that this defect should
be upon both legs at the same point and developed to the same
degree.
A spavin is undesirable for the reason that it often produces
serious lameness, which frequently is permanent. As it is a bone
enlargement, it is something that cannot be remedied. If you are
seeking good horses, better reject such as have any spavin defect.
In this same region between the hock and the fetlock curbs
troubles are located. They appear at the lower part of the hock,
directly behind. You can readily detect any enlargement if you will
step back five or six feet. The curb, while it may not produce
lameness, is altogether undesirable. It looks bad; it shows a
weakness in the hock region and often is caused by overwork,
consequently the animal with curb disease is one that has not
measured up to the work demanded of him.
Just above and to the rear of the hock the thorough-pin disease
appears, and just in front of and slightly toward the inner side of the
hock bog spavin is sometimes to be found. Lameness may come
from either of these diseases. Small tumors, puffs and other defects
frequently show themselves on the hind legs and the best way is to
reject animals having them. While some of these may be caused by
accident, the most of them are the result of bad conformation, due
to heredity, unimproved blood and bad ancestors.
EXAMINING FOR LAMENESS
Lameness comes from many causes; maybe from soreness, from
disease or from wounds. And lameness is hard to detect. Frequently
it seems to be in the shoulder, when in fact it is a puncture in the
foot. Again it may seem to be in the fetlock, but the trouble is in the
shoulder or fore leg. You must examine for lameness both in the
stable and out of the stable. If you find the horse standing squarely
upon three feet and resting the fourth foot, you should be
suspicious. If you move the horse about and he assumes the same
attitude again and still again, you can be certain that he is assuming
that position because he wants to rest some part of that member.
In testing out the horse for lameness, let no excitement prevail.
Under such excitement the horse forgets his lameness or soreness
for the time being, and you do not note the trouble. A quiet, slow
walk or trot on as hard a road as possible is a desirable sort of
examination to give.
TESTING THE WIND
The free breathing of a horse may be interfered with, and for two
reasons. Roaring or whistling, as it is called, is a serious disease of
the throat, and, at the same time, an incurable disease. The second
disease is known as heaves or bellows, and is also a most serious
disease, because it is also incurable. By the use of drugs relief may
be given temporarily, but no permanent cure follows. Unscrupulous
dealers will resort to dosing for the time being, or until a sale is
made.
You should guard against this trouble, however, for it is one of the
most serious that a horse can have. Upon this subject, Butler has
the following to say: “To test the wind and look for two serious
conditions and others which may be present, the animal should be
made to run at the top of his speed for some considerable distance
—a couple hundred yards or more. Practically this run or gallop
should be up hill, which will make the test all the better. After giving
the horse this gallop, stop him suddenly, step closely up to him and
listen to any unusual noise, indicating obstruction of the air
passages, and also observe the movements of the flanks for any
evidence of the big double jerky expulsion of the air from the lungs
characteristic of heavers.”
TESTING OF THE PACES
No examination is complete that does not make a test of the
paces. You want to know how fast the horse can walk, how he trots
or paces or how he takes some other gait. Some horses make these
movements very gracefully; others very unmannerly. A well-acting
horse is one that moves smoothly, regularly, who picks up his feet
actively and who places them firmly in their position regardless of
the ground or gait. Some horses have a rolling movement of the
legs. Avoid these. Others step on the toe or heel. These, too, should
be avoided. They suggest some defect or bad conformation.
The testing of the paces brings all parts of the body into play and
assists in catching other blemishes or defects that you may have
overlooked in your previous examination. It gives you another
opportunity to examine the wind, to observe the respiration, the
heart beatings, the condition of the nostril after work; it shows you
also how the animal takes his pace and how he stands. All of this
will be of value as indicating the soundness and health of the
individual under observation.
CONSIDERING FOR A SPECIAL PURPOSE
Now, as a last factor of your examination, consider the uses to
which the animal is put. If you are looking for breeding animals be
sure to know that the udder is not injured. Of what use is a cow with
a bad udder? How often do we find a quarter of the udder destroyed
or a teat cut or so badly mangled as to be of little use! Some udders
are dead, heavy, fleshy; some are diseased, lumpy; and even though
the animal is otherwise good you must reject her.
If the udder is good, superior in many respects, and shows great
milk production, you can often afford to overlook other defects,
especially if the result of accident.
In the case of horses, a disease or blemish due to accident may
be overlooked, if the work to which the animal will be subjected
does not interfere, let us say, for breeding purposes. The horse has
good conformation, good quality, is healthy and very superior, but
unfortunately a leg was broken. Shall she be rejected as a breeder?
No heavy work will be required of her—she is wanted for colt raising.
Take her; of course you will pay less for her. This accident interferes
in no way with her value for breeding purposes. Many cases of
accidental injuries are similar to this example among cattle and
horses.
A good rule is to reject those having defects or blemishes that
interfere with functional activity or the work to which you wish to put
them. Then, as breeders, reject all with constitutional defects, as
bad feet, narrow hocks, coarse disease-appearing bones, and bad
conformation and scrubby character.
FRACTURES
When a bone is
broken into two or more
parts it is said to be
fractured. These may be
straight across, up and
down, or oblique.
Ordinary fractures are
easily treated by splints,
but sometimes fractures
are so serious as to
CHAPTER V
Wounds and Their Treatment
The stockman has all sorts of wounds
with which to deal. He may guard his
animals with the care and caution of a
mother and still find constant bother and
worry to face in the daily management of
his stock. Today it may be a wound caused
by a nail puncture in the foot; tomorrow a
cut occasioned by a fence; and then almost
immediately another, the result of a kick or a
hook; with patience nearly exhausted, now
follow bruises of many sorts and
unexplainable lacerations.
These troubles occur on the best
managed farms. There is but one thing to
do: meet each case as it occurs and lend
such assistance as you can that nature may
repair the wrecked tissue at the earliest
possible moment.
THE KINDS OF WOUNDS
Wounds fall into four classes: the clean-
cut kind made by something sharp; the torn
or lacerated, where ragged edges are left;
the bruised, the result of continued pressure
or kicks or a knock; and the punctured, like
the entrance of a nail or splinter or gunshot.
destroy the value of the
animal.
The latter class is the most difficult in
treating, for the reason of the greater
penetration that may likely occur. In the
case of gunshot, the wound may be on the surface, or it may extend
entirely through the region attacked, or even penetrate some vital
organ like the heart or the lungs or bowels, and either immediately
or within a few days be the cause of death. Fortunately such wounds
are rare. The stockman may never have to deal with them at all.
There are punctured wounds that are common, however; some,
indeed, frequently lead to death. A nail wound is the most serious,
perhaps. It is likely that more cases of tetanus or lockjaw are due to
nail punctures than to all others combined.
After this class comes the lacerated kind. These heal slowly; the
tissue being torn and bruised is repaired only through the sloughing
off of the injured and now superfluous parts. As a result, even with
the most attentive surgical help, the injured part develops its
exposed sore, ending finally completely healed, but permanently
marked. Bruises may be equally bad, long delayed in healing and
very painful. Do you remember the stone bruises of boyhood days?
How long it required to develop! And the pain! I shall feel mine for
ages to come.
The clean-cut wounds, if not too serious, are the least difficult in
treating.
FIRST STEP IN TREATING
The flow of blood is usually associated with ordinary wounds;
other than with some bruised and punctured wounds this is always
true. Frequently a nail puncture gives off no blood or it is not
noticed. However, the blood is present, for, from the very nature of
the trouble, blood rushes to the seat, this being nature’s way of
repair. Your first step, therefore, is to check the excessive blood flow.
If left to itself the blood might do it. Blood has the trick of
coagulating or clotting; and this in time will check the flow. But you
can assist in forming the clot very simply by applying some finely
ground material that the blood may be held on the spot. Absorbent
BANDAGING A LEG
The method of applying the
bandage is shown here. The
bandage may be wrapped
directly over the hair or over
cotton saturated with an
antiseptic and placed over the
wound.
Cleansing the Wound.
Making the Bandage.
cotton is the best material to use. In
case this is not available, use
something of like nature—something
that is clean, not stored up with
germs. Tea is good, as is flour also.
Cold water acts favorably, and for the
slight, ordinary surface wounds water
is usually sufficient. A few drops of
some antiseptic in the water, if
available, is always advisable, for the
freshest water carries its full quota of
germs, some of which may cause
trouble. A tiny bit of alum powder will
be found both effective and not
painful.
—After the
flow of blood has been stopped,
cleansing the wound is next in order.
All dirt should be carefully removed,
the injured flesh cleansed, the torn
tissues brought together and stitched,
if need be, and antiseptics applied.
The water used in bathing the
wounded flesh should contain an
antiseptic, that the germs present may
be destroyed and no live ones
admitted by water in cleansing the wound. Any good commercial
antiseptic will do; or the old common ones, like corrosive sublimate,
one part in a thousand parts of water, or carbolic acid, a teaspoonful
in a quart of water. Some powdered antiseptic like iodoform is very
desirable for dusting into the wound.
—Unless the wound is of little
consequence it should be covered and bandaged that no foreign
elements be admitted and that some pressure may be given to keep
the broken parts together. To secure this effect absorbent cotton,
Special Treatment.
slightly moistened with the antiseptic, should be laid on the wound,
and firmly fastened by strips of clean cotton cloth.
By winding this bandage around and about the wound, dressed in
this careful way, the wound will be protected, germs will be kept out
and nature, thus reinforced, will be enabled to make a rapid
recovery. Unless the bandage is disturbed in some way there is no
need of changing it under twenty-four or thirty-six hours. If, for any
reason, the bandage is displaced, dress as before, and bandage
again.
—When a cut wound is deep or large,
stitching is sometimes required, that the broken parts may be
brought together for more rapid healing. Nothing is better for this
than a coarse needle and heavy thread. Before stitching, however,
the wound should be bathed as previously described. The needle
and thread should be soaked in the antiseptic, that no germs may be
introduced by means of them.
Now you are ready to make the stitches. Place the needle about
an eighth to a quarter of an inch from the edge of the wound across
to the opposite side. Bring the two ends together and tie, leaving
the lips of the wound as close together as possible. If more than a
single stitch is necessary, proceed in the same way, placing the
second stitch about three-quarters of an inch from the first one;
continue as with the first stitch if more are necessary.
In case a needle and thread are not available, pins may be used in
the emergency. Insert the pin through the two edges and bring the
lips together, making them fast by a thread or cord carried from one
end to the other several times, alternating to the right and left as
presented by the figure eight. Sometimes the wound enlarges and
becomes feverish. If such becomes very severe, remove the
fastenings and bathe the wound very gently, using a mild antiseptic
wash of tepid water in which carbolic acid has been placed.
HEALTH AND DISEASE
In the upper picture the pigs are treating
themselves. Below are shown hogs which died
during shipment to market.
Avoid any breaking of the healing tissue and do not have the
washing solution too strong, else it may injure the delicate tissue
growth. A teaspoonful of carbolic acid to a quart of water is strong
enough. With lacerated wounds the treatment is very similar. If the
wound goes bad and becomes spongy add a tablespoonful of
Nail Punctures.
acetate of lead and a tablespoonful of sulphate of zinc to the
antiseptic solution and apply twice daily.
MAKING POST MORTEM EXAMINATIONS
The upper right hand picture shows the
intestines of a healthy sheep. On the left nodule
disease is discovered. The bottom picture illustrates
how a carcass may be opened for the examination.
—These very frequently cause trouble. You have
no way of observing the wound and your only way of judging is from
the way the animal walks or acts, and if the hoof is unduly hot.
Locating lameness in the stifle joint is a common but inexcusable
error, as the action resulting from lameness in the two parts is
entirely different. The so-called gravel which is said to enter the sole
of the foot and then to work out at the heel is usually the working
out of the pus or the matter resulting from a nail puncture or a
bruise.
If an animal becomes suddenly and severely lame and there be no
evidence of any injury to any other part of the leg, such as swelling,
heat and pain upon pressure, it is always well to look for puncture in
the foot. If the animal stands with the lame foot extended and when
walking places the lame foot well forward and brings the well foot up
to it, the evidence of puncture is still stronger.
To examine the foot properly the shoe should be removed. It is
not sufficient to merely scrape the bottom of the foot clean, for if the
nail has pulled out and the horn sprung back in position, all trace of
its entrance may have been obliterated. To examine the foot
properly, tap the hoof with a hammer or knife and the exact spot
may be definitely located. If the injury is of a few days’ standing,
additional heat in the hoof and, perhaps, slight swelling of the
coronet may also be present.
In treating such wounds, pare away only such parts of the hoof as
necessity requires and introduce a bit of cotton cloth rolled as a
string by means of a probe of some kind. Both probe and cotton
must be treated with the antiseptic solution. This solution should be
a little stronger than for flesh wounds. Make the solution by using a
teaspoonful of carbolic acid to only a pint of water. After the cotton
has been inserted a few times and withdrawn, each time a fresh
cord being used and fully saturated, leave the last one in for a few
hours and then repeat the treatment. This should be done three or
four times each day.
The main point in the treatment of nail puncture of the foot is to
provide free exit to all matter that may collect and keep the parts as
clean as possible. If this be done, the matter will not be compelled
to work out at the heels, and no separation or loss of hoof will occur.
Often a very severe wound is made and the treatment acts slowly.
Treating Bruises.
Leg Wounds.
Maggots in Wounds.
In case proud flesh accumulates, it should be burned away by a
hot iron. After this operation has been performed, the cavity should
be filled with balsam of fir and cotton placed over it, a piece of
heavy leather fitted to the foot and held fast by the replaced shoe.
This will usually end the difficulty. A veterinarian should be called in
case the wound is severe or goes bad as the treatment progresses.
—In treating bruises a different procedure is
necessary. The broken tissue is concealed—beneath the skin and
usually under the surface muscles. Bathing with water and acetate
of lead—a quart of water and two tablespoonfuls of the acetate—will
tend to lessen the inflammation. In time you may have to open the
swelling for the pus to get out. After doing so, inject some wash for
cleansing, using one quart of water and a tablespoonful of chloride
of zinc.
If the swelling remains, apply twice each month a salve made by
using one teaspoonful of biniodide of mercury and three
tablespoonfuls of lard. Wash occasionally, using the chloride of zinc
solution.
—Cleanse the wound with a wash composed of one
tablespoonful of acetate of lead, one tablespoonful of sulphate of
zinc, four tablespoonfuls of tincture of arnica and one quart of water.
Use this wash frequently, every hour or so, during the first day. After
that three or four applications will be sufficient. The sore should be
kept lower than the skin during the healing process. If it tends to
crowd up, apply a tiny bit—as much as you can place on a one-cent
piece—of bichloride of mercury. This will assist in getting an even
heal and the skin will grow over, leaving no blemish or swelling.
—If the wound has been treated as
suggested above there is no possibility of any trouble from maggots.
These come from a lack of cleanliness and neglect. Of course, an
animal often gets a wound and the owner is not aware of the
mishap. Wounds, more or less infrequently treated, those made as
the result of castration, occasionally get infected with maggots.
When, for any cause, maggots are present, they must be got rid
of at once. A good plan is to use chloroform, either by spraying or by
throwing it in the wound in small drops from a sponge.
The danger from maggots can usually be avoided if a mixture
composed of one tablespoonful of turpentine, three tablespoonfuls
of tar and two tablespoonfuls of lard or fish oil be smeared all
around the border of the wound.
CHAPTER VI
Making a Post Mortem Examination
Even on the best-managed stock farms some animals do get sick
and die. Good care and good nursing may be given, but the sick
animal frequently does not recover—death often follows very quickly,
before you have an opportunity to observe the development of the
disease or to secure the services of a veterinarian. Then, again, after
a lingering sickness an animal dies, the disease being known or
unknown as the case may be.
In any event, a post-mortem examination is usually desirable, if
for no other reason than that it serves to familiarize you with the
organs of the body. With a little experience you can become quite
proficient in examining a dead animal, and you can soon learn the
difference between healthy and unhealthy organs, between diseased
and normal tissues and the relation of the internal parts to the whole
body. A post-mortem examination thus enables you to know the
cause of the disease—where it is located or whether death is the
result of accident or of some fatal disturbance of the system.
This examination should be made as soon after death as possible;
the longer the delay the greater the changes due to decomposition
of the body and its decay back to the original elements from which it
has come. Soon after death the stiffening process takes place. This
is known as rigor mortis. It may occur within an hour after death
and again it may not be complete until twenty-five or thirty hours
have passed. Soon after the death stiffening has occurred the
tissues soften and decomposition rapidly follows.
FIRST THINGS TO DO
In making a post-mortem examination, in case the animal has not
been moved, the position of the body is to be observed. Look all
about you. Is there any evidence of a struggle? Does either the body
or the ground appear as if spasms have taken place? It may be a
case of poisoning. If such be true, the outward appearance may be
further substantiated by the internal condition. If inflammation and
irritation of the stomach and bowels are observed, this evidence
helps to confirm the first observation.
RICKETS IN PIGS
Rickets in pigs is due, as in man and other
animals, to an improper development of the
bone, the result of insufficient mineral matter in
the food. The bones are weak and bend or
break. It frequently appears after the pigs are
weaned. An abundant supply of wood ashes,
charcoal, lime and salt is always good for hogs.
The appearance of the struggle, however, is not enough to
establish a case of poisoning; for struggling is a death characteristic
Observe the Discharges.
Accidents and Injury.
After Removing the Skin.
of many diseases. Of course, in making this preliminary examination
you will note if death could have been the result of some other
reason. Has some obstruction had anything to do with the trouble?
Maybe the animal has been caught in some way and not being able
to move about has starved to death, or maybe some over-exertion
has had something to do with the trouble.
Many animals choke, and, not being able to relieve themselves,
die. Thousands of farm animals, especially in the West and
Southwest, die annually from cold, and not a few from heat. All
these things enter into the case and must be considered in reaching
a reasonable conclusion.
—The next thing to do is to observe
the discharges from nose, mouth and other natural openings of the
body. External scars and wounds often bear a close relation to the
disease and these should be considered in examining the carcass.
How do the eyes look? Is there a discharge from the ears? Is the
swelling of the abdomen and the bloating more pronounced or
different than should be the case in ordinary death? Practice will
indicate the lesson that each of these teach.
—Farm animals are often killed by stray
shots from the guns of hunters and trespassers. A casual
observation will indicate if death has been due to this. Again,
animals may die from distemper or be eaten up with lice or troubled
with itch or mange—you will note these facts as you go along with
your work.
In the South, where Texas fever is so prevalent, you should look
for ticks, as these bring death to thousands of animals each year.
Look for the wee tiny ones—they cause the trouble. When cattle are
fairly covered with the large ticks death does not ordinarily follow,
since the animal has practically become immune to the poison
caused by the tick. These large ticks, however, are filled with blood
and nutriment, both obtained from the animal, and hence they may
rob the animal of blood and nutriment that it ought to have itself.
—The skin is now to be removed, so
that the color of the tissues and the nature of the blood may be
noted. If the blood be thin or black, with a disagreeable odor, you
can expect some germ trouble like blood poisoning or an infectious
and contagious disease. If the white tissues are yellow you may be
reasonably certain that the liver has not done its work as it would
have done had it been in a thoroughly healthy condition.
In removing the skin and making other observations be cautious
that you do not prick your fingers with the knife, since you may
convey in this way disease to yourself. If by accident a cut or prick is
made, cauterize the wound at once, so as to destroy any germs
transmitted in this way to you.
EXAMINING THE INTERNAL ORGANS
The next step is to examine the internal organs. To do this, place
the animal on its side, remove the upper front leg and the ribs over
the chest region. The ribs should be removed as near as possible to
the backbone so as to give an unobstructed opening over the
important organs. This large opening now allows you free access for
examination, and an unimpaired view all about the vital organs, if
these are entirely exposed.
ROUND WORMS IN HOG INTESTINE
An infestation with intestinal worms, as shown here, leads to
unthriftiness and a loss of flesh. These worms may be expelled by
Stomach and Intestines.
Kidneys and Bladder.
Lungs.
giving turpentine in doses of one teaspoonful in milk for three days
in succession.
While making this opening, observe the watery fluid as it escapes.
If a large quantity is present, dropsy or a rupture of the bladder is
indicated. If the trouble is due to the latter, an odor in the urine will
be quickly noted. When the fluid is red in color, it indicates the
presence of blood or some inflammation of the abdomen or the
bowels. A large amount of watery fluid in the chest cavity is an
indication of some lung trouble; this is further indicated by the tiny
attachments running between the lungs and the chest wall.
—If the stomach and intestines be
abnormally red, congestion is indicated, and if they be quite dark,
even purple in color, you may be sure that some kind of
inflammation has been the trouble. You will note also if the stomach
is hard and compacted; and, if so, indigestion may have been the
trouble. The intestines will also show if they be hard and compacted
or in any otherwise bad condition. Pass the hands along to see if the
intestines are knotted in any place or if nails are present in the
stomach. It is not likely that the nails have been the direct cause of
death, but this fact helps to indicate the condition of the digestion
trap.
Often hair balls or parasites will be found; either may clog up the
channel and may be the immediate cause of death. I have on more
than one occasion found that the fuzz of crimson clover,
accumulating in the intestines of horses, rolls up into a hard,
compacted ball, and not being able to pass out, becomes an
obstruction in the passageway and ultimately causes death.
—The urine tells its tale also; a very
disagreeable odor indicates some disturbance; and a brownish or
dark-red color may indicate a local disease or a constitutional
breakdown. Texas fever in cattle produces a very dark or reddish
urine, Azoturia in horses, a similar color. Gallstones or gravel are
often found in the bladder, and these frequently cause serious
disturbance, if not death.
Other Observations.
—Look the lungs over carefully. See if the natural color is present
and if the soft, spongy constituency responds to the same kind of
touch as does the thoroughly healthy lung. In health the lungs are a
very light pink color. If inflammation has been present this will be
indicated by the dark color and the hard density.
When the lung is cut apart with the knife further observation
should be made. A marble appearance indicates inflammation and
hard lumps or tubercles indicate tuberculosis. These tubercles, when
cut open, show pus and a cheeselike material, yellow in color—a
true indication of the disease.
—You should feel the heart to know if it is
natural or not, or to see if any of the valves are broken, or if some
inflammation has been back of the trouble. The sides of the open
cavity should be observed before leaving. Is it spotted, speckled?
Are pink spots seen about the ribs? This is an indication of hog
cholera, and in itself may lead to a correct interpretation of the
disease.
CHAPTER VII
Common Medicines and Their Actions
The common medicines used in treating farm animals are named
in the following list, together with origin, action, use, and dose.
ACONITE
Tincture of aconite is derived from the root of a plant. When used,
the heart beats more slowly and the blood pressure is decreased,
making the medicine desirable in cases of inflammation.
Dose: For horses and cattle, from 10 to 30 drops, and sheep and
hogs 5 to 10 drops.
ALOES
This is usually bought in a powder form. It is brown in color and
bitter in taste. Considerable time transpires before action in the
bowels takes place. Allow at least 24 hours. It is a physic and blood
purifier.
Dose: For horses, 4 to 5 tablespoonfuls; cattle, 4 to 8
tablespoonfuls; sheep, 1 to 2 tablespoonfuls; and pigs, 1 to 2
tablespoonfuls.
ALUM
This mineral salt is used in washes for sore mouth and throat, and
cleansing wounds. It may be dusted into wounds in powder form,
and is both drying and healing.
Dose: Use a tablespoonful to a pint of water.
ANISEED
This preparation is made from dried berries and ground. It
stimulates digestion, sweetens the stomach, and serves as a tonic
and appetite maker.
Dose: For horses and cattle, a tablespoonful, and for sheep and
pigs, a teaspoonful.
ARNICA
For wounds, sprains, and bruises, tincture of arnica is both cooling
and restful. It is made from the dried flowers of a plant, and is for
external use. Apply three or four times daily.
ARSENIC
This medicine comes from the mineral kingdom and is very
powerful. In using better get it in some standard medicinal form
such as Fowler’s Solution. It is used as a tonic when the stomach is
bad and the system run down.
Dose: Fowler’s Solution; for horses and cattle, 2 tablespoonfuls;
sheep, 1 teaspoonful; pigs, one-half teaspoonful. In giving to stock
mix with 4 tablespoonfuls of whiskey, and either use as a drench or
add to mash or gruel.
BELLADONNA
This is a tincture made from a plant. When used it soothes,
softens, and relaxes the parts to which applied. It checks
inflammation and relieves pain, but must be carefully used.
Dose: For horses and cattle, 1 teaspoonful; sheep, 10 drops; pigs,
5 drops.
BUTTER OF ANTIMONY
This preparation, taken from a mineral, is not used internally. It is
a powerful caustic. Its principal use is for curing thrush in horses’
feet.
TETANUS BACILLI
How the germs look under the microscope. The
poison produced by them is one of the most
violent known in disease.
BROMIDE OF POTASSIUM
This comes as a white crystal or powder, and is used to quiet the
nerves when some trouble like lockjaw has set in.
Dose: For horses and cattle, 1 teaspoonful; sheep and hogs, one-
half teaspoonful.
BINIODIDE OF MERCURY
This bright red powder is used chiefly for blistering purposes. It is
excellent when a spavin or splint or ringbone is just beginning. In
preparing, use one part of the mercury to nine parts of vaseline or
lard. Remember, it is a poison, and must be carefully handled, as is
true of some other preparations of mercury.
CAMPHOR
The camphor of commerce is in the form of a gum obtained from
a tree by boiling and evaporation. It is used in mixtures for coughs,
sore throat, and heaves. It is good also for colic and diarrhœa and
assists in lessening pain. It should be given in water.
Dose: For horses, 2 to 4 teaspoonfuls; cattle, 4 to 5 teaspoonfuls;
pigs and sheep, 2 teaspoonfuls.
CANTHARIDES OR SPANISH FLY
This is in the form of powder, and is an irritant. For use it should
be thoroughly mixed with lard or vaseline. One teaspoonful of the
cantharides to 4 tablespoonfuls of lard or vaseline. When so
prepared it is excellent as a blister. It can be applied for sweat
thickenings or lumps on any part of the body that is not on the
bone. It should not be used on curbs or tumors and is not used
internally.
CARBOLIC ACID
This is got from coal tar and petroleum. When full strength and
pure it is in the form of crystals, but is generally bought as a liquid.
It is a disinfectant and an antiseptic, and while used internally for
some purposes, is largely used internally in washes and solutions. Its
principal use is in bathing wounds and sores. Care should be taken
not to have a wash contain too much of the acid, as it will burn the
wound and stop the healing action. It is a corroding poison taken
internally. It should be just strong enough to kill bacteria; say, 1 part
to 1,000 parts of water. A very good healing salve is made when 5
drops of pure carbolic acid is used to 4 tablespoonfuls of vaseline.
CORROSIVE SUBLIMATE
This is used externally as an antiseptic and disinfectant. Dissolve 1
part to 100 parts of water. It is a preparation of mercury, is
poisonous, but excellent for bathing wounds and open sores.
CASTOR OIL
This oil is pressed from castor beans. It is a mild physic similar to
raw linseed oil. It is not used much for live stock.
Dose: For horses and cattle, 1 pint; for sheep, one-quarter pint,
and for pigs, 4 tablespoonfuls.
CALOMEL
This is a heavy white powder and a mineral. Its principal action is
as a physic, and it has a cleansing effect on the liver. Hence it is
used for all kinds of liver troubles. When dusted in old sores, it is
splendid for healing and drying up.
Dose: For horses, one-half to 1 teaspoonful; cattle, 1 to 2
teaspoonfuls; sheep and pigs, one-eighth teaspoonful.
CROTON OIL
This oil is made from seeds, and is one of the most powerful
physics known. It should never be used until milder physics do not
respond. Use it as a last resort.
Dose: For horses, 15 to 20 drops; cattle, 30 to 40 drops; sheep, 5
to 10 drops; and pigs, 2 to 3 drops. In giving, it is best to use in
connection with raw linseed oil; of the linseed oil use 1 pint for
horses and cattle and one-quarter pint for sheep and pigs.
CAUSTIC POTASH
This chemical is most easily used when purchased in pencil-like
sticks. It is never given internally, but is used to burn warts and
growths by wetting the stick and rubbing it over them. It is also
used for burning poisonous wounds to kill the poison. It is commonly
employed for dishorning calves. When a week or ten days old, and
the button of the horn is just appearing, rub the potash over the
horn. This usually insures destruction of the horn substance. Wet the
stick of potash. See that drippings do not run down the animal’s
head. In order to protect the fingers, when using, wrap paper
around the stick.
CREOLIN
This is the product of coal tar and comes in the form of a thick,
dark fluid, and, like tar, is harmless. It is frequently used as the basis
of salves for wounds, scratches, and like troubles. It is a very
effective remedy for killing lice, ticks, or fleas, and is used as a
remedy when sheep are afflicted with mange and scab.
Dose: Use from 2 to 4 tablespoonfuls to a pint of water and shake
well before using. Make up a small quantity at a time, as creolin thus
made loses its value after exposure. For disinfecting purposes, 1 part
of creolin to 100 parts of water is satisfactory.
GENTIAN
This is the root of a plant, dried and ground. It is used principally
as a tonic, and is very bitter; commonly found in condition powders
and is given to animals that are weak and run down. If used alone,
give twice a day in the food and place on the tongue with a spoon.
Dose: For horses and cattle, 1 tablespoonful; for sheep, a
teaspoonful; pigs, one-half teaspoonful.
GINGER
This is a dried root ground fine, secured from a plant, and acts as
a stimulant, relieving gases that accumulate in the stomach. It is an
excellent ingredient to use in colic and indigestion preparations. If
given alone, doses may be repeated every two or three hours.
Dose: For horses and cattle, 1 tablespoonful; sheep, 1 small
teaspoonful; pigs, one-half teaspoonful.
HYPOSULPHITE OF SODA
This salt is frequently used in combination with gentian, equal
parts of both, and in other recipes for condition powder. It cleans the
blood and builds up the system after weakening diseases. A common
preparation is made by using one-half of powdered gentian and one-
half of hyposulphite of soda. Mix all together and give two or three
times a day to the animal needing it.
Dose: For horses and cattle, 1 tablespoonful; sheep, 1
teaspoonful; pigs, one-half teaspoonful.
IODINE
This dark brown tincture is not often used internally, but is used as
a sweat blister and for blistering thickened glands. In using, take a
feather, painting the iodine on the lump until it blisters; when the
blister appears, grease the part; after two or three days have
passed, wash the lump with warm water and soap and blister again.
IODIDE OF POTASSIUM
This white powder is obtained from the mineral kingdom. When
given internally it acts as an absorbent. It is commonly used in cases
of dropsy of the belly. In administering, use equal parts of ground
gentian root and give twice a day.
Dose: For horses and cattle a teaspoonful; for sheep and pigs,
one-half teaspoonful.
LINSEED OIL
This oil is obtained from flaxseed, and is excellent when a mild
physic is desired. The easiest and most effective way of giving to
animals is in the form of a drench. About 1 pint should be used for
horses and cattle. Raw linseed oil is usually preferred to the boiled.
LAUDANUM
This is made from opium and is used both internally and
externally. It is commonly used where there is pain, hence it is
excellent for relieving pain and spasms and assists also in checking
inflammation.
Dose: For horses and cattle, 4 to 6 teaspoonfuls; sheep and pigs,
2 to 4 teaspoonfuls.
NUX VOMICA
This powder comes from ground seeds, and is used as a nerve
stimulant. It is very efficacious for strengthening weak, debilitated
animals. A common way is to mix equal parts of gentian and
powdered nux vomica thoroughly together. This may be given as a
drench, or in the feed or placed at the back of the tongue with a
spoon.
Dose: For horses and cattle, 1 teaspoonful three times a day; for
sheep and pigs, one-half teaspoonful.
NITRATE OF SILVER
This comes in the form of white penciled sticks. It is excellent for
burning off warts, proud flesh in cuts and growths on any part of the
body. Just wet the stick and rub it on the parts. Of course, be careful
that your fingers are protected from the chemical. It is a poison
taken internally.
NITRATE OF POTASH
This is frequently called saltpeter, and comes as a white crystal or
powder. It is used for kidney, lung and blood troubles. It has a very
acute action on the kidneys, causing them to secrete an extra
amount of urine.
Dose: For horses and cattle, 1 teaspoonful; sheep and pigs, one-
half teaspoonful.
SULPHATE OF COPPER
This is commonly known as blue vitriol or bluestone. It is excellent
when given internally for checking discharges, especially those of a
chronic catarrhal nature. It may also be used as a wash for wounds,
when a weak solution is made, and may be dusted on the wound
every day or two in case proud flesh forms.
SULPHATE OF IRON
Green vitriol, or copperas, as it is commonly known, is a splendid
mineral tonic, and is commonly used in combination with gentian,
equal parts of the two. Use when the system is badly run down. It is
also excellent as a worm powder.
Dose: For horses and cattle, 1 teaspoonful three times a day;
sheep and pigs, one-half teaspoonful.
SUGAR OF LEAD
This is frequently called acetate of lead. It is seldom used
internally, but quite generally externally for healing washes,
particularly for the eye.
SWEET SPIRITS OF NITER
This sweet-tasting and smelling preparation is obtained from
alcohol, and is in the form of a clear liquid. It acts upon the kidneys
and skin and is commonly given in the drinking water of animals. It
is used in combination with other medicines for colic and indigestion.
It thus acts upon the bowels and stomach and relieves pain and
dissipates the gases. In giving to animals mix in a pint of lukewarm
water and give as a drench.
Dose: For horses and cattle, 2 to 4 tablespoonfuls; for sheep and
pigs, 1 to 2 teaspoonfuls.
SPIRITS OF TURPENTINE
This is the ordinary turpentine known by all. It is excellent in cases
of acute indigestion and colic, and is destructive to bots and the long
round worms in horses. When used externally it is as a liniment.
When used internally a small quantity is given with raw linseed oil.
Colic Mixture.
Fly Blister.
Dose: For horses and cattle, 4 tablespoonfuls; for sheep and pigs,
1 tablespoonful.
SALTS
The two common salts used for live stock are Epsom and Glauber.
Epsom salts are most frequently used, the chief action being as a
physic. Aloes take the places of salts for horses, as it is believed
these are much better than the mineral salts. In giving salts to
cattle, the drench is most satisfactory.
Dose: Use 1 quart of warm water in which place 1 tablespoonful
of ginger and 1 tablespoonful of common soda. To this add 1 pint to
11⁄2 pints of salts and dissolve by shaking or stirring. For sheep and
pigs, one-quarter of this amount is sufficient.
SULPHUR
This yellow powder is well known and is a great medicine when
given internally. It acts on the blood and purifies it. It is excellent
also for killing parasites or germs in the skin, hence it is good for all
diseases. When used internally it is best to combine with gentian
root. Give once a day for a short period.
Dose: For horses and cattle, 1 tablespoonful; sheep and pigs, 1
teaspoonful.
SOME COMMON PRESCRIPTIONS
—Laudanum, 16 tablespoonfuls; aromatic spirits of
ammonia, 12 tablespoonfuls; sulphuric ether, 2 tablespoonfuls;
tincture of aconite, 10 drops; ginger, 16 tablespoonfuls. Dissolve in a
pint of water. From 10 to 20 tablespoonfuls of this can be given in
one-half pint of water. If relief is not secured, repeat in a half hour,
follow with a third dose, then with another, giving the doses one-half
to one hour apart.
—Powdered cantharides, 2 teaspoonfuls; gum
camphor powdered, 2 tablespoonfuls; lard, 8 tablespoonfuls. After
Red Blister.
Cough Mixture.
Soothing Ointment.
Hoof Ointment.
Physic Drench for Horses.
thoroughly mixing, rub in 5 to 10 minutes, depending on the severity
of the blister desired.
—Gum camphor powdered, 2 tablespoonfuls;
biniodide of mercury, 2 teaspoonfuls; lard, 8 tablespoonfuls. This
should be rubbed in from 5 to 10 minutes.
—Belladonna, 2 tablespoonfuls; pulverized
opium, 2 tablespoonfuls; gum camphor, pulverized, 2 teaspoonfuls;
chloride of ammonia, 2 tablespoonfuls; sulphur, 4 tablespoonfuls. An
easy way to give this is to mix with molasses and flour until a paste
is secured.
—Laudanum, 8 tablespoonfuls; aconite, 4
tablespoonfuls. This is excellent for sprains, and relieves the pain
and soreness when applied to a part where there is much
inflammation.
—Raw linseed oil, one-quarter pound; crude
petroleum oil, one-quarter pound; neat’s-foot oil, one-quarter
pound; pine tar, one-quarter pound. Mix well and apply every night
with a brush all over and under the hoof. A little in the hair above
will do no harm. Clean out the hoof before applying.
—Aloes, 8 teaspoonfuls; common
soda, 1 teaspoonful; ginger, 1 teaspoonful. Dissolve these in a pint
of lukewarm water and give as a drench. The horse should be
allowed rest the day following its use.

More Related Content

Similar to Practical SQL A Beginner s Guide to Storytelling with Data 2nd Edition Anthony Debarros (20)

PDF
Sql1 vol2
Ebtsam Mohamed
 
PDF
advance-sqaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal.pdf
traphuong2103
 
PPTX
SQL with PostgreSQL - Getting Started
Or Chen
 
PDF
FUNDAMENTOS DE MATEMATICAS
VeraVelazquez
 
PPTX
SQL-Demystified-A-Beginners-Guide-to-Database-Mastery.pptx
bhavaniteacher99
 
PPT
98765432345671223Intro-to-PostgreSQL.ppt
HastavaramDineshKuma
 
PPT
Higher SQL
missstevenson01
 
PPT
Toc
Sudharsan S
 
PPT
Toc
Sudharsan S
 
PPTX
Introduction to SQL
Mahir Haque
 
PDF
SQL-for-Data-Analytics-Top-10-Queries-Every-Analyst-Should-Know
Ozias Rondon
 
PPT
Oracle Training Tutorial for Beginners
rajkamaltibacademy
 
PDF
FOUNDATION OF DATA SCIENCE SQL QUESTIONS
HITIKAJAIN4
 
PDF
SQL.pdf
RiyaSharma335
 
PPTX
SQL (Basic to Intermediate Customized 8 Hours)
Edu4Sure
 
PDF
Oracle Material.pdf
rajeshkathavarayan
 
PPTX
Crash course in sql
Mithun Shanbhag
 
ODP
Oracle SQL Advanced
Dhananjay Goel
 
PPTX
DMV - All Lectures SQL.pptxpComplete SQL
ssuser68b4231
 
PDF
SQL learning notes and all code.pdf
79TarannumMulla
 
Sql1 vol2
Ebtsam Mohamed
 
advance-sqaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal.pdf
traphuong2103
 
SQL with PostgreSQL - Getting Started
Or Chen
 
FUNDAMENTOS DE MATEMATICAS
VeraVelazquez
 
SQL-Demystified-A-Beginners-Guide-to-Database-Mastery.pptx
bhavaniteacher99
 
98765432345671223Intro-to-PostgreSQL.ppt
HastavaramDineshKuma
 
Higher SQL
missstevenson01
 
Introduction to SQL
Mahir Haque
 
SQL-for-Data-Analytics-Top-10-Queries-Every-Analyst-Should-Know
Ozias Rondon
 
Oracle Training Tutorial for Beginners
rajkamaltibacademy
 
FOUNDATION OF DATA SCIENCE SQL QUESTIONS
HITIKAJAIN4
 
SQL.pdf
RiyaSharma335
 
SQL (Basic to Intermediate Customized 8 Hours)
Edu4Sure
 
Oracle Material.pdf
rajeshkathavarayan
 
Crash course in sql
Mithun Shanbhag
 
Oracle SQL Advanced
Dhananjay Goel
 
DMV - All Lectures SQL.pptxpComplete SQL
ssuser68b4231
 
SQL learning notes and all code.pdf
79TarannumMulla
 

Recently uploaded (20)

PPTX
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
Introduction to Indian Writing in English
Trushali Dodiya
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PDF
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PPTX
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
PDF
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PPTX
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
Introduction to Indian Writing in English
Trushali Dodiya
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
Ad

Practical SQL A Beginner s Guide to Storytelling with Data 2nd Edition Anthony Debarros

  • 1. Practical SQL A Beginner s Guide to Storytelling with Data 2nd Edition Anthony Debarros install download https://ebookmeta.com/product/practical-sql-a-beginner-s-guide- to-storytelling-with-data-2nd-edition-anthony-debarros/ Download more ebook from https://ebookmeta.com
  • 2. 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! Practical SQL A Beginner s Guide to Storytelling with Data 2nd Edition Anthony Debarros https://ebookmeta.com/product/practical-sql-a-beginner-s-guide- to-storytelling-with-data-2nd-edition-anthony-debarros/ Practical SQL: A Beginner's Guide to Storytelling with Data, 2nd Edition Anthony Debarros https://ebookmeta.com/product/practical-sql-a-beginners-guide-to- storytelling-with-data-2nd-edition-anthony-debarros/ 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/ Mathematics Mathematics HL Option Discrete Mathematics 1st Edition Catherine Quinn Peter Blythe Chris Sangwin Robert Haese Michael Haese https://ebookmeta.com/product/mathematics-mathematics-hl-option- discrete-mathematics-1st-edition-catherine-quinn-peter-blythe- chris-sangwin-robert-haese-michael-haese/
  • 3. Nothing s Worse Than A Clown Gone Bad 1st Edition Ponk Vonsydow https://ebookmeta.com/product/nothing-s-worse-than-a-clown-gone- bad-1st-edition-ponk-vonsydow/ Revenge Of Her Wolves Tara West https://ebookmeta.com/product/revenge-of-her-wolves-tara-west/ Demystifying the Order from Above 1st Edition Lubogo Isaac Christopher https://ebookmeta.com/product/demystifying-the-order-from- above-1st-edition-lubogo-isaac-christopher/ Blockchain and the Supply Chain: Concepts, Strategies and Practical Applications, 2nd Edition Nick Vyas https://ebookmeta.com/product/blockchain-and-the-supply-chain- concepts-strategies-and-practical-applications-2nd-edition-nick- vyas/ A Warning for Fair Women Adultery and Murder in Shakespeare s Theater 1st Edition Ann C Christensen https://ebookmeta.com/product/a-warning-for-fair-women-adultery- and-murder-in-shakespeare-s-theater-1st-edition-ann-c- christensen/
  • 4. Contemporary Strategy : Theories and Policies 1st Edition John Baylis https://ebookmeta.com/product/contemporary-strategy-theories-and- policies-1st-edition-john-baylis/
  • 6. CONTENTS IN DETAIL TITLE PAGE COPYRIGHT ABOUT THE AUTHOR PREFACE TO THE SECOND EDITION ACKNOWLEDGMENTS INTRODUCTION What Is SQL? Why SQL? Who Is This Book For? What You’ll Learn CHAPTER 1: SETTING UP YOUR CODING ENVIRONMENT Installing a Text Editor Downloading Code and Data from GitHub Installing PostgreSQL and pgAdmin Windows Installation macOS Installation Linux Installation Working with pgAdmin Launching pgAdmin and Setting a Master Password
  • 7. Connecting to the Default postgres Database Exploring the Query Tool Customizing pgAdmin Alternatives to pgAdmin Wrapping Up CHAPTER 2: CREATING YOUR FIRST DATABASE AND TABLE Understanding Tables Creating a Database Executing SQL in pgAdmin Connecting to the analysis Database Creating a Table Using the CREATE TABLE Statement Making the teachers Table Inserting Rows into a Table Using the INSERT Statement Viewing the Data Getting Help When Code Goes Bad Formatting SQL for Readability Wrapping Up CHAPTER 3: BEGINNING DATA EXPLORATION WITH SELECT Basic SELECT Syntax Querying a Subset of Columns Sorting Data with ORDER BY Using DISTINCT to Find Unique Values Filtering Rows with WHERE Using LIKE and ILIKE with WHERE
  • 8. Combining Operators with AND and OR Putting It All Together Wrapping Up CHAPTER 4: UNDERSTANDING DATA TYPES Understanding Characters Understanding Numbers Using Integers Auto-Incrementing Integers Using Decimal Numbers Choosing Your Number Data Type Understanding Dates and Times Using the interval Data Type in Calculations Understanding JSON and JSONB Using Miscellaneous Types Transforming Values from One Type to Another with CAST Using CAST Shortcut Notation Wrapping Up CHAPTER 5: IMPORTING AND EXPORTING DATA Working with Delimited Text Files Handling Header Rows Quoting Columns That Contain Delimiters Using COPY to Import Data Importing Census Data Describing Counties Creating the us_counties_pop_est_2019 Table Understanding Census Columns and Data Types Performing the Census Import with COPY Inspecting the Import
  • 9. Importing a Subset of Columns with COPY Importing a Subset of Rows with COPY Adding a Value to a Column During Import Using COPY to Export Data Exporting All Data Exporting Particular Columns Exporting Query Results Importing and Exporting Through pgAdmin Wrapping Up CHAPTER 6: BASIC MATH AND STATS WITH SQL Understanding Math Operators and Functions Understanding Math and Data Types Adding, Subtracting, and Multiplying Performing Division and Modulo Using Exponents, Roots, and Factorials Minding the Order of Operations Doing Math Across Census Table Columns Adding and Subtracting Columns Finding Percentages of the Whole Tracking Percent Change Using Aggregate Functions for Averages and Sums Finding the Median Finding the Median with Percentile Functions Finding Median and Percentiles with Census Data Finding Other Quantiles with Percentile Functions Finding the Mode Wrapping Up
  • 10. CHAPTER 7: JOINING TABLES IN A RELATIONAL DATABASE Linking Tables Using JOIN Relating Tables with Key Columns Querying Multiple Tables Using JOIN Understanding JOIN Types JOIN LEFT JOIN and RIGHT JOIN FULL OUTER JOIN CROSS JOIN Using NULL to Find Rows with Missing Values Understanding the Three Types of Table Relationships One-to-One Relationship One-to-Many Relationship Many-to-Many Relationship Selecting Specific Columns in a Join Simplifying JOIN Syntax with Table Aliases Joining Multiple Tables Combining Query Results with Set Operators UNION and UNION ALL INTERSECT and EXCEPT Performing Math on Joined Table Columns Wrapping Up CHAPTER 8: TABLE DESIGN THAT WORKS FOR YOU Following Naming Conventions Quoting Identifiers Enables Mixed Case Pitfalls with Quoting Identifiers Guidelines for Naming Identifiers
  • 11. Controlling Column Values with Constraints Primary Keys: Natural vs. Surrogate Foreign Keys How to Automatically Delete Related Records with CASCADE The CHECK Constraint The UNIQUE Constraint The NOT NULL Constraint How to Remove Constraints or Add Them Later Speeding Up Queries with Indexes B-Tree: PostgreSQL’s Default Index Considerations When Using Indexes Wrapping Up CHAPTER 9: EXTRACTING INFORMATION BY GROUPING AND SUMMARIZING Creating the Library Survey Tables Creating the 2018 Library Data Table Creating the 2017 and 2016 Library Data Tables Exploring the Library Data Using Aggregate Functions Counting Rows and Values Using count() Finding Maximum and Minimum Values Using max() and min() Aggregating Data Using GROUP BY Wrapping Up CHAPTER 10: INSPECTING AND MODIFYING DATA Importing Data on Meat, Poultry, and Egg Producers Interviewing the Dataset Checking for Missing Values
  • 12. Checking for Inconsistent Data Values Checking for Malformed Values Using length() Modifying Tables, Columns, and Data Modifying Tables with ALTER TABLE Modifying Values with UPDATE Viewing Modified Data with RETURNING Creating Backup Tables Restoring Missing Column Values Updating Values for Consistency Repairing ZIP Codes Using Concatenation Updating Values Across Tables Deleting Unneeded Data Deleting Rows from a Table Deleting a Column from a Table Deleting a Table from a Database Using Transactions to Save or Revert Changes Improving Performance When Updating Large Tables Wrapping Up CHAPTER 11: STATISTICAL FUNCTIONS IN SQL Creating a Census Stats Table Measuring Correlation with corr(Y, X) Checking Additional Correlations Predicting Values with Regression Analysis Finding the Effect of an Independent Variable with r- Squared Finding Variance and Standard Deviation Creating Rankings with SQL Ranking with rank() and dense_rank()
  • 13. Ranking Within Subgroups with PARTITION BY Calculating Rates for Meaningful Comparisons Finding Rates of Tourism-Related Businesses Smoothing Uneven Data Wrapping Up CHAPTER 12: WORKING WITH DATES AND TIMES Understanding Data Types and Functions for Dates and Times Manipulating Dates and Times Extracting the Components of a timestamp Value Creating Datetime Values from timestamp Components Retrieving the Current Date and Time Working with Time Zones Finding Your Time Zone Setting Setting the Time Zone Performing Calculations with Dates and Times Finding Patterns in New York City Taxi Data Finding Patterns in Amtrak Data Wrapping Up CHAPTER 13: ADVANCED QUERY TECHNIQUES Using Subqueries Filtering with Subqueries in a WHERE Clause Creating Derived Tables with Subqueries Joining Derived Tables Generating Columns with Subqueries Understanding Subquery Expressions Using Subqueries with LATERAL Using Common Table Expressions
  • 14. Performing Cross Tabulations Installing the crosstab() Function Tabulating Survey Results Tabulating City Temperature Readings Reclassifying Values with CASE Using CASE in a Common Table Expression Wrapping Up CHAPTER 14: MINING TEXT TO FIND MEANINGFUL DATA Formatting Text Using String Functions Case Formatting Character Information Removing Characters Extracting and Replacing Characters Matching Text Patterns with Regular Expressions Regular Expression Notation Using Regular Expressions with WHERE Regular Expression Functions to Replace or Split Text Turning Text to Data with Regular Expression Functions Full-Text Search in PostgreSQL Text Search Data Types Creating a Table for Full-Text Search Searching Speech Text Ranking Query Matches by Relevance Wrapping Up CHAPTER 15: ANALYZING SPATIAL DATA WITH POSTGIS Enabling PostGIS and Creating a Spatial Database Understanding the Building Blocks of Spatial Data
  • 15. Understanding Two-Dimensional Geometries Well-Known Text Formats Projections and Coordinate Systems Spatial Reference System Identifier Understanding PostGIS Data Types Creating Spatial Objects with PostGIS Functions Creating a Geometry Type from Well-Known Text Creating a Geography Type from Well-Known Text Using Point Functions Using LineString Functions Using Polygon Functions Analyzing Farmers’ Markets Data Creating and Filling a Geography Column Adding a Spatial Index Finding Geographies Within a Given Distance Finding the Distance Between Geographies Finding the Nearest Geographies Working with Census Shapefiles Understanding the Contents of a Shapefile Loading Shapefiles Exploring the Census 2019 Counties Shapefile Examining Demographics Within a Distance Performing Spatial Joins Exploring Roads and Waterways Data Joining the Census Roads and Water Tables Finding the Location Where Objects Intersect Wrapping Up CHAPTER 16: WORKING WITH JSON DATA
  • 16. Understanding JSON Structure Considering When to Use JSON with SQL Using json and jsonb Data Types Importing and Indexing JSON Data Using json and jsonb Extraction Operators Key Value Extraction Array Element Extraction Path Extraction Containment and Existence Analyzing Earthquake Data Exploring and Loading the Earthquake Data Working with Earthquake Times Finding the Largest and Most-Reported Earthquakes Converting Earthquake JSON to Spatial Data Generating and Manipulating JSON Turning Query Results into JSON Adding, Updating, and Deleting Keys and Values Using JSON Processing Functions Finding the Length of an Array Returning Array Elements as Rows Wrapping Up CHAPTER 17: SAVING TIME WITH VIEWS, FUNCTIONS, AND TRIGGERS Using Views to Simplify Queries Creating and Querying Views Creating and Refreshing a Materialized View Inserting, Updating, and Deleting Data Using a View Creating Your Own Functions and Procedures
  • 17. Creating the percent_change() Function Using the percent_change() Function Updating Data with a Procedure Using the Python Language in a Function Automating Database Actions with Triggers Logging Grade Updates to a Table Automatically Classifying Temperatures Wrapping Up CHAPTER 18: USING POSTGRESQL FROM THE COMMAND LINE Setting Up the Command Line for psql Windows psql Setup macOS psql Setup Linux psql Setup Working with psql Launching psql and Connecting to a Database Running SQL Queries on psql Navigating and Formatting Results Meta-Commands for Database Information Importing, Exporting, and Using Files Additional Command Line Utilities to Expedite Tasks Adding a Database with createdb Loading Shapefiles with shp2pgsql Wrapping Up CHAPTER 19: MAINTAINING YOUR DATABASE Recovering Unused Space with VACUUM Tracking Table Size
  • 18. Monitoring the Autovacuum Process Running VACUUM Manually Reducing Table Size with VACUUM FULL Changing Server Settings Locating and Editing postgresql.conf Reloading Settings with pg_ctl Backing Up and Restoring Your Database Using pg_dump to Export a Database or Table Restoring a Database Export with pg_restore Exploring Additional Backup and Restore Options Wrapping Up CHAPTER 20: TELLING YOUR DATA’S STORY Start with a Question Document Your Process Gather Your Data No Data? Build Your Own Database Assess the Data’s Origins Interview the Data with Queries Consult the Data’s Owner Identify Key Indicators and Trends over Time Ask Why Communicate Your Findings Wrapping Up APPENDIX: ADDITIONAL POSTGRESQL RESOURCES PostgreSQL Development Environments PostgreSQL Utilities, Tools, and Extensions PostgreSQL News and Community
  • 20. PRACTICAL SQL 2nd Edition A Beginner’s Guide to Storytelling with Data by Anthony DeBarros
  • 21. PRACTICAL SQL, 2ND EDITION. Copyright © 2022 by Anthony DeBarros. All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. Printed in the United States of America First printing 25 24 23 22 21 1 2 3 4 5 6 7 8 9 ISBN-13: 978-1-7185-0106-5 (print) ISBN-13: 978-1-7185-0107-2 (ebook) Publisher: William Pollock Managing Editor: Jill Franklin Production Manager: Rachel Monaghan Production Editors: Jennifer Kepler and Paula Williamson Developmental Editor: Liz Chadwick Cover Illustrator: Josh Ellingson Interior Design: Octopod Studios Technical Reviewer: Stephen Frost Copyeditor: Kim Wimpsett Compositor: Maureen Forys, Happenstance Type-O-Rama Proofreader: Liz Wheeler For information on book distributors or translations, please contact No Starch Press, Inc. directly: No Starch Press, Inc. 245 8th Street, San Francisco, CA 94103 phone: 1.415.863.9900; [email protected] www.nostarch.com The Library of Congress has catalogued the first edition as follows: Names: DeBarros, Anthony, author. Title: Practical SQL : a beginner's guide to storytelling with data / Anthony DeBarros. Description: San Francisco : No Starch Press, 2018. | Includes index. Identifiers: LCCN 2018000030 (print) | LCCN 2017043947 (ebook) | ISBN 9781593278458 (epub) | ISBN 1593278454 (epub) | ISBN 9781593278274 (paperback) | ISBN 1593278276 (paperback) | ISBN 9781593278458 (ebook) Subjects: LCSH: SQL (Computer program language) | Database design. | BISAC: COMPUTERS / Programming Languages / SQL. | COMPUTERS / Database Management / General. | COMPUTERS / Database Management / Data Mining. Classification: LCC QA76.73.S67 (print) | LCC QA76.73.S67 D44 2018 (ebook) | DDC 005.75/6--dc23 LC record available at https://lccn.loc.gov/2018000030
  • 22. No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other product and company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of this work, neither the author nor No Starch Press, Inc. shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it.
  • 23. About the Author Anthony DeBarros is a longtime journalist and early adopter of “data journalism,” the use of spreadsheets, databases, and code to find news in data. He’s currently a data editor for the Wall Street Journal, where he covers topics including the economy, trade, demographics, and the Covid-19 pandemic. Previously, he worked for the Gannett company at USA Today and the Poughkeepsie Journal and held product development and content strategy roles for Questex and DocumentCloud. About the Technical Reviewer Stephen Frost is the chief technology officer at Crunchy Data. He has been working with PostgreSQL since 2003 and general database technology since before then. Stephen began contributing to PostgreSQL development in 2004 and has been involved in the development of the role system, column-level privileges, row-level security, GSSAPI encryption, and the predefined roles system. He has also served on the board of the United States PostgreSQL Association and Software in the Public Interest, regularly speaks at PostgreSQL Community conferences and events, and works as a member of various PostgreSQL community teams.
  • 24. PREFACE TO THE SECOND EDITION Since the publication of the first edition of Practical SQL, I’ve received kind notes about the book from readers around the world. One happy reader said it helped him ace SQL questions on a job interview. Another, a teacher, wrote to say that his students remarked favorably about having the book assigned for class. Others just wanted to say thanks because they found the book helpful and a good read, two pieces of feedback that will warm the heart of most any author. I also sometimes heard from readers who hit a roadblock while working through an exercise or who had trouble with software or data files. I paid close attention to those emails, especially when the same question seemed to crop up more than once. Meanwhile, during my own journey of learning SQL—I use it every day at work— I’d often discover a technique and wish that I’d included it in the book. With all that in mind, I approached the team at No Starch Press with the idea of updating and expanding Practical SQL into a second edition. I’m thankful they said yes. This new version of the book is more complete, offers stronger guidance for readers related to software and code, and clarifies information that wasn’t as clear or presented as accurately as it could have been. The book has been thoroughly enjoyable to revisit, and I’ve learned much along the way.
  • 25. This second edition includes numerous updates, expansions, and clarifications in every chapter. Throughout, I’ve been careful to note when code syntax adheres to the SQL standard—meaning you can generally use it across database systems—or when the syntax is specific to the database used in the book, PostgreSQL. The following are among the most substantial changes: Two chapters are new. Chapter 1, “Setting Up Your Coding Environment,” details how to install PostgreSQL, pgAdmin, and additional PostgreSQL components on multiple operating systems. It also shows how to obtain the code listings and data from GitHub. In the first edition, this information was located in the introduction and occasionally missed by readers. Chapter 16, “Working with JSON Data,” covers PostgreSQL’s support for the JavaScript Object Notation data format, using datasets about movies and earthquakes. In Chapter 4 on data types, I’ve added a section on IDENTITY, the ANSI SQL standard implementation for auto-incrementing integer columns. Throughout the book, IDENTITY replaces the PostgreSQL-specific serial auto-incrementing integer type so that code examples more closely reflect the SQL standard. Chapter 5 on importing and exporting data now includes a section about using the WHERE keyword with the COPY command to filter which rows are imported from a source file to a table. I’ve removed the user-created median() function from Chapter 6 on basic math in favor of focusing exclusively on the SQL standard percentile_cont() function for calculating medians. In Chapter 7 on table joins, I’ve added a section covering the set operators UNION, UNION ALL, INTERSECT, and EXCEPT. Additionally, I’ve added a section covering the USING clause in joins to reduce redundant output and simplify query syntax. Chapter 10 on inspecting and modifying data includes a new section on using the RETURNING keyword in an UPDATE statement to display the data that the statement modified. I’ve also added a section that describes how to use the TRUNCATE command to remove all rows from a table and restart an IDENTITY sequence.
  • 26. In Chapter 11 on statistical functions, a new section demonstrates how to create a rolling average to smooth uneven data to get a better sense of trends over time. I’ve also added information on functions for calculating standard deviation and variance. Chapter 13 on advanced query techniques now shows how to use the LATERAL keyword with subqueries. One benefit is that, by combining LATERAL with JOIN, you get functionality similar to a for loop in a programming language. In Chapter 15 on analyzing spatial data, I demonstrate how to use the Geometry Viewer in pgAdmin to see geographies placed on a map. This feature was added to pgAdmin after publication of the first edition. In Chapter 17 on views, functions, and triggers, I’ve added information about materialized views and showed how their behavior differs from standard views. I also cover procedures, which PostgreSQL now supports in addition to functions. Finally, where practical, datasets have been updated to the most recent available at the time of writing. This primarily applies to US Census population statistics but also includes the text of presidential speeches and library usage statistics. Thank you for reading Practical SQL! If you have any questions or feedback, please get in touch by emailing [email protected].
  • 27. ACKNOWLEDGMENTS This second edition of Practical SQL is the work of many hands. My thanks, first, go to the team at No Starch Press. Thanks to Bill Pollock for capturing the vision and sharpening the initial concept for the book—and for agreeing to let me have another go at it. Special thanks and appreciation to senior editor Liz Chadwick, who improved each chapter with her insightful suggestions and deft editing, and to copyeditor Kim Wimpsett and the production team of Paula Williamson and Jennifer Kepler. Stephen Frost, chief technology officer at Crunchy Data and longtime contributor to the PostgreSQL community, served as the technical reviewer for this edition. I deeply appreciate the time Stephen took to explain the inner workings of PostgreSQL and SQL concepts. This book is better, more thorough, and more accurate thanks to his detailed eye. I’d also like to acknowledge Josh Berkus, whose many contributions as technical reviewer for the first edition persist in this new version. Thank you to Investigative Reporters and Editors (IRE) and its members and staff past and present for training journalists to find stories in data. IRE is where I got my start with SQL and data journalism. Many of my colleagues have not only imparted memorable lessons on data analysis, they’ve also made my workdays brighter. Special thanks to Paul Overberg for sharing his vast knowledge of demographics and the US Census, to Lou Schilling for many technical lessons, to Christopher Schnaars for his SQL expertise, to Peter Matseykanets for his encouragement, and to Chad Day, John West, and Maureen Linke and the WSJ DC visuals team for continual inspiration.
  • 28. My deepest appreciation goes to my dear wife, Elizabeth, and our sons. You are the brightest lights in my day. As we are fond of saying, “To the journey . . .”
  • 29. INTRODUCTION Shortly after joining the staff of USA Today, I received a dataset that I would analyze almost every week for the next decade. It was the weekly Best-Selling Books list, which ranked the nation’s top-selling titles based on confidential sales data. Not only did the list produce an endless stream of story ideas to pitch, it also captured the zeitgeist of America in a singular way. Did you know that cookbooks sell a bit more during the week of Mother’s Day or that Oprah Winfrey turned many obscure writers into number-one best-selling authors just by having them on her show? Every week, the book list editor and I pored over the sales figures and book genres, ranking the data in search of a new headline. Rarely did we come up empty: we chronicled everything from the rocket-rise of the blockbuster Harry Potter series to the fact that Oh, the Places You’ll Go! by Dr. Seuss had become a perennial gift for new graduates. My technical companion in that time was the database programming language SQL (for Structured Query Language). Early on, I convinced USA Today’s IT department to grant me access to the SQL-based database system that powered our book list application. Using SQL, I was able to discover the stories hidden in the database, which contained sales data related to titles, authors, genres, and the codes that defined the publishing world.
  • 30. SQL has been useful to me ever since, whether my role was in product development, in content strategy, or, lately, as a data editor for the Wall Street Journal. In each case, SQL has helped me find interesting stories in data—and that’s exactly what you’ll learn to do using this book. What Is SQL? SQL is a widely used programming language for managing data and database systems. Whether you’re a marketing analyst, a journalist, or a researcher mapping neurons in the brain of a fruit fly, you’ll benefit from using SQL to collect, modify, explore, and summarize data. Because SQL is a mature language that’s been around for decades, it’s ingrained in many modern systems. A pair of IBM researchers first outlined the syntax for SQL (then called SEQUEL) in a 1974 paper, building on the theoretical work of the British computer scientist Edgar F. Codd. In 1979, a precursor to the database company Oracle (then called Relational Software) became the first to use the language in a commercial product. Today, SQL still ranks as one of the most-used computer languages in the world, and that’s unlikely to change soon. Each database system, such as PostgreSQL, MySQL or Microsoft SQL Server, implements its own variant of SQL, so you’ll notice subtle—or sometimes significant—differences in syntax if you jump from one system to another. There are several reasons behind this. The American National Standards Institute (ANSI) adopted a standard for SQL in 1986, followed by the International Organization for Standardization (ISO) in 1987. But the standard doesn’t cover all aspects of SQL that are required for a database implementation—for example, it has no entry for creating indexes. That leaves each database system maker to choose how to implement features the standard doesn’t cover—and no database maker currently claims to conform to the entire standard. Meanwhile, business considerations can lead commercial database vendors to create nonstandard SQL features for both competitive advantage and as a way to keep users in their ecosystem. For
  • 31. example, Microsoft’s SQL Server uses the proprietary Transact-SQL (T-SQL) that includes a number of features not in the SQL standard, such as its syntax for declaring local variables. Migrating code written using T-SQL to another database system may not be trivial, therefore. In this book, the examples and code use the PostgreSQL database system. PostgreSQL, or simply Postgres, is a robust application that can handle large amounts of data. Here are some reasons PostgreSQL is a great choice to use with this book: It’s free. It’s available for Windows, macOS, and Linux operating systems. Its SQL implementation aims to closely follow the SQL standard. It’s widely used, so finding help online is easy. Its geospatial extension, PostGIS, lets you analyze geometric data and perform mapping functions and is often used with mapping software such as QGIS. It’s available in cloud computing environments such as Amazon Web Services and Google Cloud. It’s a common choice as a data store for web applications, including those powered by the popular web framework Django. The good news is that the fundamental concepts and much of the core SQL syntactical conventions of PostgreSQL will work across databases. So, if you’re using MySQL at work, you can employ much of what you learn here—or easily find parallel code concepts. When syntax is PostgreSQL-specific, I make sure to point that out. If you need to learn the SQL syntax of a system with features that deviate from the standard, such as Microsoft SQL Server’s T-SQL, you may want to further explore a resource focusing on that system. Why SQL? SQL certainly isn’t the only option for crunching data. Many people start with Microsoft Excel spreadsheets and their assortment of
  • 32. analytic functions. After working with Excel, they might graduate to Access, the database system built into some versions of Microsoft Office, which has a graphical query interface that makes it easy to get work done. So why learn SQL? One reason is that Excel and Access have their limits. Excel currently allows 1,048,576 rows maximum per worksheet. Access limits database size to two gigabytes and limits columns to 255 per table. It’s not uncommon for datasets to surpass those limits. The last obstacle you want to discover while facing a deadline is that your database system doesn’t have the capacity to get the job done. Using a robust SQL database system allows you to work with terabytes of data, multiple related tables, and thousands of columns. It gives you fine-grained control over the structure of your data, leading to efficiency, speed, and—most important—accuracy. SQL is also an excellent adjunct to programming languages used in the data sciences, such as R and Python. If you use either language, you can connect to SQL databases and, in some cases, even incorporate SQL syntax directly into the language. For people with no background in programming languages, SQL often serves as an easy-to-understand introduction into concepts related to data structures and programming logic. Finally, SQL is useful beyond data analysis. If you delve into building online applications, you’ll find that databases provide the backend power for many common web frameworks, interactive maps, and content management systems. When you need to dig beneath the surface of these applications, the ability to manage data and databases with SQL will come in very handy.
  • 33. Who Is This Book For? Practical SQL is for people who encounter data in their everyday lives and want to learn how to analyze, manage, and transform it. With that in mind, we cover real-world data and scenarios, such as US Census demographics, crime reports, and data about taxi rides in New York City. We aim to understand not only how SQL works but how we can use it to find valuable insights. This book was written with people new to programming in mind, so the early chapters cover key basics about databases, data, and SQL syntax. Readers with some SQL experience should benefit from later chapters that cover more advanced topics, such as Geographical Information Systems (GIS). I assume that you know your way around your computer, including how to install programs, navigate your hard drive, and download files from the internet, but I don’t assume you have any experience with programming or data analysis. What You’ll Learn Practical SQL starts with a chapter on setting up your system and getting the code and data examples and then moves through the basics of databases, queries, tables, and data that are common to SQL across many database systems. Chapters 14 to 19 cover topics more specific to PostgreSQL, such as full-text search, functions, and GIS. Although many chapters in this book can stand alone, you should work through the book sequentially to build on the fundamentals. Datasets presented in early chapters often reappear later, so following the book in order will help you stay on track. The following summary provides more detail about each chapter: Chapter 1: Setting Up Your Coding Environment walks through setting up PostgreSQL, the pgAdmin user interface, and a text editor, plus how to download example code and data. Chapter 2: Creating Your First Database and Table provides step-by-step instructions for the process of loading a simple dataset about teachers into a new database.
  • 34. Chapter 3: Beginning Data Exploration with SELECT explores basic SQL query syntax, including how to sort and filter data. Chapter 4: Understanding Data Types explains the definitions for setting columns in a table to hold specific types of data, from text to dates to various forms of numbers. Chapter 5: Importing and Exporting Data explains how to use SQL commands to load data from external files and then export it. You’ll load a table of US Census population data that you’ll use throughout the book. Chapter 6: Basic Math and Stats with SQL covers arithmetic operations and introduces aggregate functions for finding sums, averages, and medians. Chapter 7: Joining Tables in a Relational Database explains how to query multiple, related tables by joining them on key columns. You’ll learn how and when to use different types of joins. Chapter 8: Table Design that Works for You covers how to set up tables to improve the organization and integrity of your data as well as how to speed up queries using indexes. Chapter 9: Extracting Information by Grouping and Summarizing explains how to use aggregate functions to find trends in US library usage based on annual surveys. Chapter 10: Inspecting and Modifying Data explores how to find and fix incomplete or inaccurate data using a collection of records about meat, egg, and poultry producers as an example. Chapter 11: Statistical Functions in SQL introduces correlation, regression, ranking, and other functions to help you derive more meaning from datasets. Chapter 12: Working with Dates and Times explains how to create, manipulate, and query dates and times in your database, including working with time zones and with data about New York City taxi trips and Amtrak train schedules. Chapter 13: Advanced Query Techniques explains how to use more complex SQL operations such as subqueries and cross
  • 35. tabulations, plus the CASE statement, to reclassify values in a dataset on temperature readings. Chapter 14: Mining Text to Find Meaningful Data covers how to use PostgreSQL’s full-text search engine and regular expressions to extract data from unstructured text, using police reports and a collection of speeches by US presidents as examples. Chapter 15: Analyzing Spatial Data with PostGIS introduces data types and queries related to spatial objects, which will let you analyze geographical features such as counties, roads, and rivers. Chapter 16: Working with JSON Data introduces the JavaScript Object Notation (JSON) data format and uses data about movies and earthquakes to explore PostgreSQL JSON support. Chapter 17: Saving Time with Views, Functions, and Triggers explains how to automate database tasks so you can avoid repeating routine work. Chapter 18: Using PostgreSQL from the Command Line covers how to use text commands at your computer’s command prompt to connect to your database and run queries. Chapter 19: Maintaining Your Database provides tips and procedures for tracking the size of your database, customizing settings, and backing up data. Chapter 20: Telling Your Data’s Story provides guidelines for generating ideas for analysis, vetting data, drawing sound conclusions, and presenting your findings clearly. Appendix: Additional PostgreSQL Resources lists software and documentation to help you grow your skills. Each chapter ends with a “Try It Yourself” section that contains exercises to help you reinforce the topics you learned. Ready? Let’s begin with Chapter 1, “Setting Up Your Coding Environment.”
  • 36. 1 SETTING UP YOUR CODING ENVIRONMENT Let’s begin by installing the resources you’ll need to complete the exercises in the book. In this chapter, you’ll install a text editor, download the example code and data, and then install the PostgreSQL database system and its companion graphical user interface, pgAdmin. I’ll also tell you how to get help if you need it. When you’re finished, your computer will have a robust environment for you to learn how to analyze data with SQL. Avoid the temptation to skip ahead to the next chapter. My high school teacher (clearly a fan of alliteration) used to tell us that “proper planning prevents poor performance.” If you follow all the steps in this chapter, you’ll avoid headaches later. Our first task is to set up a text editor suitable for working with data.
  • 37. Installing a Text Editor The source data you’ll add to a SQL database is typically stored in multiple text files, often in a format called comma-separated values (CSV). You’ll learn more about the CSV format in Chapter 5, in the section “Working with Delimited Text Files,” but for now let’s make sure you have a text editor that will let you open those files without inadvertently harming the data. Common business applications—word processors and spreadsheet programs—tend to introduce styles or hidden characters into files without asking, and that makes using them for data work problematic, as data software expects data in precise formats. For example, if you open a CSV file with Microsoft Excel, the program will automatically alter some data to make it more human-readable; it will assume, for example, that an item code of 3-09 is a date and format it as 9-Mar. Text editors deal exclusively with plain text with no embellishments such as formatting, and for that reason programmers use them to edit files that hold source code, data, and software configurations—all cases where you want your text to be treated as text, and nothing more. Any text editor should work for the book’s purposes, so if you have a favorite, feel free to use it. Here are some I have used and recommend. Except where noted, they are free and available for macOS, Windows, and Linux. Visual Studio Code by Microsoft: https://code.visualstudio.com/ Atom by GitHub: https://atom.io/ Sublime Text by Sublime HQ (free to evaluate but requires purchase for continued use): https://www.sublimetext.com/ Notepad++ by author Don Ho (Windows only): https://notepad- plus-plus.org/ (note that this is a different application than Notepad.exe, which comes with Windows) More advanced users who prefer to work in the command line may want to use one of these two text editors, which are installed by default in macOS and Linux:
  • 38. vim by author Bram Moolenaar and the open source community: https://www.vim.org/ GNU nano by author Chris Allegretta and the open source community: https://www.nano-editor.org/ If you don’t have a text editor, download and install one and get familiar with the basics of opening folders and working with files. Next, let’s get the book’s example code and data. Downloading Code and Data from GitHub All of the code and data you’ll need for working through the book’s exercises are available for download. To get it, follow these steps: 1. Visit the book’s page on the No Starch Press website at https://nostarch.com/practical-sql-2nd-edition/. 2. On the page, click Download the code from GitHub to visit the repository on https://github.com/ that holds the material. 3. On the Practical SQL 2nd Edition page at GitHub, you should see a Code button. Click it, and then select Download ZIP to save the ZIP file to your computer. Place it in a location where you can easily find it, such as your desktop. (If you’re a GitHub user, you can also clone or fork the repository.) 4. Unzip the file. You should then see a folder named practical-sql- 2-master that contains the various files and subfolders for the book. Again, place this folder where you can easily find it. NOTE Windows users will need to provide permission for the PostgreSQL database you will install to read and write to the contents of the practical-sql-2-master folder. To do so, right- click the folder, click Properties, and click the Security tab. Click Edit and then Add. Type the name Everyone into the object names box and click OK. Highlight Everyone in the user list, select all boxes under Allow, and then click Apply and OK.
  • 39. Inside the practical-sql-2-master folder, for each chapter you’ll find a subfolder named Chapter_XX (XX is the chapter number). Inside subfolders, each chapter that includes code examples will also have a file named Chapter_XX that ends with a .sql extension. This is a SQL code file that you can open with your text editor or with the PostgreSQL administrative tool you’ll install later in this chapter. Note that in the book several code examples are truncated to save space, but you’ll need the full listing from the .sql file to complete the exercise. You’ll know an example is truncated when you see --snip-- in the listing. The chapter folders also contain the public data you’ll use in the exercises, stored in CSV and other text-based files. As noted, it’s fine to view CSV files with a true text editor, but don’t open these files with Excel or a word processor. Now, with the prerequisites complete, let’s load the database software. Installing PostgreSQL and pgAdmin In this section, you’ll install both the PostgreSQL database system and a companion graphical administrative tool, pgAdmin. Think of pgAdmin as a helpful visual workspace for managing your PostgreSQL database. Its interface lets you see your database objects, manage settings, import and export data, and write queries, which is the code that retrieves data from your database. One benefit of using PostgreSQL is that the open source community has provided excellent guidelines that make it easy to get PostgreSQL up and running. The following sections outline installation for Windows, macOS, and Linux as of this writing, but the steps might change as new versions of the software or operating systems are released. Check the documentation noted in each section as well as the GitHub repository with the book’s resources; I’ll maintain files there with updates and answers to frequently asked questions.
  • 40. NOTE I recommend you install the latest available version of PostgreSQL for your operating system to ensure that it’s up- to-date on security patches and new features. For this book, I’ll assume you’re using version 11.0 or later. Windows Installation For Windows, I recommend using the installer provided by the company EDB (formerly EnterpriseDB), which offers support and services for PostgreSQL users. When you download the PostgreSQL package bundle from EDB, you also get pgAdmin and Stack Builder, which includes a few other tools you’ll use in this book and throughout your SQL career. To get the software, visit https://www.postgresql.org/download/windows/ and click Download the installer in the EDB section. This should lead to a downloads page on the EDB site. Select the latest available 64-bit Windows version of PostgreSQL unless you’re using an older PC with 32-bit Windows. NOTE The following section covers installation for Windows 10. If you’re using Windows 11, please check the GitHub repository with the book’s resources for notes about any adjustments to these instructions. After you download the installer, follow these steps to install PostgreSQL, pgAdmin, and additional components: 1. Right-click the installer and select Run as administrator. Answer Yes to the question about allowing the program to make changes to your computer. The program will perform a setup task and then present an initial welcome screen. Click through it. 2. Choose your installation directory, accepting the default. 3. On the Select Components screen, select the boxes to install PostgreSQL Server, the pgAdmin tool, Stack Builder, and the
  • 41. command line tools. 4. Choose the location to store data. You can choose the default, which is in a data subdirectory in the PostgreSQL directory. 5. Choose a password. PostgreSQL is robust with security and permissions. This password is for the default initial database superuser account, which is called postgres. 6. Select the default port number where the server will listen. Unless you have another database or application using it, use the default, which should be 5432. You can substitute 5433 or another number if you already have an application using the default port. 7. Select your locale. Using the default is fine. Then click through the summary screen to begin the installation, which will take several minutes. 8. When the installation is done, you’ll be asked whether you want to launch EnterpriseDB’s Stack Builder to obtain additional packages. Make sure the box is checked and click Finish. 9. When Stack Builder launches, choose the PostgreSQL installation on the drop-down menu and click Next. A list of additional applications should download. 10. Expand the Spatial Extensions menu and select the PostGIS Bundle for the version of PostgreSQL you installed. You may see more than one listed; if so, choose the newest version. Also, expand the Add-ons, tools and utilities menu and select EDB Language Pack, which installs support for programming languages including Python. Click through several times; you’ll need to wait while the installer downloads the additional components. 11. When installation files have been downloaded, click Next to install the language and PostGIS components. For PostGIS, you’ll need to agree to the license terms; click through until you’re asked to Choose Components. Make sure PostGIS and Create spatial database are selected. Click Next, accept the default install location, and click Next again. 12. Enter your database password when prompted and continue through the prompts to install PostGIS.
  • 42. 13. Answer Yes when asked to register the PROJ_LIB and GDAL_DATA environment variables. Also, answer Yes to the questions about setting POSTGIS_ENABLED_DRIVERS and enabling the POSTGIS_ENABLE_OUTDB_RASTERS environment variable. Finally, click through the final Finish steps to complete the installation and exit the installers. Depending on the version, you may be prompted to restart your computer. When finished, you should have two new folders in your Windows Start menu: one for PostgreSQL and another for PostGIS. If you’d like to get started right away, you can skip ahead to the section “Working with pgAdmin.” Otherwise, follow the steps in the next section to set environment variables for optional Python language support. We cover using Python with PostgreSQL in Chapter 17; you can wait until then to set up Python if you’d like to move ahead now. Configuring Python Language Support In Chapter 17, you’ll learn how to use the Python programming language with PostgreSQL. In the previous section, you installed the EDB Language Pack, which provides Python support. Follow these steps to add the location of the Language Pack files to your Windows system’s environment variables: 1. Open the Windows Control Panel by clicking the Search icon on the Windows taskbar, entering Control Panel, and then clicking the Control Panel icon. 2. In the Control Panel app, enter Environment in the search box. In the list of search results displayed, click Edit the System Environment Variables. A System Properties dialog will appear. 3. In the System Properties dialog, on the Advanced tab, click Environment Variables. The dialog that opens has two sections: User variables and System variables. In the System variables section, if you don’t see a PATH variable, continue to step a to create a new one. If you do see an existing PATH variable, continue to step b to modify it.
  • 43. a. If you don’t see PATH in the System variables section, click New to open a New System Variable dialog, shown in Figure 1-1. Figure 1-1: Creating a new PATH environment variable in Windows 10 In the Variable name box, enter PATH. In the Variable value box, enter C:edblanguagepackv2Python-3.9. (Instead of typing, you can click Browse Directory and navigate to the directory in the Browse For Folder dialog.) When you’ve either entered the path manually or browsed to it, click OK on the dialog to close it. b. If you do see an existing PATH variable in the System variables section, highlight it and click Edit. In the list of variables that displays, click New and enter C:edblanguagepackv2Python-3.9. (Instead of typing, you can click Browse Directory and navigate to the directory in the Browse For Folder dialog.) Once you’ve added the Language Pack path, highlight it in the list of variables and click Move Up until the path is at the top of the variables list. That way, PostgreSQL will find the correct Python version if you have additional Python installations. The result should look like the highlighted line in Figure 1-2. Click OK to close the dialog.
  • 44. Figure 1-2: Editing existing PATH environment variables in Windows 10 4. Finally, in the System variables section, click New. In the New System Variable dialog, enter PYTHONHOME in the Variable name box. In the Variable value box, enter C:edblanguagepackv2Python-3.9. When you’re finished, click OK in all dialogs to close them. Note that these Python path settings will take effect the next time you restart your system. If you experience any hiccups during the PostgreSQL install, check the resources for the book, where I will note changes that occur as
  • 45. the software is developed and can also answer questions. If you’re unable to install PostGIS via Stack Builder, try downloading a separate installer from the PostGIS site at https://postgis.net/windows_downloads/ and consult the guides at https://postgis.net/documentation/. Now, you can move ahead to the section “Working with pgAdmin.” macOS Installation For macOS users, I recommend obtaining Postgres.app, an open source macOS application that includes PostgreSQL as well as the PostGIS extension and a few other goodies. Separately, you’ll need to install the pgAdmin GUI and the Python language for use in functions. Installing Postgres.app and pgAdmin Follow these steps: 1. Visit https://postgresapp.com/ and download the latest release of the app. This will be a Disk Image file that ends in .dmg. 2. Double-click the .dmg file to open it, and then drag and drop the app icon into your Applications folder. 3. In your Applications folder, double-click the app icon to launch Postgres.app. (If you see a dialog that says the app cannot be opened because the developer cannot be verified, click Cancel. Then right-click the app icon and choose Open.) When Postgres.app opens, click Initialize to create and start a PostgreSQL database server. A small elephant icon will appear in your menu bar to indicate that you now have a database running. To set up the included PostgreSQL command line tools so you’re able to use them in future, open your Terminal application and run the following single line of code at the prompt (you can copy the code as a single line from the Postgres.app site at https://postgresapp.com/documentation/install.html):
  • 46. sudo mkdir -p /etc/paths.d &&echo /Applications/Postgres.app/Contents/Versions/latest/bin | sudo tee /etc/paths.d/postgresapp You may be prompted for the password you use to log in to your Mac. Enter that. The commands should execute without providing any output. Next, because Postgres.app doesn’t include pgAdmin, follow these steps to install pgAdmin: 1. Visit the pgAdmin site’s page for macOS downloads at https://www.pgadmin.org/download/pgadmin-4-macos/. 2. Select the latest version and download the installer (look for a Disk Image file that ends in .dmg). 3. Double-click the .dmg file, click through the prompt to accept the terms, and then drag pgAdmin’s elephant app icon into your Applications folder. Installation on macOS is relatively simple, but if you encounter any issues, review the documentation for Postgres.app at https://postgresapp.com/documentation/ and for pgAdmin at https://www.pgadmin.org/docs/. Installing Python In Chapter 17, you’ll learn how to use the Python programming language with PostgreSQL. To use Python with Postgres.app, you must install a specific version of the language even though macOS comes with Python pre-installed (and you might have set up an additional Python environment). To enable Postgres.app’s optional Python language support, follow these steps: 1. Visit the official Python site at https://www.python.org/ and click the Downloads menu. 2. In the list of releases, find and download the latest version of Python 3.9. Choose the appropriate installer for your Mac’s processor—an Intel chip on older Macs or Apple Silicon for newer
  • 47. models. The download is an Apple software package file that ends in .pkg. 3. Double-click the package file to install Python, clicking through license agreements. Close the installer when finished. Python requirements for Postgres.app may change over time. Check its Python documentation at https://postgresapp.com/documentation/plpython.html as well as the resources for this book for updates. You’re now ready to move ahead to the section “Working with pgAdmin.” Linux Installation If you’re a Linux user, installing PostgreSQL becomes simultaneously easy and difficult, which in my experience is very much the way it is in the Linux universe. Most times you can accomplish an installation with a few commands, but finding those commands requires some Internet sleuth work. Thankfully, most popular Linux distributions— including Ubuntu, Debian, and CentOS—bundle PostgreSQL in their standard package. However, some distributions stay on top of updates more than others, so there’s a chance the PostgreSQL you have downloaded may not be the latest. The best path is to consult your distribution’s documentation for the best way to install PostgreSQL if it’s not already included or if you want to upgrade to a more recent version. Alternatively, the PostgreSQL project maintains complete up-to- date package repositories for Red Hat variants, Debian, and Ubuntu. Visit https://yum.postgresql.org/ and https://wiki.postgresql.org/wiki/Apt for details. The packages you’ll want to install include the client and server for PostgreSQL, pgAdmin (if available), PostGIS, and PL/Python. The exact names of these packages will vary according to your Linux distribution. You might also need to manually start the PostgreSQL database server. The pgAdmin app is rarely part of Linux distributions. To install it, refer to the pgAdmin site at https://www.pgadmin.org/download/ for the latest instructions and to see whether your platform is
  • 48. supported. If you’re feeling adventurous, you can find instructions on building the app from source code at https://www.pgadmin.org/download/pgadmin-4-source-code/. Once finished, you can move ahead to the section “Working with pgAdmin.” Ubuntu Installation Example To give you a sense of what a PostgreSQL Linux install looks like, here are the steps I took to load PostgreSQL, pgAdmin, PostGIS, and PL/Python on Ubuntu 21.04, codenamed Hirsute Hippo. It’s a combination of the directions found at https://wiki.postgresql.org/wiki/Apt plus the “Basic Server Setup” section at https://help.ubuntu.com/community/PostgreSQL/. You can follow along if you’re on Ubuntu. Open your Terminal by pressing CTRL-ALT-T. Then, at the prompt, enter the following lines to import a key for the PostgreSQL APT repository: sudo apt-get install curl ca-certificates gnupgcurl https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add - Next, run this single line to create the file /etc/apt/sources.list.d/pgdg.list: sudo sh -c 'echo "deb https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list' Once that’s done, update the package lists and install PostgreSQL and pgAdmin with the next two lines. Here, I installed PostgreSQL 13; you can choose a newer version if available. sudo apt-get updatesudo apt-get install postgresql-13 You should now have PostgreSQL running. At the Terminal, enter the next line, which allows you to log in to the server and connect as the default postgres user to the postgres database using the psql interactive terminal, which we’ll cover in depth in Chapter 18:
  • 49. sudo -u postgres psql postgres When psql launches, it displays version information as well as a postgres=# prompt. Enter the following at the prompt to set a password: postgres=# password postgres I also like to create a user account with a name that matches my Ubuntu username. To do this, at the postgres=# prompt, enter the following line, substituting your Ubuntu username where you see anthony: postgres=# CREATE USER anthony SUPERUSER; Exit psql by entering q at the prompt. You should be back at your Terminal prompt once again. To install pgAdmin, first import a key for the repository: curl https://www.pgadmin.org/static/packages_pgadmin_org.pub | sudo apt- key add Next, run this single line to create the file /etc/apt/sources.list.d/pgadmin4.list and update package lists: sudo sh -c 'echo "deb https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/$(lsb_release -cs) pgadmin4 main" > /etc/apt/sources.list.d/pgadmin4.list && apt update' Then you can install pgAdmin 4: sudo apt-get install pgadmin4-desktop Finally, to install the PostGIS and PL/Python extensions, run the following lines in your terminal (substituting the version numbers of your PostgreSQL version): sudo apt install postgresql-13-postgis-3sudo apt install postgresql-
  • 50. Other documents randomly have different content
  • 51. Neck and Throat. Body and Back. Fore Legs and Front Feet. driving and handling. Then give a thought to the glands while here. Enlarged glands may indicate some scrofulous or glanderous condition of the system. —A beautiful neck and throat is an absolute beauty in the horse or cow. The skin should be thin, mellow, and soft, and the hair not over thick nor coarse. Look for poll-evil at the top of the neck and head. See if swellings, lumps or hard places are to be found at the sides of the neck, or underneath joining the throat. I have found such very frequent with dairy cattle; and cases are not unusual with horses. Frequently scars are to be found on the sides or bottom of the neck. These may be due to scratches caused by nails, barb-wire or some similar accident, and again they may have been caused by sores, tumors, or other bad quality of the blood. —Passing the side, look over the withers for galls or fistulæ, the shoulders for tumors, collar puffs, and swellings. Observe at the same time if there is any wasting of the muscles on the outside along the shoulder. Now the back. Is it right as to shape? Do you find any evidence of sores or tumors? Look for these along the sides and belly. Now stoop a bit and look under; do you find anything different from what is natural? In males look for tumor or disease of the penis; do the same with the scrotum, and, in case of geldings scrutinize carefully to see if they be ridgelings. While making this examination, if the animal is nervous and fretful, you can help matters along if an assistant holds up a fore leg. Take the same precaution when examining the hind quarters and legs. By doing so, you will avoid being kicked and can run over the parts more quickly and satisfactorily. Before leaving the body observe if the hips are equally developed, and the animal evenly balanced in this region. Both horses and cattle are liable to hip injury, one of the hips being frequently knocked down. Make sure that both are sound and natural. —Now step to the front again for a careful examination of the front legs and feet. Starting with the elbow, examine for capped elbow; now the knee. It should be wide,
  • 52. ANATOMY OF THE FOOT Examine for Corns. Hind Legs and Feet. long, and deep, and at the same time free from any bony enlargements. The knees must stand strong, too. Is the leg straight? Do you observe any tendency of the knee to lean forward out of line, showing or indicating a “knee sprung” condition? Just below the knee, do you find any cuts or bunches or scars due to interference of the other foot in travel? Look here also for splints; follow along with the fingers to see if splints are present—on the inside of the leg. Be particular about the cannon. The front should be smooth—you want no bunches or scars. Just above the fetlock feel for wind puffs; and note if about the fetlock and pastern joints there are any indications of either ringbones, bunches, or puffs. Now look for side bones; if present, you will find them just at the top of the hoof. They may be on either side. Sidebones are objectionable, and are the lateral cartilages changed into a bony structure. Give the foot considerable attention. The old law of the ancients, “no feet, no horse,” is certainly true in our day. You can overlook many other imperfections and troubles in the horse, but if the feet are bad you do not have much of a horse. A good foot is well shaped, with a healthy-looking hoof and no indication of disease either now or ever before. See that the shape is agreeable. A concave wall is not to be desired, and the heels are not to be contracted. The wall should be perfect—no sand cracks, quarter crack, or softening of the wall at the toe of the foot. —These are both troublesome and cause much lameness. A healthy frog, uninjured by the knife or the blacksmith or other cause is very much to be preferred.
  • 53. The delicate nature of the foot is readily recognized when the various parts are considered in their relation to each other. —In examining these regions give the hocks of the horse special attention. No defect is more serious than bone spavin. You can, as a rule, detect this by standing in front of the horse just a little to the side. If there is any question about the matter, step around to the other side and view the opposite leg. This comparison will let you out of the difficulty, as it is very unusual that this defect should be upon both legs at the same point and developed to the same degree. A spavin is undesirable for the reason that it often produces serious lameness, which frequently is permanent. As it is a bone enlargement, it is something that cannot be remedied. If you are seeking good horses, better reject such as have any spavin defect. In this same region between the hock and the fetlock curbs troubles are located. They appear at the lower part of the hock, directly behind. You can readily detect any enlargement if you will step back five or six feet. The curb, while it may not produce lameness, is altogether undesirable. It looks bad; it shows a weakness in the hock region and often is caused by overwork, consequently the animal with curb disease is one that has not measured up to the work demanded of him. Just above and to the rear of the hock the thorough-pin disease appears, and just in front of and slightly toward the inner side of the hock bog spavin is sometimes to be found. Lameness may come from either of these diseases. Small tumors, puffs and other defects frequently show themselves on the hind legs and the best way is to reject animals having them. While some of these may be caused by accident, the most of them are the result of bad conformation, due to heredity, unimproved blood and bad ancestors. EXAMINING FOR LAMENESS Lameness comes from many causes; maybe from soreness, from disease or from wounds. And lameness is hard to detect. Frequently it seems to be in the shoulder, when in fact it is a puncture in the
  • 54. foot. Again it may seem to be in the fetlock, but the trouble is in the shoulder or fore leg. You must examine for lameness both in the stable and out of the stable. If you find the horse standing squarely upon three feet and resting the fourth foot, you should be suspicious. If you move the horse about and he assumes the same attitude again and still again, you can be certain that he is assuming that position because he wants to rest some part of that member. In testing out the horse for lameness, let no excitement prevail. Under such excitement the horse forgets his lameness or soreness for the time being, and you do not note the trouble. A quiet, slow walk or trot on as hard a road as possible is a desirable sort of examination to give. TESTING THE WIND The free breathing of a horse may be interfered with, and for two reasons. Roaring or whistling, as it is called, is a serious disease of the throat, and, at the same time, an incurable disease. The second disease is known as heaves or bellows, and is also a most serious disease, because it is also incurable. By the use of drugs relief may be given temporarily, but no permanent cure follows. Unscrupulous dealers will resort to dosing for the time being, or until a sale is made. You should guard against this trouble, however, for it is one of the most serious that a horse can have. Upon this subject, Butler has the following to say: “To test the wind and look for two serious conditions and others which may be present, the animal should be made to run at the top of his speed for some considerable distance —a couple hundred yards or more. Practically this run or gallop should be up hill, which will make the test all the better. After giving the horse this gallop, stop him suddenly, step closely up to him and listen to any unusual noise, indicating obstruction of the air passages, and also observe the movements of the flanks for any evidence of the big double jerky expulsion of the air from the lungs characteristic of heavers.”
  • 55. TESTING OF THE PACES No examination is complete that does not make a test of the paces. You want to know how fast the horse can walk, how he trots or paces or how he takes some other gait. Some horses make these movements very gracefully; others very unmannerly. A well-acting horse is one that moves smoothly, regularly, who picks up his feet actively and who places them firmly in their position regardless of the ground or gait. Some horses have a rolling movement of the legs. Avoid these. Others step on the toe or heel. These, too, should be avoided. They suggest some defect or bad conformation. The testing of the paces brings all parts of the body into play and assists in catching other blemishes or defects that you may have overlooked in your previous examination. It gives you another opportunity to examine the wind, to observe the respiration, the heart beatings, the condition of the nostril after work; it shows you also how the animal takes his pace and how he stands. All of this will be of value as indicating the soundness and health of the individual under observation. CONSIDERING FOR A SPECIAL PURPOSE Now, as a last factor of your examination, consider the uses to which the animal is put. If you are looking for breeding animals be sure to know that the udder is not injured. Of what use is a cow with a bad udder? How often do we find a quarter of the udder destroyed or a teat cut or so badly mangled as to be of little use! Some udders are dead, heavy, fleshy; some are diseased, lumpy; and even though the animal is otherwise good you must reject her. If the udder is good, superior in many respects, and shows great milk production, you can often afford to overlook other defects, especially if the result of accident. In the case of horses, a disease or blemish due to accident may be overlooked, if the work to which the animal will be subjected does not interfere, let us say, for breeding purposes. The horse has good conformation, good quality, is healthy and very superior, but
  • 56. unfortunately a leg was broken. Shall she be rejected as a breeder? No heavy work will be required of her—she is wanted for colt raising. Take her; of course you will pay less for her. This accident interferes in no way with her value for breeding purposes. Many cases of accidental injuries are similar to this example among cattle and horses. A good rule is to reject those having defects or blemishes that interfere with functional activity or the work to which you wish to put them. Then, as breeders, reject all with constitutional defects, as bad feet, narrow hocks, coarse disease-appearing bones, and bad conformation and scrubby character.
  • 57. FRACTURES When a bone is broken into two or more parts it is said to be fractured. These may be straight across, up and down, or oblique. Ordinary fractures are easily treated by splints, but sometimes fractures are so serious as to CHAPTER V Wounds and Their Treatment The stockman has all sorts of wounds with which to deal. He may guard his animals with the care and caution of a mother and still find constant bother and worry to face in the daily management of his stock. Today it may be a wound caused by a nail puncture in the foot; tomorrow a cut occasioned by a fence; and then almost immediately another, the result of a kick or a hook; with patience nearly exhausted, now follow bruises of many sorts and unexplainable lacerations. These troubles occur on the best managed farms. There is but one thing to do: meet each case as it occurs and lend such assistance as you can that nature may repair the wrecked tissue at the earliest possible moment. THE KINDS OF WOUNDS Wounds fall into four classes: the clean- cut kind made by something sharp; the torn or lacerated, where ragged edges are left; the bruised, the result of continued pressure or kicks or a knock; and the punctured, like the entrance of a nail or splinter or gunshot.
  • 58. destroy the value of the animal. The latter class is the most difficult in treating, for the reason of the greater penetration that may likely occur. In the case of gunshot, the wound may be on the surface, or it may extend entirely through the region attacked, or even penetrate some vital organ like the heart or the lungs or bowels, and either immediately or within a few days be the cause of death. Fortunately such wounds are rare. The stockman may never have to deal with them at all. There are punctured wounds that are common, however; some, indeed, frequently lead to death. A nail wound is the most serious, perhaps. It is likely that more cases of tetanus or lockjaw are due to nail punctures than to all others combined. After this class comes the lacerated kind. These heal slowly; the tissue being torn and bruised is repaired only through the sloughing off of the injured and now superfluous parts. As a result, even with the most attentive surgical help, the injured part develops its exposed sore, ending finally completely healed, but permanently marked. Bruises may be equally bad, long delayed in healing and very painful. Do you remember the stone bruises of boyhood days? How long it required to develop! And the pain! I shall feel mine for ages to come. The clean-cut wounds, if not too serious, are the least difficult in treating. FIRST STEP IN TREATING The flow of blood is usually associated with ordinary wounds; other than with some bruised and punctured wounds this is always true. Frequently a nail puncture gives off no blood or it is not noticed. However, the blood is present, for, from the very nature of the trouble, blood rushes to the seat, this being nature’s way of repair. Your first step, therefore, is to check the excessive blood flow. If left to itself the blood might do it. Blood has the trick of coagulating or clotting; and this in time will check the flow. But you can assist in forming the clot very simply by applying some finely ground material that the blood may be held on the spot. Absorbent
  • 59. BANDAGING A LEG The method of applying the bandage is shown here. The bandage may be wrapped directly over the hair or over cotton saturated with an antiseptic and placed over the wound. Cleansing the Wound. Making the Bandage. cotton is the best material to use. In case this is not available, use something of like nature—something that is clean, not stored up with germs. Tea is good, as is flour also. Cold water acts favorably, and for the slight, ordinary surface wounds water is usually sufficient. A few drops of some antiseptic in the water, if available, is always advisable, for the freshest water carries its full quota of germs, some of which may cause trouble. A tiny bit of alum powder will be found both effective and not painful. —After the flow of blood has been stopped, cleansing the wound is next in order. All dirt should be carefully removed, the injured flesh cleansed, the torn tissues brought together and stitched, if need be, and antiseptics applied. The water used in bathing the wounded flesh should contain an antiseptic, that the germs present may be destroyed and no live ones admitted by water in cleansing the wound. Any good commercial antiseptic will do; or the old common ones, like corrosive sublimate, one part in a thousand parts of water, or carbolic acid, a teaspoonful in a quart of water. Some powdered antiseptic like iodoform is very desirable for dusting into the wound. —Unless the wound is of little consequence it should be covered and bandaged that no foreign elements be admitted and that some pressure may be given to keep the broken parts together. To secure this effect absorbent cotton,
  • 60. Special Treatment. slightly moistened with the antiseptic, should be laid on the wound, and firmly fastened by strips of clean cotton cloth. By winding this bandage around and about the wound, dressed in this careful way, the wound will be protected, germs will be kept out and nature, thus reinforced, will be enabled to make a rapid recovery. Unless the bandage is disturbed in some way there is no need of changing it under twenty-four or thirty-six hours. If, for any reason, the bandage is displaced, dress as before, and bandage again. —When a cut wound is deep or large, stitching is sometimes required, that the broken parts may be brought together for more rapid healing. Nothing is better for this than a coarse needle and heavy thread. Before stitching, however, the wound should be bathed as previously described. The needle and thread should be soaked in the antiseptic, that no germs may be introduced by means of them. Now you are ready to make the stitches. Place the needle about an eighth to a quarter of an inch from the edge of the wound across to the opposite side. Bring the two ends together and tie, leaving the lips of the wound as close together as possible. If more than a single stitch is necessary, proceed in the same way, placing the second stitch about three-quarters of an inch from the first one; continue as with the first stitch if more are necessary. In case a needle and thread are not available, pins may be used in the emergency. Insert the pin through the two edges and bring the lips together, making them fast by a thread or cord carried from one end to the other several times, alternating to the right and left as presented by the figure eight. Sometimes the wound enlarges and becomes feverish. If such becomes very severe, remove the fastenings and bathe the wound very gently, using a mild antiseptic wash of tepid water in which carbolic acid has been placed.
  • 61. HEALTH AND DISEASE In the upper picture the pigs are treating themselves. Below are shown hogs which died during shipment to market. Avoid any breaking of the healing tissue and do not have the washing solution too strong, else it may injure the delicate tissue growth. A teaspoonful of carbolic acid to a quart of water is strong enough. With lacerated wounds the treatment is very similar. If the wound goes bad and becomes spongy add a tablespoonful of
  • 62. Nail Punctures. acetate of lead and a tablespoonful of sulphate of zinc to the antiseptic solution and apply twice daily. MAKING POST MORTEM EXAMINATIONS The upper right hand picture shows the intestines of a healthy sheep. On the left nodule disease is discovered. The bottom picture illustrates how a carcass may be opened for the examination. —These very frequently cause trouble. You have no way of observing the wound and your only way of judging is from
  • 63. the way the animal walks or acts, and if the hoof is unduly hot. Locating lameness in the stifle joint is a common but inexcusable error, as the action resulting from lameness in the two parts is entirely different. The so-called gravel which is said to enter the sole of the foot and then to work out at the heel is usually the working out of the pus or the matter resulting from a nail puncture or a bruise. If an animal becomes suddenly and severely lame and there be no evidence of any injury to any other part of the leg, such as swelling, heat and pain upon pressure, it is always well to look for puncture in the foot. If the animal stands with the lame foot extended and when walking places the lame foot well forward and brings the well foot up to it, the evidence of puncture is still stronger. To examine the foot properly the shoe should be removed. It is not sufficient to merely scrape the bottom of the foot clean, for if the nail has pulled out and the horn sprung back in position, all trace of its entrance may have been obliterated. To examine the foot properly, tap the hoof with a hammer or knife and the exact spot may be definitely located. If the injury is of a few days’ standing, additional heat in the hoof and, perhaps, slight swelling of the coronet may also be present. In treating such wounds, pare away only such parts of the hoof as necessity requires and introduce a bit of cotton cloth rolled as a string by means of a probe of some kind. Both probe and cotton must be treated with the antiseptic solution. This solution should be a little stronger than for flesh wounds. Make the solution by using a teaspoonful of carbolic acid to only a pint of water. After the cotton has been inserted a few times and withdrawn, each time a fresh cord being used and fully saturated, leave the last one in for a few hours and then repeat the treatment. This should be done three or four times each day. The main point in the treatment of nail puncture of the foot is to provide free exit to all matter that may collect and keep the parts as clean as possible. If this be done, the matter will not be compelled to work out at the heels, and no separation or loss of hoof will occur. Often a very severe wound is made and the treatment acts slowly.
  • 64. Treating Bruises. Leg Wounds. Maggots in Wounds. In case proud flesh accumulates, it should be burned away by a hot iron. After this operation has been performed, the cavity should be filled with balsam of fir and cotton placed over it, a piece of heavy leather fitted to the foot and held fast by the replaced shoe. This will usually end the difficulty. A veterinarian should be called in case the wound is severe or goes bad as the treatment progresses. —In treating bruises a different procedure is necessary. The broken tissue is concealed—beneath the skin and usually under the surface muscles. Bathing with water and acetate of lead—a quart of water and two tablespoonfuls of the acetate—will tend to lessen the inflammation. In time you may have to open the swelling for the pus to get out. After doing so, inject some wash for cleansing, using one quart of water and a tablespoonful of chloride of zinc. If the swelling remains, apply twice each month a salve made by using one teaspoonful of biniodide of mercury and three tablespoonfuls of lard. Wash occasionally, using the chloride of zinc solution. —Cleanse the wound with a wash composed of one tablespoonful of acetate of lead, one tablespoonful of sulphate of zinc, four tablespoonfuls of tincture of arnica and one quart of water. Use this wash frequently, every hour or so, during the first day. After that three or four applications will be sufficient. The sore should be kept lower than the skin during the healing process. If it tends to crowd up, apply a tiny bit—as much as you can place on a one-cent piece—of bichloride of mercury. This will assist in getting an even heal and the skin will grow over, leaving no blemish or swelling. —If the wound has been treated as suggested above there is no possibility of any trouble from maggots. These come from a lack of cleanliness and neglect. Of course, an animal often gets a wound and the owner is not aware of the mishap. Wounds, more or less infrequently treated, those made as the result of castration, occasionally get infected with maggots. When, for any cause, maggots are present, they must be got rid of at once. A good plan is to use chloroform, either by spraying or by throwing it in the wound in small drops from a sponge.
  • 65. The danger from maggots can usually be avoided if a mixture composed of one tablespoonful of turpentine, three tablespoonfuls of tar and two tablespoonfuls of lard or fish oil be smeared all around the border of the wound.
  • 66. CHAPTER VI Making a Post Mortem Examination Even on the best-managed stock farms some animals do get sick and die. Good care and good nursing may be given, but the sick animal frequently does not recover—death often follows very quickly, before you have an opportunity to observe the development of the disease or to secure the services of a veterinarian. Then, again, after a lingering sickness an animal dies, the disease being known or unknown as the case may be. In any event, a post-mortem examination is usually desirable, if for no other reason than that it serves to familiarize you with the organs of the body. With a little experience you can become quite proficient in examining a dead animal, and you can soon learn the difference between healthy and unhealthy organs, between diseased and normal tissues and the relation of the internal parts to the whole body. A post-mortem examination thus enables you to know the cause of the disease—where it is located or whether death is the result of accident or of some fatal disturbance of the system. This examination should be made as soon after death as possible; the longer the delay the greater the changes due to decomposition of the body and its decay back to the original elements from which it has come. Soon after death the stiffening process takes place. This is known as rigor mortis. It may occur within an hour after death and again it may not be complete until twenty-five or thirty hours have passed. Soon after the death stiffening has occurred the tissues soften and decomposition rapidly follows. FIRST THINGS TO DO
  • 67. In making a post-mortem examination, in case the animal has not been moved, the position of the body is to be observed. Look all about you. Is there any evidence of a struggle? Does either the body or the ground appear as if spasms have taken place? It may be a case of poisoning. If such be true, the outward appearance may be further substantiated by the internal condition. If inflammation and irritation of the stomach and bowels are observed, this evidence helps to confirm the first observation. RICKETS IN PIGS Rickets in pigs is due, as in man and other animals, to an improper development of the bone, the result of insufficient mineral matter in the food. The bones are weak and bend or break. It frequently appears after the pigs are weaned. An abundant supply of wood ashes, charcoal, lime and salt is always good for hogs. The appearance of the struggle, however, is not enough to establish a case of poisoning; for struggling is a death characteristic
  • 68. Observe the Discharges. Accidents and Injury. After Removing the Skin. of many diseases. Of course, in making this preliminary examination you will note if death could have been the result of some other reason. Has some obstruction had anything to do with the trouble? Maybe the animal has been caught in some way and not being able to move about has starved to death, or maybe some over-exertion has had something to do with the trouble. Many animals choke, and, not being able to relieve themselves, die. Thousands of farm animals, especially in the West and Southwest, die annually from cold, and not a few from heat. All these things enter into the case and must be considered in reaching a reasonable conclusion. —The next thing to do is to observe the discharges from nose, mouth and other natural openings of the body. External scars and wounds often bear a close relation to the disease and these should be considered in examining the carcass. How do the eyes look? Is there a discharge from the ears? Is the swelling of the abdomen and the bloating more pronounced or different than should be the case in ordinary death? Practice will indicate the lesson that each of these teach. —Farm animals are often killed by stray shots from the guns of hunters and trespassers. A casual observation will indicate if death has been due to this. Again, animals may die from distemper or be eaten up with lice or troubled with itch or mange—you will note these facts as you go along with your work. In the South, where Texas fever is so prevalent, you should look for ticks, as these bring death to thousands of animals each year. Look for the wee tiny ones—they cause the trouble. When cattle are fairly covered with the large ticks death does not ordinarily follow, since the animal has practically become immune to the poison caused by the tick. These large ticks, however, are filled with blood and nutriment, both obtained from the animal, and hence they may rob the animal of blood and nutriment that it ought to have itself. —The skin is now to be removed, so that the color of the tissues and the nature of the blood may be noted. If the blood be thin or black, with a disagreeable odor, you
  • 69. can expect some germ trouble like blood poisoning or an infectious and contagious disease. If the white tissues are yellow you may be reasonably certain that the liver has not done its work as it would have done had it been in a thoroughly healthy condition. In removing the skin and making other observations be cautious that you do not prick your fingers with the knife, since you may convey in this way disease to yourself. If by accident a cut or prick is made, cauterize the wound at once, so as to destroy any germs transmitted in this way to you. EXAMINING THE INTERNAL ORGANS The next step is to examine the internal organs. To do this, place the animal on its side, remove the upper front leg and the ribs over the chest region. The ribs should be removed as near as possible to the backbone so as to give an unobstructed opening over the important organs. This large opening now allows you free access for examination, and an unimpaired view all about the vital organs, if these are entirely exposed. ROUND WORMS IN HOG INTESTINE An infestation with intestinal worms, as shown here, leads to unthriftiness and a loss of flesh. These worms may be expelled by
  • 70. Stomach and Intestines. Kidneys and Bladder. Lungs. giving turpentine in doses of one teaspoonful in milk for three days in succession. While making this opening, observe the watery fluid as it escapes. If a large quantity is present, dropsy or a rupture of the bladder is indicated. If the trouble is due to the latter, an odor in the urine will be quickly noted. When the fluid is red in color, it indicates the presence of blood or some inflammation of the abdomen or the bowels. A large amount of watery fluid in the chest cavity is an indication of some lung trouble; this is further indicated by the tiny attachments running between the lungs and the chest wall. —If the stomach and intestines be abnormally red, congestion is indicated, and if they be quite dark, even purple in color, you may be sure that some kind of inflammation has been the trouble. You will note also if the stomach is hard and compacted; and, if so, indigestion may have been the trouble. The intestines will also show if they be hard and compacted or in any otherwise bad condition. Pass the hands along to see if the intestines are knotted in any place or if nails are present in the stomach. It is not likely that the nails have been the direct cause of death, but this fact helps to indicate the condition of the digestion trap. Often hair balls or parasites will be found; either may clog up the channel and may be the immediate cause of death. I have on more than one occasion found that the fuzz of crimson clover, accumulating in the intestines of horses, rolls up into a hard, compacted ball, and not being able to pass out, becomes an obstruction in the passageway and ultimately causes death. —The urine tells its tale also; a very disagreeable odor indicates some disturbance; and a brownish or dark-red color may indicate a local disease or a constitutional breakdown. Texas fever in cattle produces a very dark or reddish urine, Azoturia in horses, a similar color. Gallstones or gravel are often found in the bladder, and these frequently cause serious disturbance, if not death.
  • 71. Other Observations. —Look the lungs over carefully. See if the natural color is present and if the soft, spongy constituency responds to the same kind of touch as does the thoroughly healthy lung. In health the lungs are a very light pink color. If inflammation has been present this will be indicated by the dark color and the hard density. When the lung is cut apart with the knife further observation should be made. A marble appearance indicates inflammation and hard lumps or tubercles indicate tuberculosis. These tubercles, when cut open, show pus and a cheeselike material, yellow in color—a true indication of the disease. —You should feel the heart to know if it is natural or not, or to see if any of the valves are broken, or if some inflammation has been back of the trouble. The sides of the open cavity should be observed before leaving. Is it spotted, speckled? Are pink spots seen about the ribs? This is an indication of hog cholera, and in itself may lead to a correct interpretation of the disease.
  • 72. CHAPTER VII Common Medicines and Their Actions The common medicines used in treating farm animals are named in the following list, together with origin, action, use, and dose. ACONITE Tincture of aconite is derived from the root of a plant. When used, the heart beats more slowly and the blood pressure is decreased, making the medicine desirable in cases of inflammation. Dose: For horses and cattle, from 10 to 30 drops, and sheep and hogs 5 to 10 drops. ALOES This is usually bought in a powder form. It is brown in color and bitter in taste. Considerable time transpires before action in the bowels takes place. Allow at least 24 hours. It is a physic and blood purifier. Dose: For horses, 4 to 5 tablespoonfuls; cattle, 4 to 8 tablespoonfuls; sheep, 1 to 2 tablespoonfuls; and pigs, 1 to 2 tablespoonfuls. ALUM This mineral salt is used in washes for sore mouth and throat, and cleansing wounds. It may be dusted into wounds in powder form, and is both drying and healing. Dose: Use a tablespoonful to a pint of water.
  • 73. ANISEED This preparation is made from dried berries and ground. It stimulates digestion, sweetens the stomach, and serves as a tonic and appetite maker. Dose: For horses and cattle, a tablespoonful, and for sheep and pigs, a teaspoonful. ARNICA For wounds, sprains, and bruises, tincture of arnica is both cooling and restful. It is made from the dried flowers of a plant, and is for external use. Apply three or four times daily. ARSENIC This medicine comes from the mineral kingdom and is very powerful. In using better get it in some standard medicinal form such as Fowler’s Solution. It is used as a tonic when the stomach is bad and the system run down. Dose: Fowler’s Solution; for horses and cattle, 2 tablespoonfuls; sheep, 1 teaspoonful; pigs, one-half teaspoonful. In giving to stock mix with 4 tablespoonfuls of whiskey, and either use as a drench or add to mash or gruel. BELLADONNA This is a tincture made from a plant. When used it soothes, softens, and relaxes the parts to which applied. It checks inflammation and relieves pain, but must be carefully used. Dose: For horses and cattle, 1 teaspoonful; sheep, 10 drops; pigs, 5 drops. BUTTER OF ANTIMONY This preparation, taken from a mineral, is not used internally. It is a powerful caustic. Its principal use is for curing thrush in horses’
  • 74. feet. TETANUS BACILLI How the germs look under the microscope. The poison produced by them is one of the most violent known in disease. BROMIDE OF POTASSIUM This comes as a white crystal or powder, and is used to quiet the nerves when some trouble like lockjaw has set in. Dose: For horses and cattle, 1 teaspoonful; sheep and hogs, one- half teaspoonful. BINIODIDE OF MERCURY This bright red powder is used chiefly for blistering purposes. It is excellent when a spavin or splint or ringbone is just beginning. In preparing, use one part of the mercury to nine parts of vaseline or
  • 75. lard. Remember, it is a poison, and must be carefully handled, as is true of some other preparations of mercury. CAMPHOR The camphor of commerce is in the form of a gum obtained from a tree by boiling and evaporation. It is used in mixtures for coughs, sore throat, and heaves. It is good also for colic and diarrhœa and assists in lessening pain. It should be given in water. Dose: For horses, 2 to 4 teaspoonfuls; cattle, 4 to 5 teaspoonfuls; pigs and sheep, 2 teaspoonfuls. CANTHARIDES OR SPANISH FLY This is in the form of powder, and is an irritant. For use it should be thoroughly mixed with lard or vaseline. One teaspoonful of the cantharides to 4 tablespoonfuls of lard or vaseline. When so prepared it is excellent as a blister. It can be applied for sweat thickenings or lumps on any part of the body that is not on the bone. It should not be used on curbs or tumors and is not used internally. CARBOLIC ACID This is got from coal tar and petroleum. When full strength and pure it is in the form of crystals, but is generally bought as a liquid. It is a disinfectant and an antiseptic, and while used internally for some purposes, is largely used internally in washes and solutions. Its principal use is in bathing wounds and sores. Care should be taken not to have a wash contain too much of the acid, as it will burn the wound and stop the healing action. It is a corroding poison taken internally. It should be just strong enough to kill bacteria; say, 1 part to 1,000 parts of water. A very good healing salve is made when 5 drops of pure carbolic acid is used to 4 tablespoonfuls of vaseline. CORROSIVE SUBLIMATE
  • 76. This is used externally as an antiseptic and disinfectant. Dissolve 1 part to 100 parts of water. It is a preparation of mercury, is poisonous, but excellent for bathing wounds and open sores. CASTOR OIL This oil is pressed from castor beans. It is a mild physic similar to raw linseed oil. It is not used much for live stock. Dose: For horses and cattle, 1 pint; for sheep, one-quarter pint, and for pigs, 4 tablespoonfuls. CALOMEL This is a heavy white powder and a mineral. Its principal action is as a physic, and it has a cleansing effect on the liver. Hence it is used for all kinds of liver troubles. When dusted in old sores, it is splendid for healing and drying up. Dose: For horses, one-half to 1 teaspoonful; cattle, 1 to 2 teaspoonfuls; sheep and pigs, one-eighth teaspoonful. CROTON OIL This oil is made from seeds, and is one of the most powerful physics known. It should never be used until milder physics do not respond. Use it as a last resort. Dose: For horses, 15 to 20 drops; cattle, 30 to 40 drops; sheep, 5 to 10 drops; and pigs, 2 to 3 drops. In giving, it is best to use in connection with raw linseed oil; of the linseed oil use 1 pint for horses and cattle and one-quarter pint for sheep and pigs. CAUSTIC POTASH This chemical is most easily used when purchased in pencil-like sticks. It is never given internally, but is used to burn warts and growths by wetting the stick and rubbing it over them. It is also used for burning poisonous wounds to kill the poison. It is commonly employed for dishorning calves. When a week or ten days old, and
  • 77. the button of the horn is just appearing, rub the potash over the horn. This usually insures destruction of the horn substance. Wet the stick of potash. See that drippings do not run down the animal’s head. In order to protect the fingers, when using, wrap paper around the stick. CREOLIN This is the product of coal tar and comes in the form of a thick, dark fluid, and, like tar, is harmless. It is frequently used as the basis of salves for wounds, scratches, and like troubles. It is a very effective remedy for killing lice, ticks, or fleas, and is used as a remedy when sheep are afflicted with mange and scab. Dose: Use from 2 to 4 tablespoonfuls to a pint of water and shake well before using. Make up a small quantity at a time, as creolin thus made loses its value after exposure. For disinfecting purposes, 1 part of creolin to 100 parts of water is satisfactory. GENTIAN This is the root of a plant, dried and ground. It is used principally as a tonic, and is very bitter; commonly found in condition powders and is given to animals that are weak and run down. If used alone, give twice a day in the food and place on the tongue with a spoon. Dose: For horses and cattle, 1 tablespoonful; for sheep, a teaspoonful; pigs, one-half teaspoonful. GINGER This is a dried root ground fine, secured from a plant, and acts as a stimulant, relieving gases that accumulate in the stomach. It is an excellent ingredient to use in colic and indigestion preparations. If given alone, doses may be repeated every two or three hours. Dose: For horses and cattle, 1 tablespoonful; sheep, 1 small teaspoonful; pigs, one-half teaspoonful. HYPOSULPHITE OF SODA
  • 78. This salt is frequently used in combination with gentian, equal parts of both, and in other recipes for condition powder. It cleans the blood and builds up the system after weakening diseases. A common preparation is made by using one-half of powdered gentian and one- half of hyposulphite of soda. Mix all together and give two or three times a day to the animal needing it. Dose: For horses and cattle, 1 tablespoonful; sheep, 1 teaspoonful; pigs, one-half teaspoonful. IODINE This dark brown tincture is not often used internally, but is used as a sweat blister and for blistering thickened glands. In using, take a feather, painting the iodine on the lump until it blisters; when the blister appears, grease the part; after two or three days have passed, wash the lump with warm water and soap and blister again. IODIDE OF POTASSIUM This white powder is obtained from the mineral kingdom. When given internally it acts as an absorbent. It is commonly used in cases of dropsy of the belly. In administering, use equal parts of ground gentian root and give twice a day. Dose: For horses and cattle a teaspoonful; for sheep and pigs, one-half teaspoonful. LINSEED OIL This oil is obtained from flaxseed, and is excellent when a mild physic is desired. The easiest and most effective way of giving to animals is in the form of a drench. About 1 pint should be used for horses and cattle. Raw linseed oil is usually preferred to the boiled. LAUDANUM This is made from opium and is used both internally and externally. It is commonly used where there is pain, hence it is
  • 79. excellent for relieving pain and spasms and assists also in checking inflammation. Dose: For horses and cattle, 4 to 6 teaspoonfuls; sheep and pigs, 2 to 4 teaspoonfuls. NUX VOMICA This powder comes from ground seeds, and is used as a nerve stimulant. It is very efficacious for strengthening weak, debilitated animals. A common way is to mix equal parts of gentian and powdered nux vomica thoroughly together. This may be given as a drench, or in the feed or placed at the back of the tongue with a spoon. Dose: For horses and cattle, 1 teaspoonful three times a day; for sheep and pigs, one-half teaspoonful. NITRATE OF SILVER This comes in the form of white penciled sticks. It is excellent for burning off warts, proud flesh in cuts and growths on any part of the body. Just wet the stick and rub it on the parts. Of course, be careful that your fingers are protected from the chemical. It is a poison taken internally. NITRATE OF POTASH This is frequently called saltpeter, and comes as a white crystal or powder. It is used for kidney, lung and blood troubles. It has a very acute action on the kidneys, causing them to secrete an extra amount of urine. Dose: For horses and cattle, 1 teaspoonful; sheep and pigs, one- half teaspoonful. SULPHATE OF COPPER This is commonly known as blue vitriol or bluestone. It is excellent when given internally for checking discharges, especially those of a
  • 80. chronic catarrhal nature. It may also be used as a wash for wounds, when a weak solution is made, and may be dusted on the wound every day or two in case proud flesh forms. SULPHATE OF IRON Green vitriol, or copperas, as it is commonly known, is a splendid mineral tonic, and is commonly used in combination with gentian, equal parts of the two. Use when the system is badly run down. It is also excellent as a worm powder. Dose: For horses and cattle, 1 teaspoonful three times a day; sheep and pigs, one-half teaspoonful. SUGAR OF LEAD This is frequently called acetate of lead. It is seldom used internally, but quite generally externally for healing washes, particularly for the eye. SWEET SPIRITS OF NITER This sweet-tasting and smelling preparation is obtained from alcohol, and is in the form of a clear liquid. It acts upon the kidneys and skin and is commonly given in the drinking water of animals. It is used in combination with other medicines for colic and indigestion. It thus acts upon the bowels and stomach and relieves pain and dissipates the gases. In giving to animals mix in a pint of lukewarm water and give as a drench. Dose: For horses and cattle, 2 to 4 tablespoonfuls; for sheep and pigs, 1 to 2 teaspoonfuls. SPIRITS OF TURPENTINE This is the ordinary turpentine known by all. It is excellent in cases of acute indigestion and colic, and is destructive to bots and the long round worms in horses. When used externally it is as a liniment. When used internally a small quantity is given with raw linseed oil.
  • 81. Colic Mixture. Fly Blister. Dose: For horses and cattle, 4 tablespoonfuls; for sheep and pigs, 1 tablespoonful. SALTS The two common salts used for live stock are Epsom and Glauber. Epsom salts are most frequently used, the chief action being as a physic. Aloes take the places of salts for horses, as it is believed these are much better than the mineral salts. In giving salts to cattle, the drench is most satisfactory. Dose: Use 1 quart of warm water in which place 1 tablespoonful of ginger and 1 tablespoonful of common soda. To this add 1 pint to 11⁄2 pints of salts and dissolve by shaking or stirring. For sheep and pigs, one-quarter of this amount is sufficient. SULPHUR This yellow powder is well known and is a great medicine when given internally. It acts on the blood and purifies it. It is excellent also for killing parasites or germs in the skin, hence it is good for all diseases. When used internally it is best to combine with gentian root. Give once a day for a short period. Dose: For horses and cattle, 1 tablespoonful; sheep and pigs, 1 teaspoonful. SOME COMMON PRESCRIPTIONS —Laudanum, 16 tablespoonfuls; aromatic spirits of ammonia, 12 tablespoonfuls; sulphuric ether, 2 tablespoonfuls; tincture of aconite, 10 drops; ginger, 16 tablespoonfuls. Dissolve in a pint of water. From 10 to 20 tablespoonfuls of this can be given in one-half pint of water. If relief is not secured, repeat in a half hour, follow with a third dose, then with another, giving the doses one-half to one hour apart. —Powdered cantharides, 2 teaspoonfuls; gum camphor powdered, 2 tablespoonfuls; lard, 8 tablespoonfuls. After
  • 82. Red Blister. Cough Mixture. Soothing Ointment. Hoof Ointment. Physic Drench for Horses. thoroughly mixing, rub in 5 to 10 minutes, depending on the severity of the blister desired. —Gum camphor powdered, 2 tablespoonfuls; biniodide of mercury, 2 teaspoonfuls; lard, 8 tablespoonfuls. This should be rubbed in from 5 to 10 minutes. —Belladonna, 2 tablespoonfuls; pulverized opium, 2 tablespoonfuls; gum camphor, pulverized, 2 teaspoonfuls; chloride of ammonia, 2 tablespoonfuls; sulphur, 4 tablespoonfuls. An easy way to give this is to mix with molasses and flour until a paste is secured. —Laudanum, 8 tablespoonfuls; aconite, 4 tablespoonfuls. This is excellent for sprains, and relieves the pain and soreness when applied to a part where there is much inflammation. —Raw linseed oil, one-quarter pound; crude petroleum oil, one-quarter pound; neat’s-foot oil, one-quarter pound; pine tar, one-quarter pound. Mix well and apply every night with a brush all over and under the hoof. A little in the hair above will do no harm. Clean out the hoof before applying. —Aloes, 8 teaspoonfuls; common soda, 1 teaspoonful; ginger, 1 teaspoonful. Dissolve these in a pint of lukewarm water and give as a drench. The horse should be allowed rest the day following its use.