Lesson

A Practical SQL Guide with DB Browser, Part 1: Retrieve and Analyze

Open a real bike-share database in DB Browser, then retrieve, filter, sort, summarize and group rows to see when demand is highest.

Last updated:


What you will learn

SQL (Structured Query Language) lets us ask a database for information and make controlled changes to it.
A query is a set of instructions written in SQL.

By the end of this part, you should be able to open a SQLite database in DB Browser, inspect a table, retrieve and filter rows, sort and limit results, and summarize and group data.
Part 2 adds changing data, combining tables and exporting results.
We use the graphical DB Browser application, not Python.

In this guide

ContentsThe question behind the exercise

A practical question: when does a bike-share system need capacity?

The practice database contains real daily rental counts from Capital Bikeshare in Washington, D.C., from 2011 to 2012.
The data were published in the UCI Machine Learning Repository.
Each row summarizes one day, including total rentals, registered and casual riders, season, weather, and working-day status.
The data are observed, not simulated, but they are historical and aggregated.

Imagine the team that runs the system. On a busy day some stations run out of bikes and staff are missing; on a quiet day bikes stand idle and staff are wasted.
Nobody can see which days are which by reading 731 rows by hand, so the team asks the data questions, and this guide teaches how.
An operator could use comparisons across weekdays, seasons, and weather to plan staffing or service capacity.
The table has no station locations or individual trips, so it cannot tell us where bikes need to be moved.
These descriptive comparisons also do not prove why demand differs or predict today’s demand.

The dataset contains 731 daily records. Its source is Hadi Fanaee-T, 2013, Bike Sharing, UCI Machine Learning Repository.
It is licensed under CC BY 4.0. The practice file keeps the original observations and makes category codes easier to read.

Open the database in DB Browser

  1. Install DB Browser for SQLite from its official download page. Windows installation details follow this list.
  2. Download the SQL practice database.
  3. Open DB Browser and choose Open Database. Select sql-practice.sqlite.
  4. In Browse Data, choose the daily_ridership table. It contains the 731 observed daily records. The review_queue table is an empty workspace for practicing data changes. It has the same columns needed for the review, plus a review_note text column.
  5. Open Execute SQL. Enter a query and select the run button. Results appear beneath the editor.
Installation details

Windows

  1. On the download page, under Windows, choose the standard installer for your computer. Most computers use the 64-bit version. The page also offers a 32-bit version and an ARM64 version for computers with an ARM processor.
  2. Save the file somewhere familiar, such as the Downloads folder, and double-click it.
  3. In the setup screens, select Next, tick the box that accepts the license terms, and select Next again.
  4. On the Shortcuts screen there are two columns: DB Browser (SQLite) and DB Browser (SQLCipher). Leave the options in the SQLite column ticked (desktop shortcut and Start menu) and select Next.
  5. Select Next on the following screen, then Install, and Finish at the end.
  6. Open the program from its shortcut or the Start menu, under the name DB Browser for SQLite. If an empty window with an Open Database button appears, the installation worked.

If the standard installer shows an error, the download page offers alternatives:
a portable version (PortableApp) that needs no installation (there is no portable version for ARM64), or a nightly build.
On macOS and Linux, choose the package for your system on the download page and follow the instructions there.

In Browse Data, select daily_ridership to inspect rows directly.
Use Execute SQL to ask a question about many rows at once.

Without installing anything: under every query in this guide there is a Try this query button.
It opens a box where the query runs in your browser on a copy of the same database, and you can edit it and run it again.
While you type, suggestions for keywords, table names, and column names appear (Tab or Enter accepts one).
Reset database restores the copy, and Download CSV saves a result to a file.
Wherever the guide asks you to try something, an empty query box follows it:
write your own query there and run it (Ctrl+Enter, or Cmd+Enter on a Mac), or do the same in DB Browser.
For questions to solve, open the SQL exercises, where a generator gives you a new question each time and checks your answer.

Understand the columns

