0% found this document useful (0 votes)
7 views10 pages

Introduction To Data Definiton Language

This document provides an introduction to Structured Query Language (SQL), detailing its use in defining, querying, and modifying databases through Data Definition Language (DDL) and Data Manipulation Language (DML). It covers various SQL data types, methods for creating database objects, and the syntax for creating tables and defining integrity constraints such as primary keys and foreign keys. Additionally, it discusses the importance of referential integrity in maintaining data consistency across related tables.

Uploaded by

watashinojesse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views10 pages

Introduction To Data Definiton Language

This document provides an introduction to Structured Query Language (SQL), detailing its use in defining, querying, and modifying databases through Data Definition Language (DDL) and Data Manipulation Language (DML). It covers various SQL data types, methods for creating database objects, and the syntax for creating tables and defining integrity constraints such as primary keys and foreign keys. Additionally, it discusses the importance of referential integrity in maintaining data consistency across related tables.

Uploaded by

watashinojesse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Introduction to Structured Query Language (SQL)

The SQL is used to define, query and modify databases. The SQL includes data definition
language (DDL) and data manipulation language (DML).

The SQL DDL statements

This chapter describes some of the SQL statements concerning data definition language
(DDL). The DDL statements are divided into three groups. The first group includes
statements that create objects, the second group includes statements that modify the structure
of objects, and the third group includes statements that remove objects.

Before of all SQL uses different data types, some of which can be categorized as follows:

Numeric Data Types

 INTEGER: Represents integer values that can be stored in 4 bytes


 SMALLINT: Represents integer values that can be stored in 2 bytes
 DECIMAL(p,[s]): Describes fixed-point values. The argument p (precision) specifies
the total number of digits with assumed decimal point s (scale) digits from the right.
 FLOAT[(p)]: Represents floating-point values, like REAL. p defines the precision
with p < 25 as single precision (4 byte) and p >= 25 as double precision (8 byte).
 MONEY Used for representing monetary values. MONEY values correspond to 8-
byte DECIMAL values and are rounded to four digits after the decimal point.

Character Data Types

 CHAR[(n)]: Represents a fixed-length string of single-byte characters, where n is the


number of characters inside the string.
 VARCHAR[(n)]: Describes a variable-length string of single-byte characters (0 < n ≤
8000). In contrast to the CHAR data type, the values for the VARCHAR data type are
stored in their actual length.
 NCHAR[(n)]: Stores fixed-length strings of Unicode characters. The main difference
between the CHAR and NCHAR data types is that each character of the NCHAR data
type is stored in 2 bytes, while each character of the CHAR data type uses 1 byte of
storage space. Therefore, the maximum number of characters in a column of the
NCHAR data type is 4000.

Temporal Data Types

 DATETIME
 DATE
 TIME
Creating Database Objects

1
All objects of a database can be physical or logical. The physical objects are related to the
organization of the data on the physical device (disk). Database Engine’s physical objects are
files and file groups. Logical objects represent a user’s view of a database. Databases, tables,
columns, and views (virtual tables) are examples of logical objects.

Creation of a Database

Two basic methods are used to create a database. The first method involves using Object
Explorer in SQL Server Management Studio. The second method involves using the
Transact-SQL statement CREATE DATABASE. This statement has the following general
form, the details of which are discussed next:

CREATE DATABASE db_name

