Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
54 views

Lecture 04 - SQL Data Definition Language

The document provides information about structured query language (SQL) and how to define database objects using data definition language (DDL) statements in SQL. It discusses how to create tables, add and alter fields, set data types and sizes, add primary keys and foreign keys, and other constraints. Examples are provided for creating tables with fields of different data types, specifying primary keys, adding foreign keys, and using constraints to restrict field values.

Uploaded by

Holy Trap beats
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

Lecture 04 - SQL Data Definition Language

The document provides information about structured query language (SQL) and how to define database objects using data definition language (DDL) statements in SQL. It discusses how to create tables, add and alter fields, set data types and sizes, add primary keys and foreign keys, and other constraints. Examples are provided for creating tables with fields of different data types, specifying primary keys, adding foreign keys, and using constraints to restrict field values.

Uploaded by

Holy Trap beats
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Structured

Query
Language
(SQL)
With
Microsoft
SQL Server
Work Hard!!!
Study Hard!!!!
Target A+ for each Subject!!!!
Become a Champion and Make yourself
Proud!!!!
Database Management System (DBMS)
A DBMS is a set of software programs that can be used to create and maintain a database.

E.g.:

• MS Access

• MySQL

• SQL Server

• Oracle

• IBM DB2

• Mongo DB

• H2
Structured Query Language (SQL)

• SQL is used to communicate with a database.

• It act as an interface language between the user and the database

• It is a Keyword-based language.

• Each statement begins with a unique keyword.

• Statements are not case sensitive.


Structured Query Language (SQL)

SQL consists of three main types of statements

• Data Definition Language (DDL)

• Data Manipulation Language (DML)

• Data Controlled Language (DCL)


Data Definition Language
• These statements are used to create new objects, alter the structure
of existing objects, or to remove objects from the system.

CREATE, DROP, ALTER, RENAME, DESCRIBE, TRUNCATE

• These commands cannot use to modify data.


Data Manipulation Language

These statements change the data in the database.

INSERT, UPDATE, DELETE, SELECT


Data Control Language
• These statements control the access of the data in the database
and determines how, when, and whom can manipulate data.

• They provide commands to specify access rights to tables, and


views.

GRANT, REVOKE, ROLLBACK, COMMIT


Data Definition
Language (DDL)
Data Definition Language
1. CREATE DATABASE

CREATE DATABASE Database Name;

Exercise
Create A Database Called Company.

Answer :
Create Database Company;
2. SELECT DATABASE
USE Database Name;

Exercise:

Select the Database Company.

Answer:

Use Company;
3. CREATE TABLE
COMMON DATA TYPES
INT(n)
n = maximum number of digits
VARCHAR (n)
n= maximum length of character strings
CHAR (n)
n= maximum length of character strings.
DECIMAL (n, d)
n = maximum number of digits
d = maximum number of digits right of the decimal
DATE
The standard format is YY-Mon-DD
Syntax:

CREATE TABLE table_name (column_name datatype(size), column_name


datatype(size)….);
Example
CREATE TABLE DEPT (deptno int , dname varchar (14), dloc varchar (15));

When you create a table you specify the


* Table name
* Column names
* Type of values in the column (Data types)
* Maximum width of the column
Exercise

Create A Table Called Client.

CREATE TABLE client

(client_no varchar(6),

name varchar(20),

address varchar(30),

telephone int,

balance_due int,

order_date date,

Primary key(client_no));
Since we need to do table constraints, let me do the Insert operation first.
Remember this is a Data Manipulation Operation.

Insert Data into a table

Syntax:
  INSERT INTO table_name
(column_name, column_name….)
VALUES (expression, expression…);
Exercise
INSERT FOLLOWING DATA.
Client_no Name Address Telephone Balance_due Order Date
C100 Amali Colombo 0772569014 5000 2012-05-11

C200 Saman Kandy 0712569874 12500 2010-06-11


INSERT INTO client
First (client_no, name, address, telephone, balance_due,
Method
order_date) VALUES (‘C100’, ‘Amali’, ‘Colombo’,
0772569014, 5000, ‘2012-05-11’);

Second
Method. But INSERT INTO client
only
possible if VALUES (‘C100’, ‘Amali’, ‘Colombo’, 0772569014, 5000,
data is
available for ‘2012-05-11’);
each column