ColumnSQLite typeMeaning
record_idINTEGERUnique observation identifier, not a measured feature
observation_dateTEXTDate of the observation
seasonTEXTWinter, Spring, Summer, or Fall
year, monthINTEGERCalendar year and month
holidayINTEGER1 for a holiday, 0 otherwise
weekdayINTEGERDay of week, where 0 is Sunday and 6 is Saturday
working_dayINTEGER1 for a working day; 0 on weekends and on holidays that fall on a weekday
weatherTEXTClear or partly cloudy, Mist or cloudy, or Light rain or snow
temperature_normalizedREALTemperature on a normalized 0 to 1 scale
apparent_temperature_normalizedREALApparent temperature on a normalized 0 to 1 scale
humidity_normalized, wind_speed_normalizedREALHumidity and wind speed on normalized scales
casual_rides, registered_ridesINTEGERDaily rentals by user type
total_ridesINTEGERTotal rentals for the day

The SQLite type describes how a value is stored. For example, observation_date is stored as text in a date format, while holiday and working_day are stored as integers but represent categories.
Temperature, humidity, and wind are normalized source values, not degrees or percentages.
The original numeric season and weather codes have been translated to readable labels.

The first three of 731 rows of the daily_ridership table. A row describes one day, a column describes one attribute, and the record_id column is the primary key.
Rows, columns, and the primary key in the daily_ridership table.

Basic query syntax

An SQL query can span several lines. Spaces and indentation make it easier to read but do not change its meaning.
A comma separates items in a list, such as column names. A semicolon ; marks the end of a query, which is especially useful when running several queries together.
Command words are not case-sensitive (select and SELECT are the same), but a text value must match exactly when compared with =:
season = 'summer' finds no row, while 'Summer' finds 188 days.
Put text values in single quotes, such as 'Summer', but write numbers without quotes.
Parentheses group part of a condition or calculation when needed.

Choose columns and a table

Goal: show only information that helps answer a question, rather than returning the whole table.

  • SELECT chooses which columns to display. Separate columns with commas. Use * to return every column.
  • FROM names the table to read.
  • DISTINCT keeps only unique values in the selected column or combination of columns.

Example: show the observation date and rental count for each day:

SELECT observation_date, total_rides
FROM daily_ridership;

To inspect every column, run this query:

SELECT *
FROM daily_ridership;

Once you know the table, selecting only relevant columns usually makes results easier to read.

Practice

Try it: Which weather labels appear in the dataset?

Show one possible answer
SELECT DISTINCT weather
FROM daily_ridership;
Show a common mistake and why it happens

This query is valid, but returns one weather label per day, including repeats:

SELECT weather FROM daily_ridership;

Add DISTINCT to get a list without duplicates.

Filter rows with WHERE

Goal: focus on days that meet a condition, such as working days with at least 6,000 rentals.

  • WHERE checks each row and keeps only rows that satisfy a condition.

  • Use =, <> (not equal to), >, >=, <, and <= for comparisons. Put text in single quotes and write numbers without quotes.

  • AND joins conditions that must all be true. OR joins conditions where either may be true.
    When both appear, AND is evaluated before OR, so a AND b OR c means (a AND b) OR c.
    Use parentheses to show which conditions belong together.

  • IN checks whether a value is one of a list. This condition keeps the rows whose season is either of the two:

    season IN ('Winter', 'Spring')

    It is a shorter way to write:

    season = 'Winter'
    OR season = 'Spring'
  • LIKE matches text against a pattern. % stands for any sequence of zero or more characters.
    For example, %rain% matches a text value containing the character sequence rain, with zero or more characters before and after it.
    rain% matches a value that starts with that sequence, and %rain matches a value that ends with it.

  • substr cuts a piece out of a text, in this form:

    substr(text, start, length)

    Positions count from 1, so this call returns the first four characters of the date, its year:

    substr(observation_date, 1, 4)

    A date is stored as text such as 2012-02-29, so the text can be cut and compared like any other text.
    This table also has a year column; a table that keeps only the date text can be filtered by year in this way.