Example 1: Create a simple database without any further specifications. To execute this
statement, type it in the Query Editor window of SQL Server Management Studio and press
F5. We will use the following database (i.e., Company database) which we used throughout
this course.
EMPLOYEE
DNO SUPERSSN SEX ADDRESS BDATE SSN LNAME MINIT FNAME
5 987654321 M 731 Fondren, Houston, TX 09-Jan-55 123456789 Smith B John
5 888665555 M 638 Voss, Houston, TX 08-Dec-45 333445555 Wong T Franklin
5 333445555 F 5631 Rice, Houston, TX 31-Jul-62 453453453 English A Joyce
5 333445555 M 975 Fire Oak, Humble, TX 15-Sep-52 666884444 Narayan K Ramesh
1 Null M 450 Stone, Houston, TX 10-Nov-27 888665555 Borg E James
4 888665555 F 291 Berry, Bellaire, TX 20-Jun-31 987654321 Wallace S Jennifer
4 987654321 M 980 Dallas, Houston, TX 29-Mar-59 987987987 Jabbar V Ahmad
4 987654321 F 3321 Castle, SPring, TX 19-Jul-58 999887777 Zelaya J Alicia
DEPT_LOCATIONS
DEPARTMENT DNUMBER DLOCATION
DNAME DNUMBER MGRSSN MGRSTARTDATE 1 Houston
Headquarters 1 888665555 19-Jun-71 4 Stafford
Administration 4 987654321 01-Jan-85 5 Bellaire
Research 5 333445555 22-May-78 5 Sugarland
Automation 7 123456789 06-Oct-05 5 Houston
WORKS_ON
PROJECT
ESSN PNO Hours
PNAME PNUMBER PLOCATION DNUM
123456789 1 32.5
ProductX 1 Bellaire 5
123456789 2 7.5
ProductY 2 Sugarland 5
333445555 2 10
ProductZ 3 Houston 5
333445555 3 10
Computerization 10 Stafford 4
333445555 10 10
Reorganization 20 Houston 1
333445555 20 10
Newbenefits 30 Stafford 4
453453453 1 20
DEPENDENT 453453453 2 20
ESSN DEPENDENT_NAME SEX BDATE RELATIONSHIP 666884444 3 40
123456789 Alice F 31-Dec-78 Daughter 888665555 20
123456789 Elizabeth F 05-May- Spouse 987654321 20 15
57 987654321 30 20
123456789 Michael M 01-Jan-78 Son 987987987 10 35
333445555 Alice F 05-Apr-76 Daughter 987987987 30 5
333445555 Joy F 03-May- Spouse 999887777 10 10
48 999887777 30 30
333445555 Theodore M 25-Oct-73 Son
USE
987654321 Abner M 29-Feb-32 Spouse master;

2
CREATE DATABASE Company;

Example 2:
USE master;
CREATE DATABASE company
ON (
NAME=company_dat,
FILENAME = 'C:\company.mdf',
SIZE = 10,
MAXSIZE = 100,
FILEGROWTH = 5
);

LOG ON
( NAME=company_log,
FILENAME = 'C:\company.ldf',
SIZE = 40,
MAXSIZE = 100,
FILEGROWTH = 10
);

Example 2 creates a database called company. Because the PRIMARY option is omitted, the
first file is assumed as the primary file. This file has the logical name company_dat and is
stored in the file company.mdf. The original size of this file is 10MB. Additional portions of
5MB of disk storage are allocated by the system, if needed. If the MAXSIZE option is not
specified or is set to UNLIMITED, the file will grow until the disk is full. There is also a
single transaction log file with the logical name company_log and the physical name
company.ldf. All options of the file specification for the transaction log have the same name
and meaning as the corresponding options of the file specification for the data file. Using the
Transact-SQL language, you can apply the USE statement to change the database context to
the specified database.

CREATE TABLE: A Basic Form

The CREATE TABLE statement creates a new base table with all corresponding columns
and their data types. The basic form of the CREATE TABLE statement is

CREATE TABLE table_name


(
col_name1 type1 [NOT NULL| NULL] ,
col_name2 type2 [NOT NULL| NULL]} ...
)

3
Example: Define (create) the following relation usinf SQL DDL

EMPLOYEE
FNAME MINIT LNAME SSN BDATE ADDRESS SEX SUPERSSN DNO

CREATE TABLE EMPLOYEE


(
Fname VARCHAR(15) NOT NULL,
Minit CHAR(1),
Lname VARCHAR(15) NOT NULL,
Ssn CHAR(9) PRIMARY KEY,
Bdate DATE,
Address VARCHAR(30),
Sex CHAR,
Salary DECIMAL(10,2),
Super_ssn CHAR(9),
Dno INT NOT NULL
);

Declarative Integrity Constraints

One of the most important features that a DBMS must provide is a way of maintaining the
integrity of data. The constraints, which are used to check the modification or insertion of
data, are called integrity constraints.

Using the DBMS to define integrity constraints increases the reliability of data because there
is no possibility that the integrity constraints can be forgotten by a programmer. (If an
integrity constraint is handled by application programs, all programs concerning the
constraint must include the corresponding code. If the code is omitted in one application
program, the consistency of data is compromised.)

An integrity constraint not handled by the DBMS must be defined in every application
program that uses the data involved in the constraint. In contrast, the same integrity constraint
must be defined only once if it is to be handled by the DBMS. If an integrity constraint is
handled by the DBMS, the modification of the structure of the constraint must be handled
only once, in the DBMS. The modification of a structure in application programs requires the
modification of every program that involves the corresponding code.

