forked from datacarpentry/sql-ecology-lesson
-
Notifications
You must be signed in to change notification settings - Fork 0
/
00-sql-introduction.html
798 lines (760 loc) · 39.8 KB
/
00-sql-introduction.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
<!DOCTYPE html>
<!-- START: inst/pkgdown/templates/layout.html --><!-- Generated by pkgdown: do not edit by hand --><html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta charset="utf-8"><title>Data Management with SQL for Ecologists: Introducing Databases and SQL</title><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="stylesheet" type="text/css" href="assets/styles.css"><script src="assets/scripts.js" type="text/javascript"></script><!-- mathjax --><script type="text/x-mathjax-config">
MathJax.Hub.Config({
config: ["MMLorHTML.js"],
jax: ["input/TeX","input/MathML","output/HTML-CSS","output/NativeMML", "output/PreviewHTML"],
extensions: ["tex2jax.js","mml2jax.js","MathMenu.js","MathZoom.js", "fast-preview.js", "AssistiveMML.js", "a11y/accessibility-menu.js"],
TeX: {
extensions: ["AMSmath.js","AMSsymbols.js","noErrors.js","noUndefined.js"]
},
tex2jax: {
inlineMath: [['\\(', '\\)']],
displayMath: [ ['$$','$$'], ['\\[', '\\]'] ],
processEscapes: true
}
});
</script><script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js" integrity="sha256-nvJJv9wWKEm88qvoQl9ekL2J+k/RWIsaSScxxlsrv8k=" crossorigin="anonymous"></script><!-- Responsive Favicon for The Carpentries --><link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png"><link rel="icon" type="image/png" sizes="32x32" href="favicon-32x32.png"><link rel="icon" type="image/png" sizes="16x16" href="favicon-16x16.png"><link rel="manifest" href="site.webmanifest"><link rel="mask-icon" href="safari-pinned-tab.svg" color="#5bbad5"><meta name="msapplication-TileColor" content="#da532c"><meta name="theme-color" content="#ffffff"></head><body>
<header id="top" class="navbar navbar-expand-md navbar-light bg-white top-nav data"><a class="visually-hidden-focusable skip-link" href="#main-content">Skip to main content</a>
<div class="container-fluid top-nav-container">
<div class="col-md-6">
<div class="large-logo">
<img alt="Data Carpentry" src="assets/images/data-logo.svg"></div>
</div>
<div class="selector-container">
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle bordered-button" type="button" id="dropdownMenu1" data-bs-toggle="dropdown" aria-expanded="false">
<i aria-hidden="true" class="icon" data-feather="eye"></i> Learner View <i data-feather="chevron-down"></i>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1"><li><button class="dropdown-item" type="button" onclick="window.location.href='instructor/00-sql-introduction.html';">Instructor View</button></li>
</ul></div>
</div>
</div>
<hr></header><nav class="navbar navbar-expand-xl navbar-light bg-white bottom-nav data" aria-label="Main Navigation"><div class="container-fluid nav-container">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
<span class="menu-title">Menu</span>
</button>
<div class="nav-logo">
<img class="small-logo" alt="Data Carpentry" src="assets/images/data-logo-sm.svg"></div>
<div class="lesson-title-md">
Data Management with SQL for Ecologists
</div>
<div class="search-icon-sm">
<!-- TODO: do not show until we have search
<i role="img" aria-label="search button" data-feather="search"></i>
-->
</div>
<div class="desktop-nav">
<ul class="navbar-nav me-auto mb-2 mb-lg-0"><li class="nav-item">
<span class="lesson-title">
Data Management with SQL for Ecologists
</span>
</li>
<li class="nav-item">
<a class="nav-link" href="key-points.html">Key Points</a>
</li>
<li class="nav-item">
<a class="nav-link" href="reference.html#glossary">Glossary</a>
</li>
<li class="nav-item">
<a class="nav-link" href="profiles.html">Learner Profiles</a>
</li>
<li class="nav-item dropdown">
<button class="nav-link dropdown-toggle" id="navbarDropdown" data-bs-toggle="dropdown" aria-expanded="false">
More <i data-feather="chevron-down"></i>
</button>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown"><li><a class="dropdown-item" href="discuss.html">Discussion</a></li><li><a class="dropdown-item" href="reference.html">Reference</a></li>
</ul></li>
</ul></div>
<form class="d-flex col-md-2 search-form">
<fieldset disabled><input class="form-control me-2 searchbox" type="search" placeholder="Search" aria-label="Search"><button class="btn btn-outline-success tablet-search-button" type="submit">
<i class="search-icon" data-feather="search" role="img" aria-label="search button"></i>
</button>
</fieldset></form>
</div><!--/div.container-fluid -->
</nav><div class="col-md-12 mobile-title">
Data Management with SQL for Ecologists
</div>
<aside class="col-md-12 lesson-progress"><div style="width: 0%" class="percentage">
0%
</div>
<div class="progress data">
<div class="progress-bar data" role="progressbar" style="width: 0%" aria-valuenow="0" aria-label="Lesson Progress" aria-valuemin="0" aria-valuemax="100">
</div>
</div>
</aside><div class="container">
<div class="row">
<!-- START: inst/pkgdown/templates/navbar.html -->
<div id="sidebar-col" class="col-lg-4">
<div id="sidebar" class="sidebar">
<nav aria-labelledby="flush-headingEleven"><button role="button" aria-label="close menu" alt="close menu" aria-expanded="true" aria-controls="sidebar" class="collapse-toggle">
<i class="search-icon" data-feather="x" role="img"></i>
</button>
<div class="sidebar-inner">
<div class="row mobile-row">
<div class="col">
<div class="sidenav-view-selector">
<div class="accordion accordion-flush" id="accordionFlush9">
<div class="accordion-item">
<h2 class="accordion-header" id="flush-headingNine">
<button class="accordion-button collapsed" id="instructor" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseNine" aria-expanded="false" aria-controls="flush-collapseNine">
<i id="eye" aria-hidden="true" class="icon" data-feather="eye"></i> Learner View
</button>
</h2>
<div id="flush-collapseNine" class="accordion-collapse collapse" aria-labelledby="flush-headingNine" data-bs-parent="#accordionFlush2">
<div class="accordion-body">
<a href="instructor/00-sql-introduction.html">Instructor View</a>
</div>
</div>
</div><!--/div.accordion-item-->
</div><!--/div.accordion-flush-->
</div><!--div.sidenav-view-selector -->
</div><!--/div.col -->
<hr></div><!--/div.mobile-row -->
<div class="accordion accordion-flush" id="accordionFlush11">
<div class="accordion-item">
<button id="chapters" class="accordion-button show" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseEleven" aria-expanded="false" aria-controls="flush-collapseEleven">
<h2 class="accordion-header chapters" id="flush-headingEleven">
EPISODES
</h2>
</button>
<div id="flush-collapseEleven" class="accordion-collapse show collapse" aria-labelledby="flush-headingEleven" data-bs-parent="#accordionFlush11">
<div class="accordion-body">
<div class="accordion accordion-flush" id="accordionFlush1">
<div class="accordion-item">
<div class="accordion-header" id="flush-heading1">
<a href="index.html">Summary and Setup</a>
</div><!--/div.accordion-header-->
</div><!--/div.accordion-item-->
</div><!--/div.accordion-flush-->
<div class="accordion accordion-flush" id="accordionFlushcurrent">
<div class="accordion-item">
<div class="accordion-header" id="flush-headingcurrent">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapsecurrent" aria-expanded="true" aria-controls="flush-collapsecurrent">
<span class="visually-hidden">Current Chapter</span>
<span class="current-chapter">
1. Introducing Databases and SQL
</span>
</button>
</div><!--/div.accordion-header-->
<div id="flush-collapsecurrent" class="accordion-collapse collapse show" aria-labelledby="flush-headingcurrent" data-bs-parent="#accordionFlushcurrent">
<div class="accordion-body">
<ul><li><a href="#motivation">Motivation</a></li>
<li><a href="#databases">Databases</a></li>
</ul></div><!--/div.accordion-body-->
</div><!--/div.accordion-collapse-->
</div><!--/div.accordion-item-->
</div><!--/div.accordion-flush-->
<div class="accordion accordion-flush" id="accordionFlush3">
<div class="accordion-item">
<div class="accordion-header" id="flush-heading3">
<a href="01-sql-basic-queries.html">2. Accessing Data With Queries</a>
</div><!--/div.accordion-header-->
</div><!--/div.accordion-item-->
</div><!--/div.accordion-flush-->
<div class="accordion accordion-flush" id="accordionFlush4">
<div class="accordion-item">
<div class="accordion-header" id="flush-heading4">
<a href="02-sql-aggregation.html">3. Aggregating and Grouping Data</a>
</div><!--/div.accordion-header-->
</div><!--/div.accordion-item-->
</div><!--/div.accordion-flush-->
<div class="accordion accordion-flush" id="accordionFlush5">
<div class="accordion-item">
<div class="accordion-header" id="flush-heading5">
<a href="03-sql-joins.html">4. Combining Data With Joins</a>
</div><!--/div.accordion-header-->
</div><!--/div.accordion-item-->
</div><!--/div.accordion-flush-->
</div>
</div>
</div>
<hr class="half-width"><div class="accordion accordion-flush resources" id="accordionFlush12">
<div class="accordion-item">
<h2 class="accordion-header" id="flush-headingTwelve">
<button class="accordion-button collapsed" id="resources" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseTwelve" aria-expanded="false" aria-controls="flush-collapseTwelve">
RESOURCES
</button>
</h2>
<div id="flush-collapseTwelve" class="accordion-collapse collapse" aria-labelledby="flush-headingTwelve" data-bs-parent="#accordionFlush12">
<div class="accordion-body">
<ul><li>
<a href="key-points.html">Key Points</a>
</li>
<li>
<a href="reference.html#glossary">Glossary</a>
</li>
<li>
<a href="profiles.html">Learner Profiles</a>
</li>
<li><a href="discuss.html">Discussion</a></li><li><a href="reference.html">Reference</a></li>
</ul></div>
</div>
</div>
</div>
<hr class="half-width resources"><a href="aio.html">See all in one page</a>
<hr class="d-none d-sm-block d-md-none"><div class="d-grid gap-1">
</div>
</div><!-- /div.accordion -->
</div><!-- /div.sidebar-inner -->
</nav></div><!-- /div.sidebar -->
</div><!-- /div.sidebar-col -->
<!-- END: inst/pkgdown/templates/navbar.html-->
<!-- START: inst/pkgdown/templates/content-instructor.html -->
<div class="col-xl-8 col-lg-12 primary-content">
<nav class="lesson-content mx-md-4" aria-label="Previous and Next Chapter"><!-- content for small screens --><div class="d-block d-sm-block d-md-none">
<a class="chapter-link" href="index.html"><i aria-hidden="true" class="small-arrow" data-feather="arrow-left"></i>Previous</a>
<a class="chapter-link float-end" href="01-sql-basic-queries.html">Next<i aria-hidden="true" class="small-arrow" data-feather="arrow-right"></i></a>
</div>
<!-- content for large screens -->
<div class="d-none d-sm-none d-md-block">
<a class="chapter-link" href="index.html" rel="prev">
<i aria-hidden="true" class="small-arrow" data-feather="arrow-left"></i>
Home
</a>
<a class="chapter-link float-end" href="01-sql-basic-queries.html" rel="next">
Next: Accessing Data With...
<i aria-hidden="true" class="small-arrow" data-feather="arrow-right"></i>
</a>
</div>
<hr></nav><main id="main-content" class="main-content"><div class="container lesson-content">
<h1>Introducing Databases and SQL</h1>
<p> Last updated on 2023-04-21 |
<a href="https://github.com/datacarpentry/sql-ecology-lesson/edit/main/episodes/00-sql-introduction.md" class="external-link">Edit this page <i aria-hidden="true" data-feather="edit"></i></a></p>
<div class="text-end">
<button role="button" aria-pressed="false" tabindex="0" id="expand-code" class="pull-right"> Expand All Solutions <i aria-hidden="true" data-feather="plus"></i></button>
</div>
<div class="overview card">
<h2 class="card-header">Overview</h2>
<div class="row g-0">
<div class="col-md-4">
<div class="card-body">
<div class="inner">
<h3 class="card-title">Questions</h3>
<ul><li>What is a relational database and why should I use it?</li>
<li>What is SQL?</li>
</ul></div>
</div>
</div>
<div class="col-md-8">
<div class="card-body">
<div class="inner bordered">
<h3 class="card-title">Objectives</h3>
<ul><li>Describe why relational databases are useful.</li>
<li>Create and populate a database from a text file.</li>
<li>Define SQLite data types.</li>
</ul></div>
</div>
</div>
</div>
</div>
<div class="section level3">
<h3 id="setup">Setup<a class="anchor" aria-label="anchor" href="#setup"></a></h3>
<p><em>Note: this should have been done by participants before the start
of the workshop.</em></p>
<p>We use <a href="https://sqlitebrowser.org/" class="external-link">DB Browser for SQLite</a>
and the <a href="https://figshare.com/articles/Portal_Project_Teaching_Database/1314459" class="external-link">Portal
Project dataset</a> throughout this lesson. See <a href="index.html#setup">Setup</a> for instructions on how to download the
data, and also how to install DB Browser for SQLite.</p>
</div>
<section id="motivation"><h2 class="section-heading">Motivation<a class="anchor" aria-label="anchor" href="#motivation"></a>
</h2>
<hr class="half-width"><p>To start, let’s orient ourselves in our project workflow. Previously,
we used Excel and OpenRefine to go from messy, human created data to
cleaned, computer-readable data. Now we’re going to move to the next
piece of the data workflow, using the computer to read in our data, and
then use it for analysis and visualization.</p>
<div class="section level3">
<h3 id="what-is-sql">What is SQL?<a class="anchor" aria-label="anchor" href="#what-is-sql"></a></h3>
<p>SQL stands for Structured Query Language. SQL allows us to interact
with relational databases through queries. These queries can allow you
to perform a number of actions such as: insert, select, update and
delete information in a database.</p>
</div>
<div class="section level3">
<h3 id="dataset-description">Dataset Description<a class="anchor" aria-label="anchor" href="#dataset-description"></a></h3>
<p>The data we will be using is a time-series for a small mammal
community in southern Arizona. This is part of a project studying the
effects of rodents and ants on the plant community that has been running
for almost 40 years. The rodents are sampled on a series of 24 plots,
with different experimental manipulations controlling which rodents are
allowed to access which plots.</p>
<p>This is a real dataset that has been used in over 100 publications.
We’ve simplified it for the workshop, but you can download the <a href="https://esapubs.org/archive/ecol/E090/118/" class="external-link">full dataset</a> and
work with it using exactly the same tools we’ll learn about today.</p>
</div>
<div class="section level3">
<h3 id="questions">Questions<a class="anchor" aria-label="anchor" href="#questions"></a></h3>
<p>Let’s look at some of the cleaned spreadsheets you downloaded during
<a href="index.html#setup">Setup</a> to complete this challenge. You’ll need
the following three files:</p>
<ul><li><code>surveys.csv</code></li>
<li><code>species.csv</code></li>
<li><code>plots.csv</code></li>
</ul><div id="challenge" class="callout discussion">
<div class="callout-square">
<i class="callout-icon" data-feather="message-circle"></i>
</div>
<div id="challenge" class="callout-inner">
<h3 class="callout-title">Challenge<a class="anchor" aria-label="anchor" href="#challenge"></a>
</h3>
<div class="callout-content">
<p>Open each of these csv files and explore them. What information is
contained in each file? Specifically, if I had the following research
questions:</p>
<ul><li>How has the hindfoot length and weight of <em>Dipodomys</em> species
changed over time?</li>
<li>What is the average weight of each species, per year?</li>
<li>What information can I learn about <em>Dipodomys</em> species in the
2000s, over time?</li>
</ul><p>What would I need to answer these questions? Which files have the
data I need? What operations would I need to perform if I were doing
these analyses by hand?</p>
</div>
</div>
</div>
</div>
<div class="section level3">
<h3 id="goals">Goals<a class="anchor" aria-label="anchor" href="#goals"></a></h3>
<p>In order to answer the questions described above, we’ll need to do
the following basic data operations:</p>
<ul><li>select subsets of the data (rows and columns)</li>
<li>group subsets of data</li>
<li>do math and other calculations</li>
<li>combine data across spreadsheets</li>
</ul><p>In addition, we don’t want to do this manually! Instead of searching
for the right pieces of data ourselves, or clicking between
spreadsheets, or manually sorting columns, we want to make the computer
do the work.</p>
<p>In particular, we want to use a tool where it’s easy to repeat our
analysis in case our data changes. We also want to do all this searching
without actually modifying our source data.</p>
<p>Putting our data into a relational database and using SQL will help
us achieve these goals.</p>
<div id="definition-relational-database" class="callout callout">
<div class="callout-square">
<i class="callout-icon" data-feather="bell"></i>
</div>
<div id="definition-relational-database" class="callout-inner">
<h3 class="callout-title">Definition: <em>Relational Database</em><a class="anchor" aria-label="anchor" href="#definition-relational-database"></a>
</h3>
<div class="callout-content">
<p>A relational database stores data in <em>relations</em> made up of
<em>records</em> with <em>fields</em>. The relations are usually
represented as <em>tables</em>; each record is usually shown as a row,
and the fields as columns. In most cases, each record will have a unique
identifier, called a <em>key</em>, which is stored as one of its fields.
Records may also contain keys that refer to records in other tables,
which enables us to combine information from two or more sources.</p>
</div>
</div>
</div>
</div>
</section><section id="databases"><h2 class="section-heading">Databases<a class="anchor" aria-label="anchor" href="#databases"></a>
</h2>
<hr class="half-width"><div class="section level3">
<h3 id="why-use-relational-databases">Why use relational databases<a class="anchor" aria-label="anchor" href="#why-use-relational-databases"></a></h3>
<p>Using a relational database serves several purposes.</p>
<ul><li>It keeps your data separate from your analysis.
<ul><li>This means there’s no risk of accidentally changing data when you
analyze it.</li>
<li>If we get new data we can rerun the query.</li>
</ul></li>
<li>It’s fast, even for large amounts of data.</li>
<li>It improves quality control of data entry (type constraints and use
of forms in MS Access, Filemaker, Oracle Application Express etc.)</li>
<li>The concepts of relational database querying are core to
understanding how to do similar things using programming languages such
as R or Python.</li>
</ul></div>
<div class="section level3">
<h3 id="database-management-systems">Database Management Systems<a class="anchor" aria-label="anchor" href="#database-management-systems"></a></h3>
<p>There are different database management systems to work with
relational databases such as SQLite, MySQL, PostgreSQL, MSSQL Server,
and many more. Each of them differ mainly based on their scalability,
but they all share the same core principles of relational databases. In
this lesson, we use SQLite to introduce you to SQL and data retrieval
from a relational database.</p>
</div>
<div class="section level3">
<h3 id="relational-databases">Relational databases<a class="anchor" aria-label="anchor" href="#relational-databases"></a></h3>
<p>Let’s look at a pre-existing database, the
<code>portal_mammals.sqlite</code> file from the Portal Project dataset
that we downloaded during <a href="index.html#setup">Setup</a>. Click on the
“Open Database” button, select the portal_mammals.sqlite file, and click
“Open” to open the database.</p>
<p>You can see the tables in the database by looking at the left hand
side of the screen under Database Structure tab. Here you will see a
list under “Tables.” Each item listed here corresponds to one of the
<code>csv</code> files we were exploring earlier. To see the contents of
any table, right-click on it, and then click the “Browse Table” from the
menu, or select the “Browse Data” tab next to the “Database Structure”
tab and select the wanted table from the dropdown named “Table”. This
will give us a view that we’re used to - a copy of the table. Hopefully
this helps to show that a database is, in some sense, just a collection
of tables, where there’s some value in the tables that allows them to be
connected to each other (the “related” part of “relational
database”).</p>
<p>The “Database Structure” tab also provides some metadata about each
table. If you click on the down arrow next to a table name, you will see
information about the columns, which in databases are referred to as
“fields,” and their assigned data types. (The rows of a database table
are called <em>records</em>.) Each field contains one variety or type of
data, often numbers or text. You can see in the <code>surveys</code>
table that most fields contain numbers (BIGINT, or big integer, and
FLOAT, or floating point numbers/decimals) while the
<code>species</code> table is entirely made up of text fields.</p>
<p>The “Execute SQL” tab is blank now - this is where we’ll be typing
our queries to retrieve information from the database tables.</p>
<p>To summarize:</p>
<ul><li>Relational databases store data in tables with fields (columns) and
records (rows)</li>
<li>Data in tables has types, and all values in a field have the same
type (<a href="#datatypes">list of data types</a>)</li>
<li>Queries let us look up data or make calculations based on
columns</li>
</ul></div>
<div class="section level3">
<h3 id="database-design">Database Design<a class="anchor" aria-label="anchor" href="#database-design"></a></h3>
<ul><li>Every row-column combination contains a single <em>atomic</em>
value, i.e., not containing parts we might want to work with
separately.</li>
<li>One field per type of information</li>
<li>No redundant information
<ul><li>Split into separate tables with one table per class of
information</li>
<li>Needs an identifier in common between tables – shared column - to
reconnect (known as a <em>foreign key</em>).</li>
</ul></li>
</ul></div>
<div class="section level3">
<h3 id="import">Import<a class="anchor" aria-label="anchor" href="#import"></a></h3>
<p>Before we get started with writing our own queries, we’ll create our
own database. We’ll be creating this database from the three
<code>csv</code> files we downloaded earlier. Close the currently open
database (<strong>File > Close Database</strong>) and then follow
these instructions:</p>
<ol style="list-style-type: decimal"><li>Start a New Database</li>
</ol><ul><li>Click the <strong>New Database</strong> button</li>
<li>Give a name and click Save to create the database in the opened
folder</li>
<li>In the “Edit table definition” window that pops up, click cancel as
we will be importing tables, not creating them from scratch</li>
</ul><ol start="2" style="list-style-type: decimal"><li>Select <strong>File >> Import >> Table from CSV
file…</strong>
</li>
<li>Choose <code>surveys.csv</code> from the data folder we downloaded
and click <strong>Open</strong>.</li>
<li>Give the table a name that matches the file name
(<code>surveys</code>), or use the default</li>
<li>If the first row has column headings, be sure to check the box next
to “Column names in first line”.</li>
<li>Be sure the field separator and quotation options are correct. If
you’re not sure which options are correct, test some of the options
until the preview at the bottom of the window looks right.</li>
<li>Press <strong>OK</strong>, you should subsequently get a message
that the table was imported.</li>
<li>Back on the Database Structure tab, you should now see the table
listed. Right click on the table name and choose <strong>Modify
Table</strong>, or click on the <strong>Modify Table</strong> button
just under the tabs and above the table list.</li>
<li>Click <strong>Save</strong> if asked to save all pending
changes.</li>
<li>In the center panel of the window that appears, set the data types
for each field using the suggestions in the table below (this includes
fields from the <code>plots</code> and <code>species</code> tables
also).</li>
<li>Finally, click <strong>OK</strong> one more time to confirm the
operation. Then click the <strong>Write Changes</strong> button to save
the database.</li>
</ol><table style="width:100%;" class="table"><colgroup><col width="21%"><col width="42%"><col width="29%"><col width="6%"></colgroup><thead><tr class="header"><th>Field</th>
<th align="left">Data Type</th>
<th>Motivation</th>
<th>Table(s)</th>
</tr></thead><tbody><tr class="odd"><td>day</td>
<td align="left">INTEGER</td>
<td>Having data as numeric allows for meaningful arithmetic and
comparisons</td>
<td>surveys</td>
</tr><tr class="even"><td>genus</td>
<td align="left">TEXT</td>
<td>Field contains text data</td>
<td>species</td>
</tr><tr class="odd"><td>hindfoot_length</td>
<td align="left">REAL</td>
<td>Field contains measured numeric data</td>
<td>surveys</td>
</tr><tr class="even"><td>month</td>
<td align="left">INTEGER</td>
<td>Having data as numeric allows for meaningful arithmetic and
comparisons</td>
<td>surveys</td>
</tr><tr class="odd"><td>plot_id</td>
<td align="left">INTEGER</td>
<td>Field contains numeric data</td>
<td>plots, surveys</td>
</tr><tr class="even"><td>plot_type</td>
<td align="left">TEXT</td>
<td>Field contains text data</td>
<td>plots</td>
</tr><tr class="odd"><td>record_id</td>
<td align="left">INTEGER</td>
<td>Field contains numeric data</td>
<td>surveys</td>
</tr><tr class="even"><td>sex</td>
<td align="left">TEXT</td>
<td>Field contains text data</td>
<td>surveys</td>
</tr><tr class="odd"><td>species_id</td>
<td align="left">TEXT</td>
<td>Field contains text data</td>
<td>species, surveys</td>
</tr><tr class="even"><td>species</td>
<td align="left">TEXT</td>
<td>Field contains text data</td>
<td>species</td>
</tr><tr class="odd"><td>taxa</td>
<td align="left">TEXT</td>
<td>Field contains text data</td>
<td>species</td>
</tr><tr class="even"><td>weight</td>
<td align="left">REAL</td>
<td>Field contains measured numerical data</td>
<td>surveys</td>
</tr><tr class="odd"><td>year</td>
<td align="left">INTEGER</td>
<td>Allows for meaningful arithmetic and comparisons</td>
<td>surveys</td>
</tr></tbody></table><div id="challenge-1" class="callout discussion">
<div class="callout-square">
<i class="callout-icon" data-feather="message-circle"></i>
</div>
<div id="challenge-1" class="callout-inner">
<h3 class="callout-title">Challenge<a class="anchor" aria-label="anchor" href="#challenge-1"></a>
</h3>
<div class="callout-content">
<ul><li>Import the <code>plots</code> and <code>species</code> tables</li>
</ul></div>
</div>
</div>
<p>You can also use this same approach to append new fields to an
existing table.</p>
</div>
<div class="section level3">
<h3 id="adding-fields-to-existing-tables">Adding fields to existing tables<a class="anchor" aria-label="anchor" href="#adding-fields-to-existing-tables"></a></h3>
<ol style="list-style-type: decimal"><li>Go to the “Database Structure” tab, right click on the table you’d
like to add data to, and choose <strong>Modify Table</strong>, or click
on the <strong>Modify Table</strong> just under the tabs and above the
table.</li>
<li>Click the <strong>Add Field</strong> button to add a new field and
assign it a data type.</li>
</ol></div>
<div class="section level3">
<h3 id="datatypes">Data types<a class="anchor" aria-label="anchor" href="#datatypes"></a></h3>
<table class="table"><colgroup><col width="33%"><col width="66%"></colgroup><thead><tr class="header"><th>Data type</th>
<th align="left">Description</th>
</tr></thead><tbody><tr class="odd"><td>CHARACTER(n)</td>
<td align="left">Character string. Fixed-length n</td>
</tr><tr class="even"><td>VARCHAR(n) or CHARACTER VARYING(n)</td>
<td align="left">Character string. Variable length. Maximum length
n</td>
</tr><tr class="odd"><td>BINARY(n)</td>
<td align="left">Binary string. Fixed-length n</td>
</tr><tr class="even"><td>BOOLEAN</td>
<td align="left">Stores TRUE or FALSE values</td>
</tr><tr class="odd"><td>VARBINARY(n) or BINARY VARYING(n)</td>
<td align="left">Binary string. Variable length. Maximum length n</td>
</tr><tr class="even"><td>INTEGER(p)</td>
<td align="left">Integer numerical (no decimal).</td>
</tr><tr class="odd"><td>SMALLINT</td>
<td align="left">Integer numerical (no decimal).</td>
</tr><tr class="even"><td>INTEGER</td>
<td align="left">Integer numerical (no decimal).</td>
</tr><tr class="odd"><td>BIGINT</td>
<td align="left">Integer numerical (no decimal).</td>
</tr><tr class="even"><td>DECIMAL(p,s)</td>
<td align="left">Exact numerical, precision p, scale s.</td>
</tr><tr class="odd"><td>NUMERIC(p,s)</td>
<td align="left">Exact numerical, precision p, scale s. (Same as
DECIMAL)</td>
</tr><tr class="even"><td>FLOAT(p)</td>
<td align="left">Approximate numerical, mantissa precision p. A floating
number in base 10 exponential notation.</td>
</tr><tr class="odd"><td>REAL</td>
<td align="left">Approximate numerical</td>
</tr><tr class="even"><td>FLOAT</td>
<td align="left">Approximate numerical</td>
</tr><tr class="odd"><td>DOUBLE PRECISION</td>
<td align="left">Approximate numerical</td>
</tr><tr class="even"><td>DATE</td>
<td align="left">Stores year, month, and day values</td>
</tr><tr class="odd"><td>TIME</td>
<td align="left">Stores hour, minute, and second values</td>
</tr><tr class="even"><td>TIMESTAMP</td>
<td align="left">Stores year, month, day, hour, minute, and second
values</td>
</tr><tr class="odd"><td>INTERVAL</td>
<td align="left">Composed of a number of integer fields, representing a
period of time, depending on the type of interval</td>
</tr><tr class="even"><td>ARRAY</td>
<td align="left">A set-length and ordered collection of elements</td>
</tr><tr class="odd"><td>MULTISET</td>
<td align="left">A variable-length and unordered collection of
elements</td>
</tr><tr class="even"><td>XML</td>
<td align="left">Stores XML data</td>
</tr></tbody></table></div>
<div class="section level3">
<h3 id="datatypediffs">SQL Data Type Quick Reference<a class="anchor" aria-label="anchor" href="#datatypediffs"></a></h3>
<p>Different databases offer different choices for the data type
definition.</p>
<p>The following table shows some of the common names of data types
between the various database platforms:</p>
<table class="table"><colgroup><col width="19%"><col width="38%"><col width="26%"><col width="5%"><col width="4%"><col width="4%"></colgroup><thead><tr class="header"><th align="left">Data type</th>
<th align="left">Access</th>
<th align="left">SQLServer</th>
<th align="left">Oracle</th>
<th align="left">MySQL</th>
<th align="left">PostgreSQL</th>
</tr></thead><tbody><tr class="odd"><td align="left">boolean</td>
<td align="left">Yes/No</td>
<td align="left">Bit</td>
<td align="left">Byte</td>
<td align="left">N/A</td>
<td align="left">Boolean</td>
</tr><tr class="even"><td align="left">integer</td>
<td align="left">Number (integer)</td>
<td align="left">Int</td>
<td align="left">Number</td>
<td align="left">Int / Integer</td>
<td align="left">Int / Integer</td>
</tr><tr class="odd"><td align="left">float</td>
<td align="left">Number (single)</td>
<td align="left">Float / Real</td>
<td align="left">Number</td>
<td align="left">Float</td>
<td align="left">Numeric</td>
</tr><tr class="even"><td align="left">currency</td>
<td align="left">Currency</td>
<td align="left">Money</td>
<td align="left">N/A</td>
<td align="left">N/A</td>
<td align="left">Money</td>
</tr><tr class="odd"><td align="left">string (fixed)</td>
<td align="left">N/A</td>
<td align="left">Char</td>
<td align="left">Char</td>
<td align="left">Char</td>
<td align="left">Char</td>
</tr><tr class="even"><td align="left">string (variable)</td>
<td align="left">Text (<256) / Memo (65k+)</td>
<td align="left">Varchar</td>
<td align="left">Varchar2</td>
<td align="left">Varchar</td>
<td align="left">Varchar</td>
</tr><tr class="odd"><td align="left">binary object OLE Object Memo Binary (fixed up to
8K)</td>
<td align="left">Varbinary (<8K)</td>
<td align="left">Image (<2GB) Long</td>
<td align="left">Raw Blob</td>
<td align="left">Text Binary</td>
<td align="left">Varbinary</td>
</tr></tbody></table><div id="keypoints1" class="callout keypoints">
<div class="callout-square">
<i class="callout-icon" data-feather="key"></i>
</div>
<div class="callout-inner">
<h3 class="callout-title">Keypoints<a class="anchor" aria-label="anchor" href="#keypoints1"></a>
</h3>
<div class="callout-content">
<ul><li>SQL allows us to select and group subsets of data, do math and other
calculations, and combine data.</li>
<li>A relational database is made up of tables which are related to each
other by shared keys.</li>
<li>Different database management systems (DBMS) use slightly different
vocabulary, but they are all based on the same ideas.</li>
</ul></div>
</div>
</div>
</div>
</section></div> <!-- / div.lesson-content -->
</main><!-- / main#main-content.main-content --><nav class="bottom-pagination mx-md-4" aria-label="Previous and Next Chapter"><div class="d-block d-sm-block d-md-none">
<a class="chapter-link" href="index.html"><i aria-hidden="true" class="small-arrow" data-feather="arrow-left"></i>Previous</a>
<a class="chapter-link float-end" href="01-sql-basic-queries.html">Next<i aria-hidden="true" class="small-arrow" data-feather="arrow-right"></i></a>
</div>
<!-- content for large screens -->
<div class="d-none d-sm-none d-md-block">
<a class="chapter-link" href="index.html" rel="prev">
<i aria-hidden="true" class="small-arrow" data-feather="arrow-left"></i>
Home
</a>
<a class="chapter-link float-end" href="01-sql-basic-queries.html" rel="next">
Next: Accessing Data With...
<i aria-hidden="true" class="small-arrow" data-feather="arrow-right"></i>
</a>
</div>
</nav></div> <!-- / div.primary-content.col-xs-12 -->
<!-- END: inst/pkgdown/templates/content-instructor.html-->
</div><!--/div.row-->
<footer class="row footer mx-md-3"><hr><div class="col-md-6">
<p>This lesson is subject to the <a href="CODE_OF_CONDUCT.html">Code of Conduct</a></p>
<p>
<a href="https://github.com/datacarpentry/sql-ecology-lesson/edit/main/episodes/00-sql-introduction.md" class="external-link">Edit on GitHub</a>
| <a href="https://github.com/datacarpentry/sql-ecology-lesson/blob/main/CONTRIBUTING.md" class="external-link">Contributing</a>
| <a href="https://github.com/datacarpentry/sql-ecology-lesson/" class="external-link">Source</a></p>
<p><a href="https://github.com/datacarpentry/sql-ecology-lesson/blob/main/CITATION" class="external-link">Cite</a> | <a href="mailto:[email protected]">Contact</a> | <a href="https://carpentries.org/about/" class="external-link">About</a></p>
</div>
<div class="col-md-6">
<p>Materials licensed under <a href="LICENSE.html">CC-BY 4.0</a> by the authors</p>
<p><a href="https://creativecommons.org/licenses/by-sa/4.0/" class="external-link">Template licensed under CC-BY 4.0</a> by <a href="https://carpentries.org" class="external-link">The Carpentries</a></p>
<p>Built with <a href="https://github.com/carpentries/sandpaper/tree/0.14.0" class="external-link">sandpaper (0.14.0)</a>,
<a href="https://github.com/carpentries/pegboard/tree/0.7.1" class="external-link">pegboard (0.7.1)</a>,
and <a href="https://github.com/carpentries/varnish/tree/0.3.1" class="external-link">varnish (0.3.1)</a>.</p>
</div>
</footer></div> <!-- / div.container -->
<div id="to-top">
<a href="#top">
<i class="search-icon" data-feather="arrow-up" role="img" aria-label="Back to top"></i><br><span class="d-none d-sm-none d-md-none d-lg-none d-xl-block">Back</span> To Top
</a>
</div>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "TrainingMaterial",
"@id": "https://datacarpentry.github.io/sql-ecology-lesson/00-sql-introduction.html",
"dct:conformsTo": "https://bioschemas.org/profiles/TrainingMaterial/1.0-RELEASE",
"description": "A Carpentries Lesson teaching foundational data and coding skills to researchers worldwide",
"keywords": "software, data, lesson, The Carpentries",
"name": "Introducing Databases and SQL",
"creativeWorkStatus": "active",
"url": "https://datacarpentry.github.io/sql-ecology-lesson/00-sql-introduction.html",
"identifier": "https://datacarpentry.github.io/sql-ecology-lesson/00-sql-introduction.html",
"dateCreated": "2015-02-10",
"dateModified": "2023-04-21",
"datePublished": "2023-10-10"
}
</script><script>
feather.replace();
</script><!-- Matomo
2022-11-07: we have gotten a notification that we have an overage for our
tracking and I'm pretty sure this has to do with Workbench usage.
Considering that I am not _currently_ using this tracking because I do not
yet know how to access the data, I am turning this off for now.
<script>
var _paq = window._paq = window._paq || [];
/* tracker methods like "setCustomDimension" should be called before "trackPageView" */
_paq.push(["setDocumentTitle", document.domain + "/" + document.title]);
_paq.push(["setDomains", ["*.preview.carpentries.org","*.datacarpentry.github.io","*.datacarpentry.org","*.librarycarpentry.github.io","*.librarycarpentry.org","*.swcarpentry.github.io", "*.carpentries.github.io"]]);
_paq.push(["setDoNotTrack", true]);
_paq.push(["disableCookies"]);
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u="https://carpentries.matomo.cloud/";
_paq.push(['setTrackerUrl', u+'matomo.php']);
_paq.push(['setSiteId', '1']);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.async=true; g.src='https://cdn.matomo.cloud/carpentries.matomo.cloud/matomo.js'; s.parentNode.insertBefore(g,s);
})();
</script>
End Matomo Code --></body></html><!-- END: inst/pkgdown/templates/layout.html-->