Example: select working days with at least 6,000 rentals:

SELECT observation_date, total_rides
FROM daily_ridership
WHERE working_day = 1
  AND total_rides >= 6000;

Example: show the days in 2012 whose weather text ends with cloudy, using the pieces of text from the list above:

SELECT observation_date, weather
FROM daily_ridership
WHERE weather LIKE '%cloudy'
  AND substr(observation_date, 1, 4) = '2012';

The result is 360 rows, one day in each row. The text '2012' is in quotes because substr returns text, not a number.

Note: single quotes for text, not double quotes. In standard SQL, single quotes mark text and double quotes mark the names of columns and tables.
SQLite is lenient: when a word in double quotes is not a column name, it treats it as text, so WHERE season = "Summer" also runs in DB Browser (it returns the same 188 days as 'Summer').
Do not rely on this. Most other databases report an error, and in SQLite a double-quoted word that matches a column name is read as that column.
For example, WHERE weather = "weather" compares the column with itself, returns all 731 rows, and shows no error message.
Use single quotes for text, so the query behaves the same in every database.

Show a plausible mistake and why it happens

The pattern rain% searches only descriptions that start with the sequence rain.
The query below returns no rows, because every label that mentions rain starts with Light.
To allow characters before it, put % at the beginning of the pattern.

SELECT observation_date, weather
FROM daily_ridership
WHERE weather LIKE 'rain%';

Practice

Try it: Which days have weather text containing rain, or are nonworking days?

Show one possible answer
SELECT observation_date, weather, total_rides
FROM daily_ridership
WHERE weather LIKE '%rain%'
   OR working_day = 0;
Show a common mistake and why it happens

Without parentheses, AND is evaluated before OR. This condition can include every nonworking day, including days outside summer:

SELECT observation_date, weather, total_rides
FROM daily_ridership
WHERE season = 'Summer'
  AND weather LIKE '%rain%'
   OR working_day = 0;

To restrict both options to summer days, group the rain and nonworking-day conditions in parentheses:

SELECT observation_date, weather, total_rides
FROM daily_ridership
WHERE season = 'Summer'
  AND (weather LIKE '%rain%'
       OR working_day = 0);

The first version returns 234 rows, the corrected version 60.

Sort and limit results

Goal: quickly find the busiest days or show a short list in an order that helps answer the question.

  • ORDER BY sorts by a column.

  • ASC means ascending and DESC means descending. Ascending is the default.

  • ORDER BY can sort by several columns, separated by commas, as in:

    ORDER BY total_rides DESC,
             observation_date

    This sorts by total_rides and, among rows with the same total_rides, by observation_date.
    Each column has its own ASC or DESC. A second sort key fixes the order of tied rows.

  • LIMIT caps the number of rows shown. When asking for the first or last values, sort before limiting.

Example: the five busiest days:

SELECT observation_date, total_rides
FROM daily_ridership
ORDER BY total_rides DESC
LIMIT 5;
Show a plausible mistake and why it happens

LIMIT 5 without sorting returns five rows, but does not guarantee that they are the busiest:

SELECT observation_date, total_rides
FROM daily_ridership
LIMIT 5;

To get the busiest days, sort by total_rides before applying the limit.

Practice

Try it: Find the five days with the fewest rentals.

Show one possible answer
SELECT observation_date, total_rides
FROM daily_ridership
ORDER BY total_rides ASC
LIMIT 5;
Show a common mistake and why it happens

Using DESC returns the five busiest days, so it reverses the goal:

SELECT observation_date, total_rides
FROM daily_ridership
ORDER BY total_rides DESC
LIMIT 5;

For the lowest rental counts, choose ASC.

Summarize values

Goal: describe the size of a dataset numerically, such as how many days were observed and the range of rentals.