All declarative constraints can be categorized into several groups:

 DEFAULT clause
 UNIQUE clause
 PRIMARY KEY clause
 CHECK clause
 FOREIGN KEY clause and referential integrity

4
The DEFAULT and UNIQUE Clause

The DEFAULT clause in the column definition specifies the default value of the column -
that is, whenever a new row is inserted into the table, the default value for the particular
column will be used if there is no value specified for it.

Sometimes more than one column or group of columns of the table have unique values and
therefore can be used as the primary key. All columns or groups of columns that qualify to be
primary keys are called candidate keys. Each candidate key is defined using the UNIQUE
clause in the CREATE TABLE.

Example:
CREATE TABLE DEPARTMENT
(
Dname VARCHAR(15) UNIQUE,
Dnumber INT PRIMARY KEY,
Mgr_ssn CHAR(9) NOT NULL,
Mgr_start_date DATE DEFAULT ('01/01/2015')
);

The table can also be defined as:

CREATE TABLE DEPARTMENT


(
Dname VARCHAR(15) NOT NULL,
Dnumber INT NOT NULL,
Mgr_ssn CHAR(9) NOT NULL,
Mgr_start_date DATE DEFAULT ('01/01/2015'),
PRIMARY KEY (Dnumber),
UNIQUE (Dname)
);

Each value of the project_no column of the projects table is unique, including the NULL
value. If an existing value should be inserted into the column project_no, the system rejects
it. The explicit name of the constraint that is defined is unique_no.

The PRIMARY KEY Clause

The primary key of a table is a column or group of columns whose values are different in
every row. Each primary key is defined using the PRIMARY KEY clause in the CREATE
TABLE.

CREATE TABLE DEPARTMENT


(
Dname VARCHAR(15) UNIQUE,
Dnumber INT CONSTRAINT prim_dept PRIMARY KEY,
Mgr_ssn CHAR(9) NOT NULL,

5
Mgr_start_date DATE DEFAULT ('01/01/2015')
);

Here, the PRIMARY KEY clause belongs to the declaration of the corresponding column,
together with its data type and nullability. For this reason, it is called a column-level
constraint.

The primary key of the table is specified using the declarative integrity constraint named
prim_dept. This integrity constraint is a table-level constraint, because it is specified after
the definition of all columns of the employee table.

The CHECK Clause

The check constraint specifies conditions for the data inserted into a column. Each row
inserted into a table or each value updating the value of the column must meet these
conditions. The CHECK clause is used to specify check constraints. This clause can be
defined in the CREATE TABLE. The syntax of the CHECK clause is

CREATE TABLE EMPLOYEE


(
Fname VARCHAR(15) NOT NULL,
Minit CHAR,
Lname VARCHAR(15) NOT NULL,
Ssn CHAR(9) PRIMARY KEY,
Bdate DATE,
Address VARCHAR(30) DEFAULT ('Benghazi'),
Sex CHAR(1) CHECK (Sex IN ('M', 'F')),
Salary DECIMAL(10,2),
Super_ssn CHAR(9),
Dno INT NOT NULL,

);

The database system returns an error if the sex column, after a modification of its existing
values or after the insertion of a new row, would contain a value different from the values in
the set ('M', 'F') that is male or female.

The FOREIGN KEY Clause

A foreign key is a column or group of columns in one table that contains values that match
the primary key values in the same or another table. Each foreign key is defined using the
FOREIGN KEY clause combined with the REFERENCES clause. The FOREIGN KEY
clause has the following form:

6
CREATE TABLE DEPARTMENT
(
Dname VARCHAR(15) NOT NULL,
Dnumber INT NOT NULL,
Mgr_ssn CHAR(9) NOT NULL,
Mgr_start_date DATE,
PRIMARY KEY (Dnumber),
UNIQUE (Dname),
FOREIGN KEY (Mgr_ssn) REFERENCES EMPLOYEE(Ssn)
);

It can also be defined as:

CONSTRAINT foreign_dept FOREIGN KEY (Mgr_ssn) REFERENCES EMPLOYEE(Ssn)

The DEPARTMENT table is specified with two declarative integrity constraints. Both
constraints are table-level constraints, where the former specifies the primary key and the
latter the foreign key. Further, the constraint foreign_dept specifies the EMPLOYEE
table as the parent table and its Ssn column as the corresponding primary key of the column
with the same name in the DEPARTMENT table.

The FOREIGN KEY clause can be omitted if the foreign key is defined as a column-level
constraint, because the column being constrained is the implicit column “list” of the foreign
key, and the keyword REFERENCES is sufficient to indicate what kind of constraint this is.
A definition of the foreign keys in tables of a database imposes the specification of another
important integrity constraint: the referential integrity.

