SQL Generation

Turn plain-English questions into correct SQL against a schema. The skill behind analytics chat, natural-language dashboards, and 'just ask the database' interfaces.

100
Duration
4s
Input Tokens
1023
Output Tokens
202
Cost
$0.00
Context
Input
Add a foreign key from completions to enrollments, linking through user_id and course_id to ensure data consistency.
Expected output
ALTER TABLE completions ADD COLUMN course_id INT, ADD CONSTRAINT fk_completions_user_course FOREIGN KEY (user_id, course_id) REFERENCES enrollments(user_id, course_id);
Model output
ALTER TABLE completions
  ADD COLUMN course_id INT;

UPDATE completions c
SET course_id = l.course_id
FROM lessons l
WHERE l.lesson_id = c.lesson_id;

ALTER TABLE completions
  ALTER COLUMN course_id SET NOT NULL;

ALTER TABLE completions
  ADD CONSTRAINT completions_user_course_fk
  FOREIGN KEY (user_id, course_id)
  REFERENCES enrollments (user_id, course_id)
  ON DELETE RESTRICT;

CREATE INDEX IF NOT EXISTS idx_completions_user_course
  ON completions(user_id, course_id);