Default format for entering dates: ‘YYYY-MM-DD’


4. Create Tables with constraints
NULL values Concept
• Setting a null value is appropriate when the actual value is unknown or
when a value would not be meaningful.

• A null value is not equivalent to a value of zero.

• A null value will evaluate to null in any expression, e.g.: null


multiplied by 10 is null.

• When a column name is defined as not null, then that column


becomes a mandatory column. It implies that the user is forced to
enter data into that column.

Ex: Client_Name varchar(30) not null


Default value concept:

At the time of cell creation a ‘default value’ can be assigned to it.


The data type of the default value should match the data type of
column.

Ex:

CREATE TABLE client (client_no varchar(6), name varchar(20), address varchar(30)


default 'Colombo', telephone int, balance_due int, order_date date, Primary
key(client_no) );
Check Integrity Constraints

Use CHECK constraint when you need to enforce integrity rule


that can be evaluated based on a logical expression.
Following are few examples of appropriate CHECK constraint:

1. A CHECK constraint on the client_no column of client so that


client_no values starts with ‘C’.

2. A CHECK constraint of name column of the client so that


the name is entered in upper case.

3. A CHECK constraint on the address column of client so


that only the address “Colombo”, “Galle”, “Matara”, and
“Jaffna” are allowed.
Answers
1) Create table client with client_no values starts with ‘C’.

CREATE TABLE client (client_no varchar(10) constraint ck_clientno CHECK


(client_no like ‘C%’), name varchar(20), address varchar(30), telephone int,
balance_due int, order_date date, Primary key(client_no) );

2) Create table client with the name is entered in upper case

CREATE TABLE client (client_no varchar(10), name varchar(20) constraint


ck_name CHECK (name=upper(name)), address varchar(30), telephone int,
balance_due int, order_date date, Primary key(client_no) );

Here by default SQL Server ignore the case sensitive


3) Create table client with address column of client so that only the address
“Colombo”, “Galle”, “Matara”, and “Jaffna” are allowed.