Referential Integrity

A referential integrity enforces insert and update rules for the tables with the foreign key and
the corresponding primary key constraint.

Possible Problems in Relation to Referential Integrity

There are four cases in which the modification of the values in the foreign key or in the
primary key can cause problems. All of these cases will be shown using the company
database. The first two cases affect modifications of the referencing table, while the last two
concern modifications of the parent table.

Case 1
Insert a new row into the Department table with the manager number (Mgr_ssn =
1111111). The insertion of the new row in the referencing table Department introduces a
new employee number for which there is no matching employee in the table (Employee). If
the referential integrity for both tables is specified as is done in, Database Engine rejects the
insertion of a new row.

7
Case 2
Modify the employee number 123456789 in all rows of the Department table. The new
number is 123459999. In Case 2, the existing value of the foreign key in the Department
table should be replaced using the new value, for which there is no matching value in the
parent table Employee. If the referential integrity for both tables is specified as is done in, the
database system rejects the modification of the rows in the Department table.

Case 3
Modify the employee number 123456789 in the corresponding row of the Employee table.
The new number is 112233445566. In Case 3, the existing value of the primary key in the
parent table and the foreign key of the referencing table is modified only in the other table.
The values in the referencing table are unchanged. Therefore, the system rejects the
modification of the row with the employee number 123456789 in the Employee table.
Referential integrity requires that no rows in the referencing table (the one with the
FOREIGN KEY clause) can exist unless a corresponding row in the parent table (the one
with the PRIMARY KEY clause) also exists. Otherwise, the rows in the parent table would
be “orphaned.” If the modification described above were permitted, then rows in the
Department table having the employee number 123456789 would be orphaned, and the
system would reject it.

Case 4
Delete the row of the Employee table with the employee number 123456789. Case 4 is
similar to Case 3. The deletion would remove the employee for which matching rows exist in
the referencing table. Database Engine can react differently if the values of the primary key
of a table should be modified or deleted. If you try to update values of a foreign key, and
those modifications result in inconsistencies in the corresponding primary key (see Case 1
and Case 2 in the previous sections), the database system will always reject the modification.

Modifying Database Objects

The Transact-SQL language supports changing the structure of the following database
objects, such as Database, Table, Stored procedure, etc.

Altering a Database

ALTER DATABASE company


ADD FILE (NAME= company_dat1,
FILENAME = 'C:\ company.mdf', SIZE = 10,
MAXSIZE = 100, FILEGROWTH = 5);

The ALTER DATABASE statement adds a new file with the logical name company_dat1.
Its initial size is 10MB, and this file will grow using units of 5MB until it reaches the upper
limit of 100MB. The REMOVE FILE clause removes one or more files that belong to an
existing database. The file can be a data file or a log file. The file cannot be removed unless it

8
is empty. Log files are added in the same way as database files. The only difference is that
you use the ADD LOG FILE clause instead of ADD FILE.

Altering a Table

The ALTER TABLE statement modifies the schema of a table. The Transact-SQL language
allows alterations such as add or drop one or more new columns, modify column properties,
add or remove integrity constraints, etc.

Adding or Dropping a New Column

ALTER TABLE Employee


ADD telephone_no CHAR(12) NULL;

The ALTER TABLE statement adds the column telephone_no to the Employee table.

ALTER TABLE Employee


DROP COLUMN telephone_no;

The ALTER TABLE statement removes the telephone_no column.

ALTER TABLE Department


ALTER COLUMN dname CHAR(25) NOT NULL;

The ALTER TABLE statement changes the previous properties (CHAR(30), nullable) of the
location column of the Department table to new properties (CHAR(25), not nullable).

ALTER TABLE Employee


ADD CONSTRAINT Sex_check CHECK (Sex IN ('M', 'F'));

ALTER TABLE statement defines an integrity constraint named Sex_check.

ALTER TABLE Employee


ADD CONSTRAINT PK_Employee PRIMARY KEY(ssn);

The ALTER TABLE statement declares the primary key for the Employee table.

Removing Database Objects

Some Transact-SQL statements can be used to remove a database objects. The statement
DROP DATABASE database1 { ...} removes one or more databases. This means that all
traces of the database are removed from your database system. One or more tables can be
removed from a database with the following statement:

9
DROP TABLE table_name1 {, ...}
All data belonging to the removed table are also dropped.

DROP TABLE Employee

10

You might also like