Summary (aggregate) functions calculate one value across several rows:

  • COUNT(*) counts rows.
  • COUNT(column) counts only the rows in which that column is not NULL. NULL is how a database marks a missing value; an empty text is not NULL and is counted.
  • COUNT(DISTINCT column) counts how many different values the column has. It works like DISTINCT, which lists each value once, but returns their number instead of the list.
  • SUM(column) adds values.
  • AVG(column) calculates a mean.
  • MIN(column) and MAX(column) return the lowest and highest values.

A missing value is not equal to anything, not even to another NULL, so WHERE column = NULL never matches a row.
To find the missing values write column IS NULL, and to keep the rows that have a value write column IS NOT NULL.
In this table no value is missing: WHERE total_rides IS NOT NULL keeps all 731 days and WHERE total_rides IS NULL keeps none.

Two more tools are used together with the summary functions, although they are not summary functions themselves:

  • Rounding: ROUND(value, digits) rounds one number to the number of digits after the decimal point that you ask for. A summary function can be placed inside it, as in ROUND(AVG(total_rides), 0): the average is calculated first, and then it is rounded to a whole number.
  • A name for the result: the keyword AS gives a result a readable name, as in AS average_per_day.

Example: count the days and summarize the demand:

SELECT COUNT(*) AS days,
       SUM(total_rides) AS rentals,
       ROUND(AVG(total_rides), 0) AS average_per_day,
       MIN(total_rides) AS quietest_day,
       MAX(total_rides) AS busiest_day
FROM daily_ridership;

Here are the 731 days that these numbers summarize:

Each of the 731 days as a dot, by date. Rentals rise in the warm months and fall in winter, and the 2012 dots lie above the 2011 dots. The busiest day had 8,714 rentals and the quietest had 22.
Each dot is one day: its date across and its number of rentals up. The dotted line is the average of all 731 days, 4,504, and the two circled dots are the busiest and the quietest day. The figure shows a rise and fall within each year, and it does not say why the days differ.

Example: count the days, the days that have a weather label, and the different weather labels:

SELECT COUNT(*) AS days,
       COUNT(weather) AS days_with_weather,
       COUNT(DISTINCT weather) AS weather_types
FROM daily_ridership;

The result is 731, 731 and 3. The three forms count different things:
COUNT(*) counts rows, COUNT(weather) counts the rows that have a weather label, and COUNT(DISTINCT weather) counts how many different labels there are, each label once, however many days carry it.
These are the three labels that SELECT DISTINCT weather lists.
A missing value is counted by neither of the two column forms.

Practice

Try it: How many days are in the dataset, and what is the rounded average number of daily rentals?

Show one possible answer
SELECT COUNT(*) AS days,
       ROUND(AVG(total_rides), 0) AS average_per_day
FROM daily_ridership;
Show a common mistake and why it happens

The reasoning: a column name inside COUNT seems to count days just as well as *.
But this query asks a different question, how many values are not missing in total_rides:

SELECT COUNT(total_rides) AS days
FROM daily_ridership;

This table has no missing values in that column, so the result is 731, the same as COUNT(*), but only by coincidence:
with missing values the two numbers differ.

Practice

Try it: On how many different days of the week do holidays fall?

Show one possible answer
SELECT COUNT(DISTINCT weekday) AS different_weekdays
FROM daily_ridership
WHERE holiday = 1;
Show a common mistake and why it happens

The reasoning: a holiday is a row, so COUNT(*) seems to answer a question about holidays.
But this query asks for the number of holiday days, 21, and not for how many different days of the week they fall on:

SELECT COUNT(*) AS different_weekdays
FROM daily_ridership
WHERE holiday = 1;

Calculations in a query

Goal: compute a new value from the columns, such as the share of casual rentals out of all rentals.

  • +, -, * and / calculate with columns and numbers, one row at a time.
    This expression gives, for each day, how many more rentals were registered than casual:

    registered_rides - casual_rides

    Parentheses set the order, as in arithmetic.

  • Dividing a whole number by a whole number gives a whole number in SQLite, rounded down:
    7 / 2 is 3, while 7.0 / 2 is 3.5. To keep the decimals, make one of the numbers a decimal.
    A percentage is therefore written 100.0 * SUM(a) / SUM(b), with 100.0 and not 100.

  • A calculation can be placed inside a summary function:

    AVG(registered_rides - casual_rides)

    This calculates the difference for each row first, and then averages the differences.

  • 1e6 is scientific notation for 1 times 10 to the power 6, which is 1000000 (a million), and 1e9 is a billion.
    Dividing by 1e6 turns a count into millions.