CREATE TABLE client (client_no varchar(10), name varchar(20), address


varchar(15) constraint ck_address CHECK (address in ('Colombo’, ’Galle’,
’Matara’, ’Jaffna’), telephone int, balance_due int, order_date date, Primary
key(client_no) );

Another Example with all the constraints

Create table SalesPerson (EMP_ID int primary key, EmpName varchar(20) not null,
Ranking int default 1 not null check (Ranking in (1,2,3)), salary decimal(7,2) not null
check(salary>=10000));
Exercise
Field Name Filed Filed
Type Size
Primary Key
Client_No Varchar 6
Cannot be Null
Name Varchar 20
Should only contains A, Address Varchar 30
B, C
Rank Varchar 1
Should between 5000 to Balance_due Decimal 8,2
50000
Order_date Date
Default value should be
System Date
Answer

Create table Client (Client_No varchar(6) primary key, Name varchar(20)


not null, address varchar (30) not null, Rank varchar(1) check (rank in
('A', 'B', 'C')), balance_due decimal(8,2) check (balance_due>5000 and
balance_due <50000), order_date date default getdate());
Referential Integrity Constraint (Foreign Key)
• Foreign key provides referential integrity rules either within a table or among
tables. A foreign key is used in a relationship with either a primary key of the
same table or another table.

• The syntax of the CREATE TABLE command with the FOREIGN KEY column
constraint is. Other than this syntax there are different ways to create a Foreign
Key on another table.

CREATE TABLE table_name (column_name datatype(size), column_name


datatype(size) [CONSTRAINT constraint_name] REFERENCES
table_name(column_name),... );
Referential Integrity Constraint (Foreign Key)
Example: An employee works for a department. One employee belongs to one
department and many employees will be there in a department.
PK FK PK
EmpNo Name Salary DeptNo DeptNo DepName

First create the Department table. Then create Employee table with a foreign key by taking
primary key of Department table.

Create table Department (DeptNo varchar(5) primary key, DeptName varchar(10));

Create table Employee (EmpNo varchar(4) primary key, Name varchar(10), Salary int,
DeptNo varchar(5) References Department (DeptNo));
Another Way

Create table Employee (EmpNo varchar(4) primary key, Name varchar(10), Salary int,
DeptNo varchar(5) Foreign key References Department (DeptNo));

Another Way

Create table Employee (EmpNo varchar(4) primary key, Name varchar(10), Salary int,
DeptNo varchar(5), Foreign key (DeptNo) References Department (DeptNo));
Example :
Invoice Order
PK PK FK FK FK
InvNo Name Date Order_Id InvNo Emp_Id Cus_Id SalesDate

SalesPerson Customer
PK PK
Emp_Id Emp_Name Cus_Id CusName Status

Create table Order (Order_Id int primary key, InvNo varchar(5), Emp_Id varchar(5),
Cus_Id varchar(5), Sales_date Date, Foreign Key (InvNo) References Invoice (InvNo),
Foreign Key (Emp_Id) References SalesPerson (Emp_Id), Foreign Key (Cus_Id)
References Customer (Cus_Id));
Composite Primary Key
If there are more than one primary key in the table you can set composite primary
keys.
PK FK PK
EmpNo Name Salary DeptNo DeptNo DepName

Example :
Suppose EmpNo and DeptNo are primary keys of the Employee table.

Create table Employee (EmpNo varchar(4), Name varchar(10), Salary int, DeptNo
varchar(5) Foreign key References Department (DeptNo), Primary Key (EmpNo,
DeptNo));
5. ALTER TABLE
ADD FIELD

Syntax
ALTER TABLE table_name
ADD newcolumn_name data_type(size),….;
Example:

Add the following columns to the table client.

Column name Data type


Fax number int

Order amount int

ALTER TABLE client ADD fax_no int , amount int ;


5. ALTER TABLE
CHANGE FIELD TYPE/FIELD SIZE

Syntax
ALTER TABLE table_name
ALTER COLUMN column_name newdata_type(size),….;
Exercise

Change Datatype Of fax_no Field As Varchar

ALTER TABLE client


ALTER COLUMN fax_no varchar(8);
5. ALTER TABLE
DROP FIELD

Syntax
ALTER TABLE table_name
DROP COLUMN column_name;
Exercise

Ex: Drop Field fax_no.

ALTER TABLE client


DROP COLUMN fax_no;
5. ALTER TABLE
FOREIGN KEY on ALTER TABLE
Syntax
ALTER TABLE table_name ADD FOREIGN KEY column_name REFERENCES table_name
(column_name);

To create a FOREIGN KEY constraint on the “DeptNo" column when the “Employee" table is already
created, use the following command. But remember before you execute this command first you should
add DeptNo column to the Employee table.
Example:
ALTER TABLE Employee
ADD FOREIGN KEY (DeptNo) REFERENCES Department (DeptNo);

Another Way
ALTER TABLE Employee
ADD CONSTRAINT FK_Employee_Dept
FOREIGN KEY (DeptNo) REFERENCES Department (DeptNo);
5. ALTER TABLE
Drop the Foreign Key Constraint

Syntax:
ALTER TABLE table_name
DROP CONSTRAINT constraint_name

Example:
ALTER TABLE Employee
DROP CONSTRAINT FK_Employee_Dept
6. Dropping Table
Syntax
Drop Table table_name

• If you have data in the table, it will delete permanently.


• The data and Table structure both will remove from the
database.
• Once the Table is deleted, you cannot get it back.

Example:
Drop table Client;
7. Truncate Table
Syntax
Truncate Table table_name

• This statement will remove all the data from the table
but table structure will remain as it is.

Example:
Truncate Table Client;
8. Rename Table
SQL Server does not have any statement that directly renames a
table. However, it does provide you with a stored procedure
named sp_rename that allows you to change the name of a
table.

Syntax:
EXEC sp_rename ‘old_table_name', ‘new_table_name'

Example:
EXEC sp_rename 'Client', 'Client_Master'
9. Describe Table
The simplest way to use a stored procedure sp_columns to show
the columns and related information about a SQL Server table is to
execute the stored procedure passing it the table name

Syntax:
Exec sp_columns table_name;

Example:
Exec sp_columns Client;
10. Drop the Database
You can drop the Database using the following syntax.

Syntax:
Drop Database database_name;

Example:
Drop Database Company;

You might also like