Changing Data · Problem 117 of 118

Copy Low Grades to a New Table

MediumChanging DataSchool data

Create a table named low_grades that holds the student_id, section_id and grade of every enrollment with a grade below 40.

Check query. After your statements run, this query is run on the changed data and its result is compared with the expected one:

SELECT COUNT(*) AS rows_copied, MIN(grade) AS lowest, MAX(grade) AS highest
FROM low_grades;
Hint 1

CREATE TABLE low_grades AS SELECT ... FROM enrollments WHERE ....

Reference solution

CREATE TABLE low_grades AS
SELECT student_id, section_id, grade
FROM enrollments
WHERE grade < 40;

CREATE TABLE ... AS SELECT builds the table from the query result in one step. The new table has the columns and the data but none of the rules (no primary key, no NOT NULL, no defaults). For anything permanent, create the table with the rules you want and fill it with INSERT ... SELECT, as in the alternative. Without the WHERE, the new table would silently hold all 1,002 enrollments.

Another way. Create the table first, then fill it with INSERT ... SELECT. This lets you choose the column types and add constraints.

CREATE TABLE low_grades (student_id INTEGER, section_id INTEGER, grade REAL);
INSERT INTO low_grades (student_id, section_id, grade)
SELECT student_id, section_id, grade FROM enrollments WHERE grade < 40;