Example: the percentage of the rentals that were casual, the average gap between registered and casual rentals, and the total in millions:

SELECT ROUND(100.0 * SUM(casual_rides) / SUM(total_rides), 1)
    AS casual_percent,
       ROUND(AVG(registered_rides - casual_rides), 0) AS average_gap,
       ROUND(SUM(total_rides) / 1e6, 2) AS million_rentals
FROM daily_ridership;

The result is 18.8 percent, an average gap of 2,808 rentals a day and 3.29 million rentals.

Show a plausible mistake and why it happens

With 100 instead of 100.0, the division is between whole numbers, and the result loses its decimals (18.0 instead of 18.8):

SELECT ROUND(100 * SUM(casual_rides) / SUM(total_rides), 1) AS casual_percent
FROM daily_ridership;

Practice

Try it: For the summer season (Summer) only, show the percentage of the rentals that were casual (casual rentals out of all rentals), rounded to one decimal.

Show one possible answer
SELECT ROUND(100.0 * SUM(casual_rides) / SUM(total_rides), 1)
           AS casual_percent
FROM daily_ridership
WHERE season = 'Summer';

The result is 21.3 percent.

Show a common mistake and why it happens

The reasoning: 100 looks the same as 100.0. But the sums are whole numbers, so the division is a whole-number division and the decimals are lost (21.0 instead of 21.3):

SELECT ROUND(100 * SUM(casual_rides) / SUM(total_rides), 1) AS casual_percent
FROM daily_ridership
WHERE season = 'Summer';

Group with GROUP BY

Goal: compare summaries across groups, such as working and nonworking days.

The 731 daily rows are split into four seasons by GROUP BY season. The result has one row per season with the number of days and the average total rides.
GROUP BY turns many rows into one result row per group (real values from the practice database).
  • GROUP BY divides rows into groups based on one or more column values. A summary function calculates a value for each group.
  • A selected column alongside a summary should identify the group or be included in a summary function.
  • GROUP BY can group by a calculation. SQLite also lets it use the name that AS gave to the calculation in SELECT; some other databases do not, and writing the calculation again always works.

Example: compare daily rentals by day type:

SELECT working_day,
       COUNT(*) AS days,
       ROUND(AVG(total_rides), 0) AS average_rentals,
       ROUND(AVG(casual_rides), 0) AS average_casual,
       ROUND(AVG(registered_rides), 0) AS average_registered
FROM daily_ridership
GROUP BY working_day
ORDER BY working_day;

In this dataset, average rentals are about 4,585 on working days and 4,330 on nonworking days.
The mix is different: casual rentals average about 1,371 on nonworking days and 607 on working days, while registered rentals average about 3,978 on working days and 2,959 on nonworking days.
These are historical averages for one system, not current targets for another operator.
They suggest useful follow-up questions about how staffing and service schedules respond to different kinds of demand.

Show a plausible mistake and why it happens

Without GROUP BY working_day, the query returns one average for the whole dataset instead of one per day type:

SELECT working_day,
       ROUND(AVG(casual_rides), 0) AS average_casual
FROM daily_ridership;

To group by a piece of a text, give the piece a name with AS and group by that name.
This query counts the days in each year of the date text:

SELECT substr(observation_date, 1, 4) AS date_year,
       COUNT(*) AS days
FROM daily_ridership
GROUP BY date_year;

The result has two rows: 2011 with 365 days and 2012 with 366.

Grouping the days by the month column, with AVG(total_rides), gives one average for each month.
Here are the twelve results:

