Sample Database
Customers Table
CustomerID FirstName LastName Email City Country
Product Table
ProductID ProductName Category Price StockQuantity
1 Laptop Electronics 1200.00 25
2 Headphones Electronics 50.00 100
3 Office Chair Furniture 200.00 15
4 Coffee Maker Appliances 75.00 40
Orders Table
OrderID CustomerID TotalAmount
1 1 1275.00
2 2 250.00
3 3 400.00
OrderDetails Table
OrderDetailID OrderID ProductID Quantity UnitPrice Subtotal
1 1 1 1 1200 1200
2 1 2 1 50 50
3 2 3 1 200 200
4 3 4 5 75 375
SQL command
Create Database
The CREATE DATABASE statement is used to create a new SQL database.
CREATE DATABASE databasename;
Drop Database
The DROP DATABASE statement is used to drop an existing SQL database.
DROP DATABASE databasename;
Backup Database
The BACKUP DATABASE statement is used in SQL Server to create a full back up
of an existing SQL database.
BACKUP DATABASE databasename
TO DISK = 'filepath';
Create Table
The CREATE TABLE statement is used to create a new table in a database.
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
Insert into
Data can be inserted into table as follows:
One row or multiple rows at a time
INSERT INTO Customers (CustomerName, Country)
VALUES ('Cardinal', 'Norway'),
('Mary', 'Finland');
If data is inserted for all columns, we can skip mentioning column
names :
INSERT INTO Customers
VALUES ('Cardinal', 'Norway'),
Drop Table
The DROP TABLE statement is used to drop an existing table in a database.
DROP TABLE table_name;
Alter Table
The ALTER TABLE statement is used to add, delete, or modify columns in an
existing table.
The ALTER TABLE statement is also used to add and drop various constraints on
an existing table.
1. ALTER TABLE - ADD Column
To add a column in a table, use the following syntax:
ALTER TABLE table_name
ADD column_name datatype;
2. ALTER TABLE - ADD Column
To delete a column in a table, use the following syntax (notice that some
database systems don't allow deleting a column):
ALTER TABLE table_name
DROP COLUMN column_name;
3. ALTER TABLE - ALTER/MODIFY
DATATYPE
To change the data type of a column in a table, use the following syntax:
ALTER TABLE table_name
MODIFY column_name datatype;
4. DROP COLUMN Example
Next, we want to delete the column named "DateOfBirth" in the "Persons" table.
ALTER TABLE table_name
DROP COLUMN column_name
Constraints
Not Null
Unique
Primary Key
Foreign Key
Check
Default
Index
Dates