Reference Desk Queries

LIS 4050, Week 8. Write SQL that answers each question, then run it against the library’s tables to check your work.

The questions

  1. Can I see every title we own?
  2. What’s the phone number for the Eastside branch?
  3. Which patrons call Central home? List them alphabetically.
  4. How many items does patron P101 have checked out?

Stretch: Which titles has P101 checked out? (Hint: JOIN)

SQL cheat sheet

The basic pattern. Clauses always go in this order, and the query ends with a semicolon:

SELECT columns
FROM table
WHERE condition
ORDER BY column;
  • SELECT * means every column.
  • Text values go in single quotes: WHERE Title = 'Kindred'. Numbers don’t: WHERE Barcode = 3101.
  • Sort A to Z with ORDER BY Title, or Z to A with ORDER BY Title DESC.
  • Count rows instead of listing them: SELECT COUNT(*) FROM ITEM;

To combine two tables, JOIN them on the column they share:

SELECT PATRON.PatronName, BRANCH.BranchPhone
FROM PATRON JOIN BRANCH
  ON PATRON.HomeBranch = BRANCH.BranchName;
Ctrl+Enter (or ⌘+Enter) also runs it. Text values go in ‘single quotes’; numbers don’t.

Results

Loading the tables…

Keep practicing

  • Library Carpentry: SQL: free lessons written for library workers, using a sample of journal article data. It uses SQLite, the same database this page runs on.
  • SQLBolt: short interactive lessons with exercises you run in your browser.
  • W3Schools SQL Tutorial: a quick reference for each command, with examples you can try.