Remember to

  • Install DB Browser
  • Set font sizes to larger values under:
  • Preferences -> Data Browers -> Font size
  • Preferences -> SQL -> SQL editor font size & SQL log font size
  • Download portal_mammals.sqlite.
  • Open portal_mammals.sqlite in DB Browser.

Why Databases

Database Queries

Using DB Browser

Selecting columns

SELECT *
FROM surveys;
SELECT year, month, day
FROM surveys;
SELECT DISTINCT year, month, day
FROM surveys;
SELECT year, month, day, species_id, hindfoot_length/10
FROM surveys;
SELECT year, month, day, species_id, ROUND(hindfoot_length/10)
FROM surveys;

Filtering

SELECT year, month, day, species_id, ROUND(hindfoot_length/10)
FROM surveys
WHERE species_id = 'DS';
SELECT year, month, day, species_id, ROUND(hindfoot_length/10)
FROM surveys
WHERE species_id = 'DS' AND year > 1990;
SELECT year, month, day, species_id, ROUND(hindfoot_length/10)
FROM surveys
WHERE species_id = 'DS' AND year > 1990 AND hindfoot_length IS NOT NULL;

Style

Saving queries for future use

Do the Simple WHERE exercise.

Sorting

SELECT genus, species
FROM species
ORDER BY genus;
SELECT genus, species
FROM species
ORDER BY genus DESC;
SELECT genus, species
FROM species
ORDER BY taxa, genus, species;

Aggregation

SELECT species_id, AVG(weight), COUNT(species_id)
FROM surveys
GROUP BY species_id;
SELECT species_id, plot_id, AVG(weight), COUNT(species_id)
FROM surveys
GROUP BY species_id, plot_id;
SELECT species_id, plot_id, AVG(weight), COUNT(weight)
FROM surveys
GROUP BY species_id, plot_id;
SELECT species_id, plot_id, AVG(weight) as avg_weight, COUNT(weight) as num_indiv
FROM surveys
GROUP BY species_id, plot_id;

Do the COUNT exercise.

Order matters

Nemonic from: https://twitter.com/statsnam/status/1149431249511075840

Select - So
From - Few
Where - Workers
Group by - Go
Having - Home
Order by - On time

Basic join

SELECT DISTINCT year, month, day, plot_type 
FROM surveys
JOIN plots USING (plot_id);
SELECT year, month, day, plot_type
FROM surveys
JOIN plots
SELECT DISTINCT year, month, day, plot_type
FROM surveys
JOIN species on surveys.species_id = species.species_id;

Multi-table join

SELECT year, month, day, taxa, plot_type
FROM surveys
JOIN species USING (species_id)
JOIN plots USING (plot_id)

Do Basic Join.

Do Multi-table Join.