Introduction
Good database design helps keep data organized, easy to find, and safe from mistakes.
-- No single syntax for design, but key ideas include: -- 1. Define tables with clear columns and data types -- 2. Use primary keys to identify rows uniquely -- 3. Use foreign keys to link related tables -- 4. Avoid repeating data (normalization) -- 5. Add indexes for faster searches
CREATE TABLE Customers ( CustomerID INT PRIMARY KEY, Name VARCHAR(100), Email VARCHAR(100) UNIQUE );
CREATE TABLE Orders ( OrderID INT PRIMARY KEY, CustomerID INT, OrderDate DATE, FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) );
-- Avoid repeating customer info in Orders table to prevent mistakes.CREATE TABLE Authors ( AuthorID INT PRIMARY KEY, Name VARCHAR(100) NOT NULL ); CREATE TABLE Books ( BookID INT PRIMARY KEY, Title VARCHAR(200) NOT NULL, AuthorID INT, FOREIGN KEY (AuthorID) REFERENCES Authors(AuthorID) ); INSERT INTO Authors (AuthorID, Name) VALUES (1, 'Jane Austen'); INSERT INTO Books (BookID, Title, AuthorID) VALUES (101, 'Pride and Prejudice', 1); SELECT Books.Title, Authors.Name FROM Books JOIN Authors ON Books.AuthorID = Authors.AuthorID;
id column?id INT PRIMARY KEY inside the column definition.CREATE TABLE authors (author_id INT PRIMARY KEY, name VARCHAR(100));CREATE TABLE books (book_id INT PRIMARY KEY, title VARCHAR(100), author_id INT, FOREIGN KEY (author_id) REFERENCES authors(author_id));author_id = 5, but no author with author_id = 5 exists?orders with columns order_id (primary key), customer_id, and order_date. You want to add a foreign key constraint on customer_id referencing customers(customer_id). Which of these statements has an error?customer_id, causing syntax error.Pass the test and this pattern moves unknown