Skip to content

Commit d61ffbd

Browse files
committed
source commit: 5dda556
0 parents  commit d61ffbd

23 files changed

+2588
-0
lines changed

00-sql-introduction.md

Lines changed: 287 additions & 0 deletions
Large diffs are not rendered by default.

01-sql-basic-queries.md

Lines changed: 357 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,357 @@
1+
---
2+
title: Accessing Data With Queries
3+
teaching: 30
4+
exercises: 5
5+
---
6+
7+
::::::::::::::::::::::::::::::::::::::: objectives
8+
9+
- Write and build queries.
10+
- Filter data given various criteria.
11+
- Sort the results of a query.
12+
13+
::::::::::::::::::::::::::::::::::::::::::::::::::
14+
15+
:::::::::::::::::::::::::::::::::::::::: questions
16+
17+
- How do I write a basic query in SQL?
18+
19+
::::::::::::::::::::::::::::::::::::::::::::::::::
20+
21+
## Writing my first query
22+
23+
Let's start by using the **surveys** table. Here we have data on every
24+
individual that was captured at the site, including when they were captured,
25+
what plot they were captured on, their species ID, sex and weight in grams.
26+
27+
Let's write an SQL query that selects all of the columns in the surveys table. SQL queries can be written in the box located under the "Execute SQL" tab. Click on the right arrow above the query box to execute the query. (You can also use the keyboard shortcut "Cmd-Enter" on a Mac or "Ctrl-Enter" on a Windows machine to execute a query.) The results are displayed in the box below your query. If you want to display all of the columns in a table, use the wildcard \*.
28+
29+
```sql
30+
SELECT *
31+
FROM surveys;
32+
```
33+
34+
We have capitalized the words SELECT and FROM because they are SQL keywords.
35+
SQL is case insensitive, but it helps for readability, and is good style.
36+
37+
If we want to select a single column, we can type the column name instead of the wildcard \*.
38+
39+
```sql
40+
SELECT year
41+
FROM surveys;
42+
```
43+
44+
If we want more information, we can add more columns to the list of fields,
45+
right after SELECT:
46+
47+
```sql
48+
SELECT year, month, day
49+
FROM surveys;
50+
```
51+
52+
### Limiting results
53+
54+
Sometimes you don't want to see all the results, you just want to get a sense of what's being returned. In that case, you can use a `LIMIT` clause. In particular, you would want to do this if you were working with large databases.
55+
56+
```sql
57+
SELECT *
58+
FROM surveys
59+
LIMIT 10;
60+
```
61+
62+
### Unique values
63+
64+
If we want only the unique values so that we can quickly see what species have
65+
been sampled we use `DISTINCT`
66+
67+
```sql
68+
SELECT DISTINCT species_id
69+
FROM surveys;
70+
```
71+
72+
If we select more than one column, then the distinct pairs of values are
73+
returned
74+
75+
```sql
76+
SELECT DISTINCT year, species_id
77+
FROM surveys;
78+
```
79+
80+
### Calculated values
81+
82+
We can also do calculations with the values in a query.
83+
For example, if we wanted to look at the mass of each individual
84+
on different dates, but we needed it in kg instead of g we would use
85+
86+
```sql
87+
SELECT year, month, day, weight/1000
88+
FROM surveys;
89+
```
90+
91+
When we run the query, the expression `weight / 1000` is evaluated for each
92+
row and appended to that row, in a new column. If we used the `INTEGER` data type
93+
for the weight field then integer division would have been done, to obtain the
94+
correct results in that case divide by `1000.0`. Expressions can use any fields,
95+
any arithmetic operators (`+`, `-`, `*`, and `/`) and a variety of built-in
96+
functions. For example, we could round the values to make them easier to read.
97+
98+
```sql
99+
SELECT plot_id, species_id, sex, weight, ROUND(weight / 1000, 2)
100+
FROM surveys;
101+
```
102+
103+
::::::::::::::::::::::::::::::::::::::: challenge
104+
105+
## Challenge
106+
107+
- Write a query that returns the year, month, day, species\_id and weight in mg.
108+
109+
::::::::::::::: solution
110+
111+
## Solution
112+
113+
```sql
114+
SELECT day, month, year, species_id, weight * 1000
115+
FROM surveys;
116+
```
117+
118+
:::::::::::::::::::::::::
119+
120+
::::::::::::::::::::::::::::::::::::::::::::::::::
121+
122+
## Filtering
123+
124+
Databases can also filter data – selecting only the data meeting certain
125+
criteria. For example, let's say we only want data for the species
126+
*Dipodomys merriami*, which has a species code of DM. We need to add a
127+
`WHERE` clause to our query:
128+
129+
```sql
130+
SELECT *
131+
FROM surveys
132+
WHERE species_id='DM';
133+
```
134+
135+
We can do the same thing with numbers.
136+
Here, we only want the data since 2000:
137+
138+
```sql
139+
SELECT * FROM surveys
140+
WHERE year >= 2000;
141+
```
142+
143+
If we used the `TEXT` data type for the year, the `WHERE` clause should
144+
be `year >= '2000'`.
145+
146+
We can use more sophisticated conditions by combining tests
147+
with `AND` and `OR`. For example, suppose we want the data on *Dipodomys merriami*
148+
starting in the year 2000:
149+
150+
```sql
151+
SELECT *
152+
FROM surveys
153+
WHERE (year >= 2000) AND (species_id = 'DM');
154+
```
155+
156+
Note that the parentheses are not needed, but again, they help with
157+
readability. They also ensure that the computer combines `AND` and `OR`
158+
in the way that we intend.
159+
160+
If we wanted to get data for any of the *Dipodomys* species, which have
161+
species codes `DM`, `DO`, and `DS`, we could combine the tests using OR:
162+
163+
```sql
164+
SELECT *
165+
FROM surveys
166+
WHERE (species_id = 'DM') OR (species_id = 'DO') OR (species_id = 'DS');
167+
```
168+
169+
::::::::::::::::::::::::::::::::::::::: challenge
170+
171+
## Challenge
172+
173+
- Produce a table listing the data for all individuals in Plot 1
174+
that weighed more than 75 grams, telling us the date, species id code, and weight
175+
(in kg).
176+
177+
::::::::::::::: solution
178+
179+
## Solution
180+
181+
```sql
182+
SELECT day, month, year, species_id, weight / 1000
183+
FROM surveys
184+
WHERE (plot_id = 1) AND (weight > 75);
185+
```
186+
187+
:::::::::::::::::::::::::
188+
189+
::::::::::::::::::::::::::::::::::::::::::::::::::
190+
191+
## Building more complex queries
192+
193+
Now, let's combine the above queries to get data for the 3 *Dipodomys* species from
194+
the year 2000 on. This time, let's use IN as one way to make the query easier
195+
to understand. It is equivalent to saying `WHERE (species_id = 'DM') OR (species_id = 'DO') OR (species_id = 'DS')`, but reads more neatly:
196+
197+
```sql
198+
SELECT *
199+
FROM surveys
200+
WHERE (year >= 2000) AND (species_id IN ('DM', 'DO', 'DS'));
201+
```
202+
203+
We started with something simple, then added more clauses one by one, testing
204+
their effects as we went along. For complex queries, this is a good strategy,
205+
to make sure you are getting what you want. Sometimes it might help to take a
206+
subset of the data that you can easily see in a temporary database to practice
207+
your queries on before working on a larger or more complicated database.
208+
209+
When the queries become more complex, it can be useful to add comments. In SQL,
210+
comments are started by `--`, and end at the end of the line. For example, a
211+
commented version of the above query can be written as:
212+
213+
```sql
214+
-- Get post 2000 data on Dipodomys' species
215+
-- These are in the surveys table, and we are interested in all columns
216+
SELECT * FROM surveys
217+
-- Sampling year is in the column `year`, and we want to include 2000
218+
WHERE (year >= 2000)
219+
-- Dipodomys' species have the `species_id` DM, DO, and DS
220+
AND (species_id IN ('DM', 'DO', 'DS'));
221+
```
222+
223+
Although SQL queries often read like plain English, it is *always* useful to add
224+
comments; this is especially true of more complex queries.
225+
226+
## Sorting
227+
228+
We can also sort the results of our queries by using `ORDER BY`.
229+
For simplicity, let's go back to the **species** table and alphabetize it by taxa.
230+
231+
First, let's look at what's in the **species** table. It's a table of the species\_id and the full genus, species and taxa information for each species\_id. Having this in a separate table is nice, because we didn't need to include all
232+
this information in our main **surveys** table.
233+
234+
```sql
235+
SELECT *
236+
FROM species;
237+
```
238+
239+
Now let's order it by taxa.
240+
241+
```sql
242+
SELECT *
243+
FROM species
244+
ORDER BY taxa ASC;
245+
```
246+
247+
The keyword `ASC` tells us to order it in ascending order.
248+
We could alternately use `DESC` to get descending order.
249+
250+
```sql
251+
SELECT *
252+
FROM species
253+
ORDER BY taxa DESC;
254+
```
255+
256+
`ASC` is the default.
257+
258+
We can also sort on several fields at once.
259+
To truly be alphabetical, we might want to order by genus then species.
260+
261+
```sql
262+
SELECT *
263+
FROM species
264+
ORDER BY genus ASC, species ASC;
265+
```
266+
267+
::::::::::::::::::::::::::::::::::::::: challenge
268+
269+
## Challenge
270+
271+
- Write a query that returns year, species\_id, and weight in kg from
272+
the surveys table, sorted with the largest weights at the top.
273+
274+
::::::::::::::: solution
275+
276+
## Solution
277+
278+
```sql
279+
SELECT year, species_id, weight / 1000
280+
FROM surveys
281+
ORDER BY weight DESC;
282+
```
283+
284+
:::::::::::::::::::::::::
285+
286+
::::::::::::::::::::::::::::::::::::::::::::::::::
287+
288+
## Order of execution
289+
290+
Another note for ordering. We don't actually have to display a column to sort by
291+
it. For example, let's say we want to order the birds by their species ID, but
292+
we only want to see genus and species.
293+
294+
```sql
295+
SELECT genus, species
296+
FROM species
297+
WHERE taxa = 'Bird'
298+
ORDER BY species_id ASC;
299+
```
300+
301+
We can do this because sorting occurs earlier in the computational pipeline than
302+
field selection.
303+
304+
The computer is basically doing this:
305+
306+
1. Filtering rows according to WHERE
307+
2. Sorting results according to ORDER BY
308+
3. Displaying requested columns or expressions.
309+
310+
Clauses are written in a fixed order: `SELECT`, `FROM`, `WHERE`, then `ORDER BY`.
311+
312+
:::::::::::::::::::::::::::::::::::::: discussion
313+
314+
## Multiple statements
315+
316+
It is possible to write a query as a single line, but for readability, we recommend to put each clause on its own line.
317+
The standard way to separate a whole SQL statement is with a semicolon. This allows more than one SQL statement to be executed together.
318+
319+
320+
::::::::::::::::::::::::::::::::::::::::::::::::::
321+
322+
::::::::::::::::::::::::::::::::::::::: challenge
323+
324+
## Challenge
325+
326+
- Let's try to combine what we've learned so far in a single
327+
query. Using the surveys table, write a query to display the three date fields,
328+
`species_id`, and weight in kilograms (rounded to two decimal places), for
329+
individuals captured in 1999, ordered alphabetically by the `species_id`.
330+
- Write the query as a single line, then put each clause on its own line, and
331+
see how more legible the query becomes!
332+
333+
::::::::::::::: solution
334+
335+
## Solution
336+
337+
```sql
338+
SELECT year, month, day, species_id, ROUND(weight / 1000, 2)
339+
FROM surveys
340+
WHERE year = 1999
341+
ORDER BY species_id;
342+
```
343+
344+
:::::::::::::::::::::::::
345+
346+
::::::::::::::::::::::::::::::::::::::::::::::::::
347+
348+
:::::::::::::::::::::::::::::::::::::::: keypoints
349+
350+
- It is useful to apply conventions when writing SQL queries to aid readability.
351+
- Use logical connectors such as AND or OR to create more complex queries.
352+
- Calculations using mathematical symbols can also be performed on SQL queries.
353+
- Adding comments in SQL helps keep complex queries understandable.
354+
355+
::::::::::::::::::::::::::::::::::::::::::::::::::
356+
357+

0 commit comments

Comments
 (0)