Bar chart with one bar for each calendar month, the two years combined. Average rentals per day rise from 2,176 in January to between 5,199 and 5,772 in each month from May to October, and fall to 3,404 in December.
Each bar is one calendar month, numbered 1 (January) to 12 (December) as in the month column: the average number of daily rentals over the days of that month in 2011 and 2012 together. The dotted line is the average of all days. These are averages of one system in two years; they do not explain why demand changes.

Practice

Try it: To compare the average number of casual rentals on working and nonworking days, show the day type (working day or not) and the average, rounded to a whole number.

Show one possible answer
SELECT working_day,
       ROUND(AVG(casual_rides), 0) AS average_casual
FROM daily_ridership
GROUP BY working_day;
Show a common mistake and why it happens

Without grouping by working_day, this query returns one average for the whole dataset:

SELECT ROUND(AVG(casual_rides), 0) AS average_casual
FROM daily_ridership;

To compare the two groups, include the grouping column in both the selected columns and GROUP BY.

Filter groups with HAVING

Goal: show only groups that meet a condition after their summaries have been calculated.

The steps of a query in the order the database processes them: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT. WHERE filters rows before grouping and HAVING filters groups after it.
WHERE filters rows before grouping; HAVING filters groups after it.
  • WHERE filters individual rows before grouping.
  • HAVING filters groups after their summaries have been calculated.
  • A condition on a regular column, such as day type, belongs in WHERE. A condition on an average or count belongs in HAVING.
  • In HAVING we write the calculation again, as AVG(total_rides), which works in every database. ORDER BY can use the name that AS gave to a result.

Example: show seasons whose average daily rentals exceed 4,000:

SELECT season,
       COUNT(*) AS days,
       ROUND(AVG(total_rides), 0) AS average_rentals
FROM daily_ridership
GROUP BY season
HAVING AVG(total_rides) > 4000
ORDER BY average_rentals DESC;

The 4,000 threshold is for this example; it is not an official service standard.

Show a plausible mistake and why it happens

This condition is invalid because the average has not been calculated when WHERE filters rows:

SELECT season, AVG(total_rides) AS average_rentals
FROM daily_ridership
WHERE AVG(total_rides) > 4000
GROUP BY season;

Put a condition on an average in HAVING, after grouping.

Practice

Try it: Calculate the average number of daily rentals by season using working days only, then show seasons whose average is greater than 3,000.
Show the season and the average, rounded to a whole number.

Show one possible answer
SELECT season,
       ROUND(AVG(total_rides), 0) AS average_rentals
FROM daily_ridership
WHERE working_day = 1
GROUP BY season
HAVING AVG(total_rides) > 3000;
Show a common mistake and why it happens

Filtering by working_day after grouping does not choose which days enter the calculation.
For example, this condition is in the wrong place:

SELECT season, ROUND(AVG(total_rides), 0) AS average_rentals
FROM daily_ridership
GROUP BY season
HAVING working_day = 1;

Filter source rows with WHERE before grouping, then filter the calculated average with HAVING after grouping.

Check your understanding

When filtering data, ask whether a condition selects individual rows before a calculation or groups based on a calculated result.
The day-type condition belongs in WHERE; the average condition belongs in HAVING.

Keep in mind

  • SELECT and FROM choose columns and a table. DISTINCT removes repeated values.
  • WHERE filters rows, GROUP BY forms groups, and HAVING filters groups.
  • ORDER BY sorts results. LIMIT shortens the result, so sort first when order matters.
  • COUNT, SUM, AVG, MIN, and MAX summarize values. COUNT(*) counts rows, COUNT(column) counts rows that have a value, and COUNT(DISTINCT column) counts different values.
  • +, -, * and / calculate in a query; write 100.0 for a percentage, so that the division keeps its decimals.
  • IN, LIKE, IS NULL and substr are tools for the conditions in WHERE.

Continue learning

Part 2 teaches how to change data safely, combine tables with JOIN, export results, and answer the capacity question with everything from this part:
continue to Part 2.

For more about structured data, tables, and databases, return to the opening-unit section on structured data and databases.