Create a table called students where each student has an id, name, and age, and ensure that the id uniquely identifies each student.
CREATE TABLE students (
id INT PRIMARY KEY ,
name VARCHAR ( 100 ),
age INT
);
Enter fullscreen mode
Exit fullscreen mode
Create a table employees where name and email cannot be empty, but phone_number can be optional.
CREATE TABLE employees (
id INT PRIMARY KEY ,
name VARCHAR ( 100 ) NOT NULL ,
email VARCHAR ( 100 ) NOT NULL ,
phone_number VARCHAR ( 15 )
);
Enter fullscreen mode
Exit fullscreen mode
Create a table users where both username and email must be unique across all records.
CREATE TABLE users (
id INT PRIMARY KEY ,
username VARCHAR ( 50 ) UNIQUE ,
email VARCHAR ( 100 ) UNIQUE
);
Enter fullscreen mode
Exit fullscreen mode
Create a table products where price must always be greater than 0 and stock cannot be negative.
CREATE TABLE products (
id INT PRIMARY KEY ,
name VARCHAR ( 100 ),
price DECIMAL ( 10 , 2 ) CHECK ( price > 0 ),
stock INT CHECK ( stock >= 0 )
);
Enter fullscreen mode
Exit fullscreen mode
Create a table orders where status should default to 'pending' if no value is provided, and created_at should store the current timestamp automatically.
CREATE TABLE orders (
id INT PRIMARY KEY ,
status VARCHAR ( 20 ) DEFAULT 'pending' ,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Enter fullscreen mode
Exit fullscreen mode
Create a table accounts where account_number must be unique and not null, and balance must always be greater than or equal to 0.
CREATE TABLE accounts (
id INT PRIMARY KEY ,
account_number VARCHAR ( 20 ) UNIQUE NOT NULL ,
balance DECIMAL ( 10 , 2 ) CHECK ( balance >= 0 )
);
Enter fullscreen mode
Exit fullscreen mode
Create a table enrollments where a student can enroll in multiple courses, but the combination of student_id and course_id must be unique.
CREATE TABLE enrollments (
student_id INT ,
course_id INT ,
PRIMARY KEY ( student_id , course_id )
);
Enter fullscreen mode
Exit fullscreen mode
Create two tables: departments with id and name, and employees with id, name, and department_id, ensuring that department_id in employees must exist in departments.
CREATE TABLE departments (
id INT PRIMARY KEY ,
name VARCHAR ( 100 )
);
CREATE TABLE employees (
id INT PRIMARY KEY ,
name VARCHAR ( 100 ),
department_id INT ,
FOREIGN KEY ( department_id ) REFERENCES departments ( id )
);
Enter fullscreen mode
Exit fullscreen mode
Modify the previous foreign key example so that when a department is deleted, all related employees are also deleted, and when a department ID is updated, it reflects in the employees table.
CREATE TABLE departments (
id INT PRIMARY KEY ,
name VARCHAR ( 100 )
);
CREATE TABLE employees (
id INT PRIMARY KEY ,
name VARCHAR ( 100 ),
department_id INT ,
FOREIGN KEY ( department_id )
REFERENCES departments ( id )
ON DELETE CASCADE
ON UPDATE CASCADE
);
Enter fullscreen mode
Exit fullscreen mode
Top comments (0)