forked from datacarpentry/sql-ecology-lesson
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02-sql-aggregation.html
779 lines (741 loc) · 50.9 KB
/
02-sql-aggregation.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
<!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: Aggregating and Grouping Data</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/02-sql-aggregation.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: 54%" class="percentage">
54%
</div>
<div class="progress data">
<div class="progress-bar data" role="progressbar" style="width: 54%" aria-valuenow="54" 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/02-sql-aggregation.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="accordionFlush2">
<div class="accordion-item">
<div class="accordion-header" id="flush-heading2">
<a href="00-sql-introduction.html">1. Introducing Databases and SQL</a>
</div><!--/div.accordion-header-->
</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="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">
3. Aggregating and Grouping Data
</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="#count-and-group-by">COUNT and GROUP BY</a></li>
<li><a href="#ordering-aggregated-results">Ordering Aggregated Results</a></li>
<li><a href="#aliases">Aliases</a></li>
<li><a href="#the-having-keyword">The <code>HAVING</code> keyword</a></li>
<li><a href="#saving-queries-for-future-use">Saving Queries for Future Use</a></li>
<li><a href="#what-about-null">What About NULL?</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="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="01-sql-basic-queries.html"><i aria-hidden="true" class="small-arrow" data-feather="arrow-left"></i>Previous</a>
<a class="chapter-link float-end" href="03-sql-joins.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="01-sql-basic-queries.html" rel="prev">
<i aria-hidden="true" class="small-arrow" data-feather="arrow-left"></i>
Previous: Accessing Data With
</a>
<a class="chapter-link float-end" href="03-sql-joins.html" rel="next">
Next: Combining 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>Aggregating and Grouping Data</h1>
<p> Last updated on 2023-04-21 |
<a href="https://github.com/datacarpentry/sql-ecology-lesson/edit/main/episodes/02-sql-aggregation.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>How can I summarize my data by aggregating, filtering, or ordering
query results?</li>
<li>How can I make sure column names from my queries make sense and
aren’t too long?</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>Apply aggregation functions to group records together.</li>
<li>Filter and order results of a query based on aggregate
functions.</li>
<li>Employ aliases to assign new names to items in a query.</li>
<li>Save a query to make a new table.</li>
<li>Apply filters to find missing values in SQL.</li>
</ul></div>
</div>
</div>
</div>
</div>
<section id="count-and-group-by"><h2 class="section-heading">COUNT and GROUP BY<a class="anchor" aria-label="anchor" href="#count-and-group-by"></a>
</h2>
<hr class="half-width"><p>Aggregation allows us to combine results by grouping records based on
value. It is also useful for calculating combined values in groups.</p>
<p>Let’s go to the surveys table and find out how many individuals there
are. Using the wildcard * counts the number of records (rows):</p>
<div class="codewrapper sourceCode" id="cb1">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> <span class="fu">COUNT</span>(<span class="op">*</span>)</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> surveys;</span></code></pre>
</div>
<p>We can also find out how much all of those individuals weigh:</p>
<div class="codewrapper sourceCode" id="cb2">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> <span class="fu">COUNT</span>(<span class="op">*</span>), <span class="fu">SUM</span>(weight)</span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> surveys;</span></code></pre>
</div>
<p>We can output this value in kilograms (dividing the value by
1000.00), then rounding to 3 decimal places: (Notice the divisor has
numbers after the decimal point, which forces the answer to have a
decimal fraction)</p>
<div class="codewrapper sourceCode" id="cb3">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> <span class="fu">ROUND</span>(<span class="fu">SUM</span>(weight)<span class="op">/</span><span class="fl">1000.00</span>, <span class="dv">3</span>)</span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> surveys;</span></code></pre>
</div>
<p>There are many other aggregate functions included in SQL, for
example: <code>MAX</code>, <code>MIN</code>, and <code>AVG</code>.</p>
<div id="challenge" class="callout challenge">
<div class="callout-square">
<i class="callout-icon" data-feather="zap"></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>Write a query that returns: the total weight, average weight, minimum
and maximum weights for all animals caught over the duration of the
survey. Can you modify it so that it outputs these values only for
weights between 5 and 10?</p>
</div>
</div>
</div>
<div id="accordionSolution1" class="accordion challenge-accordion accordion-flush">
<div class="accordion-item">
<button class="accordion-button solution-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseSolution1" aria-expanded="false" aria-controls="collapseSolution1">
<h4 class="accordion-header" id="headingSolution1">
Show me the solution
</h4>
</button>
<div id="collapseSolution1" class="accordion-collapse collapse" aria-labelledby="headingSolution1" data-bs-parent="#accordionSolution1">
<div class="accordion-body">
<div class="codewrapper sourceCode" id="cb4">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- All animals</span></span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> <span class="fu">SUM</span>(weight), <span class="fu">AVG</span>(weight), <span class="fu">MIN</span>(weight), <span class="fu">MAX</span>(weight)</span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> surveys;</span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-5"><a href="#cb4-5" aria-hidden="true" tabindex="-1"></a><span class="co">-- Only weights between 5 and 10</span></span>
<span id="cb4-6"><a href="#cb4-6" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> <span class="fu">SUM</span>(weight), <span class="fu">AVG</span>(weight), <span class="fu">MIN</span>(weight), <span class="fu">MAX</span>(weight)</span>
<span id="cb4-7"><a href="#cb4-7" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> surveys</span>
<span id="cb4-8"><a href="#cb4-8" aria-hidden="true" tabindex="-1"></a><span class="kw">WHERE</span> (weight <span class="op">></span> <span class="dv">5</span>) <span class="kw">AND</span> (weight <span class="op"><</span> <span class="dv">10</span>);</span></code></pre>
</div>
</div>
</div>
</div>
</div>
<p>Now, let’s see how many individuals were counted in each species. We
do this using a <code>GROUP BY</code> clause</p>
<div class="codewrapper sourceCode" id="cb5">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> species_id, <span class="fu">COUNT</span>(<span class="op">*</span>)</span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> surveys</span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a><span class="kw">GROUP</span> <span class="kw">BY</span> species_id;</span></code></pre>
</div>
<p><code>GROUP BY</code> tells SQL what field or fields we want to use
to aggregate the data. If we want to group by multiple fields, we give
<code>GROUP BY</code> a comma separated list.</p>
<div id="challenge-1" class="callout challenge">
<div class="callout-square">
<i class="callout-icon" data-feather="zap"></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">
<p>Write queries that return:</p>
<ol style="list-style-type: decimal"><li>How many individuals were counted in each year in total</li>
<li>How many were counted each year, for each different species</li>
<li>The average weights of each species in each year</li>
</ol><p>Can you get the answer to both 2 and 3 in a single query?</p>
</div>
</div>
</div>
<div id="accordionSolution2" class="accordion challenge-accordion accordion-flush">
<div class="accordion-item">
<button class="accordion-button solution-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseSolution2" aria-expanded="false" aria-controls="collapseSolution2">
<h4 class="accordion-header" id="headingSolution2">
Solution of 1
</h4>
</button>
<div id="collapseSolution2" class="accordion-collapse collapse" aria-labelledby="headingSolution2" data-bs-parent="#accordionSolution2">
<div class="accordion-body">
<div class="codewrapper sourceCode" id="cb6">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> <span class="dt">year</span>, <span class="fu">COUNT</span>(<span class="op">*</span>)</span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> surveys</span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a><span class="kw">GROUP</span> <span class="kw">BY</span> <span class="dt">year</span>;</span></code></pre>
</div>
</div>
</div>
</div>
</div>
<div id="accordionSolution3" class="accordion challenge-accordion accordion-flush">
<div class="accordion-item">
<button class="accordion-button solution-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseSolution3" aria-expanded="false" aria-controls="collapseSolution3">
<h4 class="accordion-header" id="headingSolution3">
Solution of 2 and 3
</h4>
</button>
<div id="collapseSolution3" class="accordion-collapse collapse" aria-labelledby="headingSolution3" data-bs-parent="#accordionSolution3">
<div class="accordion-body">
<div class="codewrapper sourceCode" id="cb7">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> <span class="dt">year</span>, species_id, <span class="fu">COUNT</span>(<span class="op">*</span>), <span class="fu">AVG</span>(weight)</span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> surveys</span>
<span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a><span class="kw">GROUP</span> <span class="kw">BY</span> <span class="dt">year</span>, species_id;</span></code></pre>
</div>
</div>
</div>
</div>
</div>
</section><section id="ordering-aggregated-results"><h2 class="section-heading">Ordering Aggregated Results<a class="anchor" aria-label="anchor" href="#ordering-aggregated-results"></a>
</h2>
<hr class="half-width"><p>We can order the results of our aggregation by a specific column,
including the aggregated column. Let’s count the number of individuals
of each species captured, ordered by the count:</p>
<div class="codewrapper sourceCode" id="cb8">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> species_id, <span class="fu">COUNT</span>(<span class="op">*</span>)</span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> surveys</span>
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a><span class="kw">GROUP</span> <span class="kw">BY</span> species_id</span>
<span id="cb8-4"><a href="#cb8-4" aria-hidden="true" tabindex="-1"></a><span class="kw">ORDER</span> <span class="kw">BY</span> <span class="fu">COUNT</span>(species_id);</span></code></pre>
</div>
</section><section id="aliases"><h2 class="section-heading">Aliases<a class="anchor" aria-label="anchor" href="#aliases"></a>
</h2>
<hr class="half-width"><p>As queries get more complex, the expressions we use can get long and
unwieldy. To help make things clearer in the query and in its output, we
can use aliases to assign new names to things in the query.</p>
<p>We can use aliases in column names using <code>AS</code>:</p>
<div class="codewrapper sourceCode" id="cb9">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> <span class="fu">MAX</span>(<span class="dt">year</span>) <span class="kw">AS</span> last_surveyed_year</span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> surveys;</span></code></pre>
</div>
<p>The <code>AS</code> isn’t technically required, so you could do</p>
<div class="codewrapper sourceCode" id="cb10">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> <span class="fu">MAX</span>(<span class="dt">year</span>) last_surveyed_year</span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> surveys;</span></code></pre>
</div>
<p>but using <code>AS</code> is much clearer so it is good style to
include it.</p>
<p>We can not only alias column names, but also table names in the same
way:</p>
<div class="codewrapper sourceCode" id="cb11">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> <span class="op">*</span></span>
<span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> surveys <span class="kw">AS</span> surv;</span></code></pre>
</div>
<p>And again, the <code>AS</code> keyword is not required, so this
works, too:</p>
<div class="codewrapper sourceCode" id="cb12">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> <span class="op">*</span></span>
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> surveys surv;</span></code></pre>
</div>
<p>Aliasing table names can be helpful when working with queries that
involve multiple tables; you will learn more about this later.</p>
</section><section id="the-having-keyword"><h2 class="section-heading">The <code>HAVING</code> keyword<a class="anchor" aria-label="anchor" href="#the-having-keyword"></a>
</h2>
<hr class="half-width"><p>In the previous episode, we have seen the keyword <code>WHERE</code>,
allowing to filter the results according to some criteria. SQL offers a
mechanism to filter the results based on <strong>aggregate
functions</strong>, through the <code>HAVING</code> keyword.</p>
<p>For example, we can request to only return information about species
with a count higher than 10:</p>
<div class="codewrapper sourceCode" id="cb13">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> species_id, <span class="fu">COUNT</span>(species_id)</span>
<span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> surveys</span>
<span id="cb13-3"><a href="#cb13-3" aria-hidden="true" tabindex="-1"></a><span class="kw">GROUP</span> <span class="kw">BY</span> species_id</span>
<span id="cb13-4"><a href="#cb13-4" aria-hidden="true" tabindex="-1"></a><span class="kw">HAVING</span> <span class="fu">COUNT</span>(species_id) <span class="op">></span> <span class="dv">10</span>;</span></code></pre>
</div>
<p>The <code>HAVING</code> keyword works exactly like the
<code>WHERE</code> keyword, but uses aggregate functions instead of
database fields to filter.</p>
<p>You can use the <code>AS</code> keyword to assign an alias to a
column or table, and refer to that alias in the <code>HAVING</code>
clause. For example, in the above query, we can call the
<code>COUNT(species_id)</code> by another name, like
<code>occurrences</code>. This can be written this way:</p>
<div class="codewrapper sourceCode" id="cb14">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> species_id, <span class="fu">COUNT</span>(species_id) <span class="kw">AS</span> occurrences</span>
<span id="cb14-2"><a href="#cb14-2" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> surveys</span>
<span id="cb14-3"><a href="#cb14-3" aria-hidden="true" tabindex="-1"></a><span class="kw">GROUP</span> <span class="kw">BY</span> species_id</span>
<span id="cb14-4"><a href="#cb14-4" aria-hidden="true" tabindex="-1"></a><span class="kw">HAVING</span> occurrences <span class="op">></span> <span class="dv">10</span>;</span></code></pre>
</div>
<p>Note that in both queries, <code>HAVING</code> comes <em>after</em>
<code>GROUP BY</code>. One way to think about this is: the data are
retrieved (<code>SELECT</code>), which can be filtered
(<code>WHERE</code>), then joined in groups (<code>GROUP BY</code>);
finally, we can filter again based on some of these groups
(<code>HAVING</code>).</p>
<div id="challenge-2" class="callout challenge">
<div class="callout-square">
<i class="callout-icon" data-feather="zap"></i>
</div>
<div id="challenge-2" class="callout-inner">
<h3 class="callout-title">Challenge<a class="anchor" aria-label="anchor" href="#challenge-2"></a>
</h3>
<div class="callout-content">
<p>Write a query that returns, from the <code>species</code> table, the
number of <code>species</code> in each <code>taxa</code>, only for the
<code>taxa</code> with more than 10 <code>species</code>.</p>
</div>
</div>
</div>
<div id="accordionSolution4" class="accordion challenge-accordion accordion-flush">
<div class="accordion-item">
<button class="accordion-button solution-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseSolution4" aria-expanded="false" aria-controls="collapseSolution4">
<h4 class="accordion-header" id="headingSolution4">
Show me the solution
</h4>
</button>
<div id="collapseSolution4" class="accordion-collapse collapse" aria-labelledby="headingSolution4" data-bs-parent="#accordionSolution4">
<div class="accordion-body">
<div class="codewrapper sourceCode" id="cb15">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> taxa, <span class="fu">COUNT</span>(<span class="op">*</span>) <span class="kw">AS</span> n</span>
<span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> species</span>
<span id="cb15-3"><a href="#cb15-3" aria-hidden="true" tabindex="-1"></a><span class="kw">GROUP</span> <span class="kw">BY</span> taxa</span>
<span id="cb15-4"><a href="#cb15-4" aria-hidden="true" tabindex="-1"></a><span class="kw">HAVING</span> n <span class="op">></span> <span class="dv">10</span>;</span></code></pre>
</div>
</div>
</div>
</div>
</div>
</section><section id="saving-queries-for-future-use"><h2 class="section-heading">Saving Queries for Future Use<a class="anchor" aria-label="anchor" href="#saving-queries-for-future-use"></a>
</h2>
<hr class="half-width"><p>It is not uncommon to repeat the same operation more than once, for
example for monitoring or reporting purposes. SQL comes with a very
powerful mechanism to do this by creating views. Views are a form of
query that is saved in the database, and can be used to look at, filter,
and even update information. One way to think of views is as a table,
that can read, aggregate, and filter information from several places
before showing it to you.</p>
<p>Creating a view from a query requires us to add
<code>CREATE VIEW viewname AS</code> before the query itself. For
example, imagine that our project only covers the data gathered during
the summer (May - September) of 2000. That query would look like:</p>
<div class="codewrapper sourceCode" id="cb16">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> <span class="op">*</span></span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> surveys</span>
<span id="cb16-3"><a href="#cb16-3" aria-hidden="true" tabindex="-1"></a><span class="kw">WHERE</span> <span class="dt">year</span> <span class="op">=</span> <span class="dv">2000</span> <span class="kw">AND</span> (<span class="dt">month</span> <span class="op">></span> <span class="dv">4</span> <span class="kw">AND</span> <span class="dt">month</span> <span class="op"><</span> <span class="dv">10</span>);</span></code></pre>
</div>
<p>But we don’t want to have to type that every time we want to ask a
question about that particular subset of data. Hence, we can benefit
from a view:</p>
<div class="codewrapper sourceCode" id="cb17">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a><span class="kw">CREATE</span> <span class="kw">VIEW</span> summer_2000 <span class="kw">AS</span></span>
<span id="cb17-2"><a href="#cb17-2" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> <span class="op">*</span></span>
<span id="cb17-3"><a href="#cb17-3" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> surveys</span>
<span id="cb17-4"><a href="#cb17-4" aria-hidden="true" tabindex="-1"></a><span class="kw">WHERE</span> <span class="dt">year</span> <span class="op">=</span> <span class="dv">2000</span> <span class="kw">AND</span> (<span class="dt">month</span> <span class="op">></span> <span class="dv">4</span> <span class="kw">AND</span> <span class="dt">month</span> <span class="op"><</span> <span class="dv">10</span>);</span></code></pre>
</div>
<p>Using a view we will be able to access these results with a much
shorter notation:</p>
<div class="codewrapper sourceCode" id="cb18">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> <span class="op">*</span></span>
<span id="cb18-2"><a href="#cb18-2" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> summer_2000</span>
<span id="cb18-3"><a href="#cb18-3" aria-hidden="true" tabindex="-1"></a><span class="kw">WHERE</span> species_id <span class="op">=</span> <span class="st">'PE'</span>;</span></code></pre>
</div>
</section><section id="what-about-null"><h2 class="section-heading">What About NULL?<a class="anchor" aria-label="anchor" href="#what-about-null"></a>
</h2>
<hr class="half-width"><p>From the last example, there should only be five records. If you look
at the <code>weight</code> column, it’s easy to see what the average
weight would be. If we use SQL to find the average weight, SQL behaves
like we would hope, ignoring the NULL values:</p>
<div class="codewrapper sourceCode" id="cb19">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> <span class="fu">AVG</span>(weight)</span>
<span id="cb19-2"><a href="#cb19-2" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> summer_2000</span>
<span id="cb19-3"><a href="#cb19-3" aria-hidden="true" tabindex="-1"></a><span class="kw">WHERE</span> species_id <span class="op">=</span> <span class="st">'PE'</span>;</span></code></pre>
</div>
<p>But if we try to be extra clever, and find the average ourselves, we
might get tripped up:</p>
<div class="codewrapper sourceCode" id="cb20">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> <span class="fu">SUM</span>(weight), <span class="fu">COUNT</span>(<span class="op">*</span>), <span class="fu">SUM</span>(weight)<span class="op">/</span><span class="fu">COUNT</span>(<span class="op">*</span>)</span>
<span id="cb20-2"><a href="#cb20-2" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> summer_2000</span>
<span id="cb20-3"><a href="#cb20-3" aria-hidden="true" tabindex="-1"></a><span class="kw">WHERE</span> species_id <span class="op">=</span> <span class="st">'PE'</span>;</span></code></pre>
</div>
<p>Here the <code>COUNT</code> function includes all five records (even
those with NULL values), but the <code>SUM</code> only includes the
three records with data in the <code>weight</code> field, giving us an
incorrect average. However, our strategy <em>will</em> work if we modify
the <code>COUNT</code> function slightly:</p>
<div class="codewrapper sourceCode" id="cb21">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb21-1"><a href="#cb21-1" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> <span class="fu">SUM</span>(weight), <span class="fu">COUNT</span>(weight), <span class="fu">SUM</span>(weight)<span class="op">/</span><span class="fu">COUNT</span>(weight)</span>
<span id="cb21-2"><a href="#cb21-2" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> summer_2000</span>
<span id="cb21-3"><a href="#cb21-3" aria-hidden="true" tabindex="-1"></a><span class="kw">WHERE</span> species_id <span class="op">=</span> <span class="st">'PE'</span>;</span></code></pre>
</div>
<p>When we count the weight field specifically, SQL ignores the records
with data missing in that field. So here is one example where NULLs can
be tricky: <code>COUNT(*)</code> and <code>COUNT(field)</code> can
return different values.</p>
<p>Another case is when we use a “negative” query. Let’s count all the
non-female animals:</p>
<div class="codewrapper sourceCode" id="cb22">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb22-1"><a href="#cb22-1" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> <span class="fu">COUNT</span>(<span class="op">*</span>)</span>
<span id="cb22-2"><a href="#cb22-2" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> summer_2000</span>
<span id="cb22-3"><a href="#cb22-3" aria-hidden="true" tabindex="-1"></a><span class="kw">WHERE</span> sex <span class="op">!=</span> <span class="st">'F'</span>;</span></code></pre>
</div>
<p>Now let’s count all the non-male animals:</p>
<div class="codewrapper sourceCode" id="cb23">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb23-1"><a href="#cb23-1" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> <span class="fu">COUNT</span>(<span class="op">*</span>)</span>
<span id="cb23-2"><a href="#cb23-2" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> summer_2000</span>
<span id="cb23-3"><a href="#cb23-3" aria-hidden="true" tabindex="-1"></a><span class="kw">WHERE</span> sex <span class="op">!=</span> <span class="st">'M'</span>;</span></code></pre>
</div>
<p>But if we compare those two numbers with the total:</p>
<div class="codewrapper sourceCode" id="cb24">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb24-1"><a href="#cb24-1" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> <span class="fu">COUNT</span>(<span class="op">*</span>)</span>
<span id="cb24-2"><a href="#cb24-2" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> summer_2000;</span></code></pre>
</div>
<p>We’ll see that they don’t add up to the total! That’s because SQL
doesn’t automatically include NULL values in a negative conditional
statement. So if we are querying “not x”, then SQL divides our data into
three categories: ‘x’, ‘not NULL, not x’ and NULL; then, returns the
‘not NULL, not x’ group. Sometimes this may be what we want - but
sometimes we may want the missing values included as well! In that case,
we’d need to change our query to:</p>
<div class="codewrapper sourceCode" id="cb25">
<h3 class="code-label">SQL<i aria-hidden="true" data-feather="chevron-left"></i><i aria-hidden="true" data-feather="chevron-right"></i>
</h3>
<pre class="sourceCode sql" tabindex="0"><code class="sourceCode sql"><span id="cb25-1"><a href="#cb25-1" aria-hidden="true" tabindex="-1"></a><span class="kw">SELECT</span> <span class="fu">COUNT</span>(<span class="op">*</span>)</span>
<span id="cb25-2"><a href="#cb25-2" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> summer_2000</span>
<span id="cb25-3"><a href="#cb25-3" aria-hidden="true" tabindex="-1"></a><span class="kw">WHERE</span> sex <span class="op">!=</span> <span class="st">'M'</span> <span class="kw">OR</span> sex <span class="kw">IS</span> <span class="kw">NULL</span>;</span></code></pre>
</div>
<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>Use the <code>GROUP BY</code> keyword to aggregate data.</li>
<li>Functions like <code>MIN</code>, <code>MAX</code>, <code>AVG</code>,
<code>SUM</code>, <code>COUNT</code>, etc. operate on aggregated
data.</li>
<li>Aliases can help shorten long queries. To write clear and readable
queries, use the <code>AS</code> keyword when creating aliases.</li>
<li>Use the <code>HAVING</code> keyword to filter on aggregate
properties.</li>
<li>Use a <code>VIEW</code> to access the result of a query as though it
was a new table.</li>
</ul></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="01-sql-basic-queries.html"><i aria-hidden="true" class="small-arrow" data-feather="arrow-left"></i>Previous</a>
<a class="chapter-link float-end" href="03-sql-joins.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="01-sql-basic-queries.html" rel="prev">
<i aria-hidden="true" class="small-arrow" data-feather="arrow-left"></i>
Previous: Accessing Data With
</a>
<a class="chapter-link float-end" href="03-sql-joins.html" rel="next">
Next: Combining 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/02-sql-aggregation.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/02-sql-aggregation.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": "Aggregating and Grouping Data",
"creativeWorkStatus": "active",
"url": "https://datacarpentry.github.io/sql-ecology-lesson/02-sql-aggregation.html",
"identifier": "https://datacarpentry.github.io/sql-ecology-lesson/02-sql-aggregation.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-->