Relationship in queries
Last updated
SELECT students.student_id, students.name FROM students LEFT JOIN student_details ON students.student_id = student_details.student_id WHERE student_details.student_id IS NULL;SELECT students.name, student_details.address FROM students LEFT JOIN student_details ON students.student_id = student_details.student_id WHERE students.student_id = 2;-- Insert authors
INSERT INTO authors (author_id, name) VALUES
(1, 'Jane Doe'),
(2, 'John Smith'),
(3, 'Alice Johnson');-- Insert books
INSERT INTO books (book_id, title, author_id) VALUES
(101, 'The Art of SQL', 1),
(102, 'Database Design Mastery', 1),
(103, 'Query Optimization Techniques', 2),
(104, 'Introduction to Relational Databases', 3);SELECT books.book_id, books.title, authors.name AS author_name FROM books JOIN authors ON books.author_id = authors.author_id;SELECT authors.author_id, authors.name FROM authors LEFT JOIN books ON authors.author_id = books.author_id WHERE books.book_id IS NULL;-- Insert courses
INSERT INTO courses (course_id, course_name) VALUES
(201, 'Database Fundamentals'),
(202, 'Advanced SQL Queries'),
(203, 'Data Modeling and Design'),
(204, 'Database Administration');-- Insert student courses
INSERT INTO student_courses (student_course_id, student_id, course_id) VALUES
(1, 1, 201),
(2, 1, 202),
(3, 2, 202),
(4, 2, 203),
(5, 3, 201),
(6, 3, 204);SELECT students.name, courses.course_name FROM students JOIN student_courses ON students.student_id = student_courses.student_id JOIN courses ON student_courses.course_id = courses.course_id WHERE students.student_id = 1;SELECT courses.course_name, students.name FROM courses JOIN student_courses ON courses.course_id = student_courses.course_id JOIN students ON student_courses.student_id = students.student_id WHERE courses.course_id = 201;SELECT students.name, COALESCE(courses.course_name, 'No Course') AS course_name FROM students LEFT JOIN student_courses ON students.student_id = student_courses.student_id LEFT JOIN courses ON student_courses.course_id = courses.course_id;