Skip to article frontmatterSkip to article content

University Queries

from university import *

dj.config['display.limit'] = 5  # keep ouptput short

dj.Diagram(schema)
Loading...
assert Grade(), "populate the database first"

Single-Table Queries

# All student info. Displaying a query gives you a preview of the results but does not fetch the data into memory.
Student()
Loading...
# You can fetch the data into memory using the fetch() method.
query = Student()  # forms the query
data = query.fetch()  # fetches query results into memory
# See help(query.fetch) help help(query.fetch1) for more options.

data
array([(1000, 'Allison', 'Hill', 'F', datetime.date(1994, 10, 30), '819 Johnson Course', 'East William', 'AK', '74064', '+1-586-737-9402x6542'), (1001, 'James', 'Howard', 'M', datetime.date(2008, 3, 7), '78161 Calderon River Suite 931', 'Lake Jeremyport', 'CO', '31013', '(547)452-5534x1928'), (1002, 'Devin', 'Schaefer', 'M', datetime.date(1997, 2, 22), '503 Linda Locks', 'Carlshire', 'FM', '94599', '+1-876-772-4238x8496'), ..., (2997, 'Anna', 'Thomas', 'F', datetime.date(2005, 2, 27), '2926 Chapman Fort Suite 201', 'West Donald', 'CT', '33462', '263.502.9862x8118'), (2998, 'Jeanette', 'Meyer', 'F', datetime.date(2003, 1, 3), '135 Emily Gateway Suite 478', 'West Mark', 'RI', '16828', '481.533.9172x3288'), (2999, 'Michael', 'Kirby', 'M', datetime.date(1994, 9, 11), '87055 Shaffer Burg', 'Hannahfort', 'MD', '46623', '613-369-0702x4991')], shape=(2000,), dtype=[('student_id', '<i8'), ('first_name', 'O'), ('last_name', 'O'), ('sex', 'O'), ('date_of_birth', 'O'), ('home_address', 'O'), ('home_city', 'O'), ('home_state', 'O'), ('home_zip', 'O'), ('home_phone', 'O')])

All following examples will only show query previews without fetching the data into memory.

# Show female students from Utah
Student & {'home_state': 'UT', 'sex': "F"}
Loading...
# Show names female students not from Utah
((Student & {'sex': "F"}) - {'home_state': 'UT'}).proj('first_name', 'last_name')
Loading...
# Show full names of female students not from Utah
(Student & "sex='F' AND home_state <> 'UT'").proj(full_name='CONCAT(first_name, " ",last_name)')
Loading...
# Show the three youngest students named "David"
Student & {'first_name': 'David'} & dj.Top(limit=3, order_by='date_of_birth DESC')
Loading...
# Show student names and their ages in years
Student.proj('first_name', 'last_name', age='FLOOR(DATEDIFF(CURDATE(), date_of_birth) / 365.25)')
Loading...
# IDs of sudents whose birthday is today
(Student & 'month(date_of_birth) = month(CURDATE()) AND day(date_of_birth) = day(CURDATE())').proj()
Loading...
# Students with their age and all other attributes
# ... is used to select all attributes in addition to the calculated ones
Student.proj(..., age='FLOOR(DATEDIFF(CURDATE(), date_of_birth) / 365.25)')
Loading...
# Show all info except for the date of birth and phone number
Student.proj(..., '-date_of_birth', '-home_phone')
Loading...
# Show all students who are either from Utah or California
Student & [{'home_state': 'UT'}, {'home_state': 'CA'}]  # condition in a list are combined with OR
Loading...
# Show all students who are either from Utah or California
Student & 'home_state in ("UT", "CA")'   # this relies on SQL condition syntax
Loading...

Subquries in Restrictions

The restriction operators & and - can use other queries as conditions.

# Students with majors in math

Student & (StudentMajor & {'dept': 'MATH'})
Loading...
# Students who have not taken a course in math

Student.proj('first_name', 'last_name') - (Enroll & {'dept': 'MATH'})
Loading...
# Students with ungraded enrollments in current term

Student.proj('first_name', 'last_name') & ((Enroll & CurrentTerm) - Grade)
Loading...
# All-'A' students
(Student.proj('first_name', 'last_name') & Grade) - (Grade - {'grade': 'A'})
Loading...

Restrictions of Universal Sets

# All unique first names among male students

dj.U('first_name') & (Student & {'sex': 'M'})
Loading...
# Show all years of birth for students registered in the current term

dj.U('year') & (Student.proj(year='year(date_of_birth)') & (Enroll & CurrentTerm))
Loading...

Joins

# Students with their majors

Student.proj('first_name', 'last_name') * StudentMajor
Loading...
# Student names along with their majors and declaration dates

Student.proj('first_name', 'last_name') * StudentMajor
Loading...
# Show students names along with their majors and declaration dates, includes students without majors
Student.proj('first_name', 'last_name').join(StudentMajor, left=True)
Loading...

Aggregation

# Show departments with the number of students in each
Department.aggr(StudentMajor, count='COUNT(student_id)')
Loading...
# Departments with the number of male and female students 
Department.aggr(StudentMajor*Student, males='SUM(sex="M")', females='SUM(sex="F")')
Loading...
# Courses taught in the current term with student enrollment counts
Course.aggr(Enroll & CurrentTerm, ..., students='COUNT(student_id)')
Loading...
# Students and their GPA and total credits
Student.aggr(Course*Grade*LetterGrade,
    'first_name', 'last_name', credits='sum(credits)', gpa='sum(points*credits)/sum(credits)')
Loading...
# Top five students by GPA with at least 12 credits
Student.aggr(Course*Grade*LetterGrade,
    'first_name', 'last_name', credits='sum(credits)', gpa='sum(points*credits)/sum(credits)'
    ) & 'credits > 12' & dj.Top(limit=5, order_by='gpa DESC')
Loading...