Constraints are rules that you can apply to columns in a SQL Server table to enforce data integrity and validity.
Data Definition Language (DDL) statements in SQL Server are used for defining and managing database objects, including tables. Here's how you create tables:
CREATE TABLE
Students (
StudentID INTPRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Birthdate DATE,
GPA DECIMAL(10, 2),
IsActive BIT);
In this example, a "Students" table is created with columns for student ID, first name, last name, birthdate, and GPA. The CREATE TABLE statement defines the table structure and data types for each column.
You can use DDL statements to modify existing tables. Common modifications include adding columns, changing column data types, and adding constraints. Here's how you can modify a table:
ALTER TABLE
Students
ADD
PhoneNumber
VARCHAR(20);
In this example, a new column named "PhoneNumber" is added to the "Students" table.
You can modify the data type or other properties of an existing column:
ALTER TABLE
Students
ALTER COLUMN
GPA
DECIMAL(4, 2);
To remove a column from a table, use the ALTER TABLE statement with the DROP COLUMN clause:
ALTER TABLE
Students
ADD
CONSTRAINT UK_PhoneNumber UNIQUE (PhoneNumber);
In this example, a unique constraint is added to ensure that phone numbers in the "Students" table are unique.
DROP TABLE
Students;
Caution: Be careful when using DROP TABLE, as it permanently deletes all data and the table structure.
1. Create a table named "Employees" with columns for employee ID (INT), first name (VARCHAR), last name (VARCHAR), and date of hire (DATE). Define appropriate constraints.
2. Add a new column to the "Products" table called "StockQuantity" to keep track of product stock levels. Set a default value of 0 for this column.
3. Modify the "Customers" table to add a constraint that ensures email addresses are unique.
4. Create a table named "Orders" with columns for order ID (INT), customer ID (INT), order date (DATE), and total amount (DECIMAL). Include primary key and foreign key constraints.
5. In a library database, create a table named "Books" with columns for book ID (INT), title (VARCHAR), author (VARCHAR), and publication date (DATE). Add a constraint to ensure that the title and author together are unique.
Constraints are rules that you can apply to columns in a SQL Server table to enforce data integrity and validity.
Data Manipulation Language (DML) statements in SQL Server are used to interact with data within tables. Here's how you can insert data into a table: