0% found this document useful (0 votes)
4 views

Basic SQL Server 2000 DDL and DML

database

Uploaded by

cherinet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Basic SQL Server 2000 DDL and DML

database

Uploaded by

cherinet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

SQL Server 2000 Lab Note

Database Laboratory Note (MS SQL Server 2000)


Creating a New Database using QA (query analyzer)
In MS-SQL server 2000 a database can be considered as a container to the objects
in a database. A database has tables views, queries constraints etc.
CREATE DATABASE <Name of Database>
ON
( NAME = <name for the database>
FILENAME = <Location>
SIZE = 10,
MAXSIZE = 50,
FILEGROWTH = 5 )
LOG ON
( NAME = < name of log file>
FILENAME = <location>
SIZE = 5MB,
MAXSIZE = 25MB,
FILEGROWTH = 5MB
)
The above database definition needs lots of information from the designer. If we
are interested to use the default size and location of the database, then we can
use the simple database definition as follows:
1. Simple Database definition
Syntax:
CREATE DATABASE <Name of Database>
Eg. CREATE DATABASE testgroup
If you execute the above statement on the query window you will see the
following message
The CREATE DATABASE process is allocating 0.63 MB on disk 'testgroup'.
The CREATE DATABASE process is allocating 0.49 MB on disk 'testgroup_log'.
This indicates that you have successfully created the database and that the
data file and the log file are having the specified size of memory. You are now
able to use the database.
2. Deleting a Database
DROP DATABASE <Database name>
Eg. DROP DATABASE testgroup

1
Prepared By: Wondwossen Mulugeta, Faculty of Informatics, AAU ([email protected])
SQL Server 2000 Lab Note

Creating tables in a database using QA(query analyzer)


Tables are one of the basic objects we have under a database. Tables are created
using the create table statement. It requires the following things

Name ⇒ The name of the table to be created


Field ⇒ The name of the columns to be created
Data type ⇒ The data type of the field to be created
Length ⇒ The size of the data type
Constraint ⇒ Rules that governs the table (it is optional)

Here the following characters are not allowed to be used for object naming.
(+,-,/,>,<,\,!,*,%,$,#,(,) , .,? white space etc)

Simple syntax

CREATE TABLE <Table name>


(
att1 datatype constraint,
att2 datatype constraint,
.
.
Attn datatype constraint
)
Constraint can be primary key, not null, unique, foreign key, etc. constraints are
optional. If you have you can use it if not you can leave the space empty.

The primary key constraint: is an entity constraint which is used to assign a


field as a key of that table. In the above syntax you van only assign a single field
as a primary key. If you have a composite key as a primary key see the section
constraints.
The not null constraint: is a constraint on a specific field and is used to enforce
that field not to be empty at the time of data entry. The default here is null (i.e.
you can enter a data for that field or you can leave it empty)
The unique constraint: is a constraint on a specific field which is used to make a
certain field.

2
Prepared By: Wondwossen Mulugeta, Faculty of Informatics, AAU ([email protected])
SQL Server 2000 Lab Note

Here is an example of creating a table without any constraint.


Eg.
CREATE TABLE teststudent
(
id_no char(12),
F_name char(20),
Lname char(20),
Sex char(6),
E_year int
)
The above table will be successfully executed. But the table will not be a valid
table in relational database system. It violates the primary key constraint thus we
need to add constraints. The detail syntax to create a table with its primary key
is.
3. Creating a Table with Primary Key Constraint

create table Department


(
DID char(5) primary key,
Name char(10) not null,
Loc char(10)
)

The above table (Department) will consider DID as a primary key and Name can
not take null and Loc has no constraints.

4. Creating a Table with more than one attribute as a Primary Key


create table Loan
(
MID char(3) not null,
CID char(3) not null,
BDate datetime not null,
DDate datetime,
Constraint Pk_Loan Primary Key (MID,CID,BDate)
)

The above table (Loan) will consider MID, CID and BDate together as a primary
key.

3
Prepared By: Wondwossen Mulugeta, Faculty of Informatics, AAU ([email protected])
SQL Server 2000 Lab Note

5. Creating a Table with Primary Key and Foreign Key


Primary key (candidate key) foreign key attributes are used to create relationship
between tables so that cross referencing can be used to retrieve interrelated
tuples from the tables.
The General syntax would be:
CREATE TABLE <Table name>
(
att1 datatype PRIMARY KEY,
att2 datatype constraint,
.
attn datatype constraint,
FOREIGN KEY (Atti) REFERENCES <home table(att)>
)
the last line can be changed to the following if we want to assigne a user defined
name for the constraint
Constraint ConstName foreign key (attribute) references hometable(attribute)
Eg:
Assuming that the Department and Employee table are related with each other
where the Department Id (DID) is primary key attribute posted in Employee
table as a foreign key with the name EDID. The coding method will be.
create table Department
(
DID char(5) primary key,
Name char(10) not null,
Loc char(10)
)

create table Employee


(
E ID char(5) primary key,
FName char(10) not null,
LName char(10) not null,
Salary money.
EDID char(5) foreign key references Department(DID)
)

4
Prepared By: Wondwossen Mulugeta, Faculty of Informatics, AAU ([email protected])
SQL Server 2000 Lab Note

or

create table Employee


(
E ID char(5) primary key,
FName char(10) not null,
LName char(10) not null,
Salary money.
EDID char(5),
foreign key (EDID) references Department(DID)
)
Or the above Employee table can be changed to

create table Employee


(
E ID char(5) primary key,
FName char(10) not null,
LName char(10) not null,
Salary money.
EDID char(5),
Constraint Fk_Emp foreign key (EDID) references Department(DID)
)

6. Altering a table to change data definition of the table


One can change the table definition after creating the table. The kind of
change might be:
¾ Adding a new attribute to an existing table
¾ Deleting and existing attribute from an existing table
¾ Changing the datatype and size of an existing attribute
¾ Adding more constraints to an existing attribute of a table like
not null.

create table Employee


(
E ID char(5) primary key,
FName char(10) not null,
LName char(10) not null,
Salary money
)
5
Prepared By: Wondwossen Mulugeta, Faculty of Informatics, AAU ([email protected])
SQL Server 2000 Lab Note

7. Add Column/Attribute to an existing table


Syntax:
ALTER TABLE <table name> ADD <column name> <data type> <constraint>
ƒ Adding DateOfBirth in Employee Table
ALTER TABLE Employee ADD DoB Datetime

After this instruction is executed, the employee table will have the
following schema.
EID FName LName Salary DoB

8. Delete a Column/Attribute from an existing table


Syntax:
ALTER TABLE <table name> DROP <column name>
ƒ Deleting Date of Birth (Dob) from Employee Table
ALTER TABLE Employee DROP COLUMN DoB
If an attribute (a column) have a constraint, we can not delete is by using the
above query, instead we have to first drop/delete the constraint on the
attribute (column). For example, to delete an attribute which is a Primary
Key, first the primary key constraint should be dropped before trying to
delete the table.

In the next table, the primary key are (MID,CID,BDate) with constraint name
Pk_Loan. Then, if we want to delete the MID attribute, we can not simply
drop it before lifting the constraint on it. Thus first the Pk_Loan should be
deleted and then MID can be deleted.

create table Loan


(
MID char(3) not null,
CID char(3) not null,
BDate datetime not null,
DDate datetime,
Constraint Pk_Loan Primary Key (MID,CID,BDate)
)
Thus:
Alter Table Loan Drop Constraint Pk_Loan
Alter Table Loan Drop Column MID

6
Prepared By: Wondwossen Mulugeta, Faculty of Informatics, AAU ([email protected])
SQL Server 2000 Lab Note

9. Change Definition of a Column/Attribute in a Table


Syntax:
ALTER TABLE <table name> ALTER COLUMN <column name> <New
data type> <New Size> <New Constraint>
Eg: to change the size of Name in the Department table above from 10 to 15 char
ALTER TABLE Employee ALTER COLUMN FName char(15) not null

10. Insert values for an Existing table


ƒ Inserting values to a table without codes
To inserting values to a table without codes, open the table in the Enterprise
Manager and insert a value in the column and move to the next using TAB
key.

ƒ Inserting values to a table using codes in Query Analyzer


Syntax:
INSERT INTO <Table name> VALUES (values separated by a comma)
In the insert into command, the number of values in the curve bracket ‘( )’
should match with the number of attributes of the target table. In addition,
character data values should be embraced within single quote ‘ ‘.

ƒ Inserting one tuple in Employee table


Eg: INSERT INTO Employee VALUES ('E01','Abebe',’Taye’, 1250)

For multiple tuple insertion, one has to repeatedly execute the above code
with different values.
11. Add Constraint to an existing table
After a table is created one can add constraints or delete constraints to the
existing table. Constraints might be: Primary Key, Foreign Key, Null, Check,
etc.
The general syntax would be:
ALTER TABLE <table name> ADD CONSTRAINT <constraint name> <constraint>

a) Add Primary Key Constraint


Syntax:
ALTER TABLE <table name> ADD CONSTRAINT <constraint name>
Primary Key <(attribute name)>
E.g.:
ALTER TABLE Employee ADD CONSTRAINT PK_SupID Primary Key (EID)

7
Prepared By: Wondwossen Mulugeta, Faculty of Informatics, AAU ([email protected])
SQL Server 2000 Lab Note

b) Add Foreign Key Constraint


Syntax:
ALTER TABLE <table name> ADD CONSTRAINT <constraint name>
Foreign Key <attribute name> references <table name><attribute name>
Eg:
ALTER TABLE Employee ADD CONSTRAINT FK_DID Foreign Key (DID)
References Department(DID)

12. Viewing the content of a table


The SELECT statement is used to display the content or part of a table
in a table form.
Most commonly used parts of the SELECT statement is the following:

SELECT <field list> FROM <tables>


WHERE <condition>
GROUP BY <field>
HAVING <aggregate condition>

¾ Simple select statement


SELECT * FROM Employee
where the asterisk ( * ) means all the attributes from employee table.

SELECT EID,FName,Slary FROM Employee


Contains only the three attributes from employee table in the result.

SELECT * FROM Employee


WHERE Salary>1000
Displays, tuples from the Employee table whose value for the salary
attribute is greater than 1000

To display attributes from more than one table


SELECT * FROM Employee, Department
WHERE Employee.EDID=Department.DID
The condition of selection is the equality between primary key and
foreign key attributes from the two related tables. But instead of
using the long able name in the condition, we can represent the table
names by a variable which is called alias.

8
Prepared By: Wondwossen Mulugeta, Faculty of Informatics, AAU ([email protected])
SQL Server 2000 Lab Note

Thus the above SQL command will be:


SELECT * FROM Employee E , DepartmentD
WHERE E .EDID=D. DID
Or, if we want to select only some of the attributes from the two
tables.
SELECT E.EID,E.FName,E.Lname,D.NameFROM Employee E , Department D
WHERE E .EDID=D. DID

In the select statement inbuilt functions like count (COUNT), maximum (MAX),
minimum (MIN), average (AVG), total (SUM), etc can be used, where in such
cases the group by phrase will be used.
To displays the maximum salary from each department
SELECT DID, MAX(salary) FROM Employee
GROUP BY EDID

To displays the average salary from each department


SELECT DID, AVG(salary) FROM Employee
GROUP BY EDID
To count the number of employees in each department
SELECT DID, MAX(EID) FROM Employee
GROUP BY EDID
For the new attribute created, we can give new attribute name using alias
method.
SELECT DID, AVG(salary) AS Avg_Salary FROM Employee
GROUP BY EDID

We can also sort the result using one of the attributes in the result using the
ORDER BY clause.
SELECT * FROM Employee
WHERE Salary>1000
ORDER BY FName

13. Deleting tuples from a table


To delete the whole content of a tuple from an existing table we will use the DELETE
command.
General synax:
DELETE <TableName> WHERE <Condition>

To delete and employee with first name ‘abebe’


DELETE employee WHERE FName='Abebe'
9
Prepared By: Wondwossen Mulugeta, Faculty of Informatics, AAU ([email protected])
SQL Server 2000 Lab Note

To delete an employee with employee id ‘e05’


DELETE employee WHERE EID='e05'

If we use the delete statement without the where clause (without the
condition), all tuples of the table will be deleted and we will have an empty
table.
DELETE employee

The above command will delete all the tuples in the employee table but NOT
the table.

14. Modifying attribute values of a tuple


To modify or update attribute values of tuples in an existing table we will use the
UPDATE command.
General synax:
UPDATE <TableName>
SET <AtrributeName=value>
WHERE <Condition>

To increase the salary of all employees by 5%


UPDATE Employee
SET Salary=Salary*1.05

To increase the salary of only one employee with id ‘e06’ by 15%


UPDATE Employee
SET Salary=Salary*1.05
WHERE EID=’e06’

To increase the salary of all employees earning a slary less than 1000 by 25%
UPDATE Employee
SET Salary=Salary*1.25
WHERE salary<1000

15. Creating a view or virtual table


In SQL, a VIEW is a virtual table based on the result-set of a SELECT
statement.
A view contains rows and columns, just like a real table. The fields in a view
are fields from one or more real tables in the database. You can add SQL
functions, WHERE, and JOIN statements to a view and present the data as if
the data were coming from a single table.
Note: The database design and structure will NOT be affected by the
functions, where, or join statements in a view.
10
Prepared By: Wondwossen Mulugeta, Faculty of Informatics, AAU ([email protected])
SQL Server 2000 Lab Note

General Syntax
CREATE VIEW <View_Name> AS
SELECT <attribute List>
FROM <Table_Name>
WHERE <Condition>

Note: The database does not store the view data! The database engine
recreates the data, using the view's SELECT statement, every time a user
queries a view.

To create a virtual table or a view which will display the list of employees
whose salary is greater than 100, the view will be:
CREATE VIEW Emp_Sal_1000 AS
SELECT *
FROM Employee

After this query is executed, we can run the following query, as it acts just
like a normal table in the database.
SELECT * FROM Emp_Sal_1000

To create a view that contains the average salary of employees in each


department.
CREATE VIEW Avg_Salary_Dept AS
SELECT DID, AVG(salary) FROM Employee
GROUP BY EDID

Generally, any select statement can be used to from a view, where then after
the view can be used as a normal table. A view can also be used in other
queries as a normal table.

11
Prepared By: Wondwossen Mulugeta, Faculty of Informatics, AAU ([email protected])
SQL Server 2000 Lab Note

16. Joining tables


Joining tables is similar with combining tables using the select statement where
in the condition we use equality between primary key attributes and foreign key
attributes. When it comes to JOIN, we will use the clause JOIN with different
variety of joins like INNER, RIGHT OUTER, LEFT OUTER, etc. in addition all
the issues we have seen fro select statement and create view can be implemented
using the join query. One can use join in normal select statement. One can also
use join in creating a view.
The General Syntax:
SELECT <attribute List>
FROM <table1> [ JOIN TYPE ] <table2>
ON <Join condition>
WHERE <additional Condition>

There are different types of join.


1. Inner Join
Joins the tables using equality between the attributes of primary key
and foreign key columns where only tuples participating on the
relationship are included in the result.
SELECT <attribute List>
FROM <table1> INNER JOIN <table2>
ON <Join condition>
WHERE <additional Condition>
2. Left Join
Joins the tables using equality between the attributes of primary key
and foreign key columns and also includes tuples from the table in
the left in the result even if they don’t participate in the relationship.
For attributes from the table in the right side the value ‘null’ will be
field for those tuples from the left side not participating in the
relationship.
SELECT <attribute List>
FROM <table1> LEFT JOIN <table2>
ON <Join condition>
WHERE <additional Condition>

12
Prepared By: Wondwossen Mulugeta, Faculty of Informatics, AAU ([email protected])
SQL Server 2000 Lab Note

3. Right Join
Joins the tables using equality between the attributes of primary key
and foreign key columns and also includes tuples from the table in
the right side in the result even if they don’t participate in the
relationship. For attributes from the table in the left side the value
‘null’ will be field for those tuples from the right side not
participating in the relationship.
SELECT <attribute List>
FROM <table1> RIGHT JOIN <table2>
ON <Join condition>
WHERE <additional Condition>

4. Full Join
Joins the tables using equality between the attributes of primary key
and foreign key columns and also includes tuples from both tables
in the result even if they don’t participate in the relationship. For
attributes from the table in the left side the value ‘null’ will be field
for those tuples from the table in the right side not participating in
the relationship. And For attributes from the table in the right side
the value ‘null’ will be field for those tuples from the table in the left
side not participating in the relationship.

SELECT <attribute List>


FROM <table1> FULL JOIN <table2>
ON <Join condition>
WHERE <additional Condition>

13
Prepared By: Wondwossen Mulugeta, Faculty of Informatics, AAU ([email protected])
SQL Server 2000 Lab Note

Sample tables and Examples to elestrate the join types.


EMPLOYEE
EID FName LName Salary EDID
e01 Abebe Taye 1500.0000 d01
e02 bekele mamo 230.0000 d03
e03 Almaz mitiku 700.0000 d02
E04 hirut seleshi 350.0000 d01
E05 mammo mesfin 875.0000 d03
E06 mahlet takele 1250.0000 NULL
E07 belay Kebede 1100.0000 NULL

DEPARTMENT
DID DName DLoc
D01 Finanace B05
D02 Personnel B04
D03 sales B03
D04 Project B07
D05 Mang B01

¾ Inner Join
SELECT * FROM
employee INNER JOIN department
ON employee.edid=department.did
Or using the alias method

SELECT * FROM
employee E INNER JOIN department D
ON E.edid=D.did

The above two SQL queries will produce the following table

EID FName LName Salary EDID DID DName DLoc


e01 Abebe Taye 1500.0000 d01 d01 Finanace B05
e02 Bekele mamo 230.0000 d03 d03 Sales B03
e03 Almaz mitiku 700.0000 d02 d02 Personnel B04
e04 hirut seleshi 350.0000 d01 d01 Finanace B05
e05 mammo mesfin 875.0000 d03 d03 Sales B03

14
Prepared By: Wondwossen Mulugeta, Faculty of Informatics, AAU ([email protected])
SQL Server 2000 Lab Note

¾ Left Join (Left Outer Join)


SELECT * FROM
employee LEFT JOIN department
ON employee.edid=department.did

SELECT * FROM
employee LEFT OUTER JOIN department
ON employee.edid=department.did

Or using the alias method

SELECT * FROM
employee E LEFT JOIN department D
ON E.edid=D.did

SELECT * FROM
employee E LEFT OUTER JOIN department D
ON E.edid=D.did

The above four SQL queries will produce the following table

EID FName LName Salary EDID DID DName DLoc


e01 Abebe Taye 1500.00 d01 d01 Finanace B05
e02 bekele mamo 230.00 d03 d03 sales B03
e03 Almaz mitiku 700.00 d02 d02 Personnel B04
e04 hirut seleshi 350.00 d01 d01 Finanace B05
e05 mammo mesfin 875.00 d03 d03 sales B03
e06 mahlet takele 1250.00 NULL NULL NULL NULL
e07 belay Kebede 1100.00 NULL NULL NULL NULL

15
Prepared By: Wondwossen Mulugeta, Faculty of Informatics, AAU ([email protected])
SQL Server 2000 Lab Note

¾ Right Join (Right Outer Join)


SELECT * FROM
employee RIGHT JOIN department
ON employee.edid=department.did

SELECT * FROM
employee RIGHT OUTER JOIN department
ON employee.edid=department.did

Or using the alias method

SELECT * FROM
employee E RIGHT JOIN department D
ON E.edid=D.did

SELECT * FROM
employee E RIGHT OUTER JOIN department D
ON E.edid=D.did

The above four SQL queries will produce the following table
EID FName LName Salary EDID DID DName DLoc
e01 Abebe Taye 1500.0000 d01 d01 Finanace B05
e04 hirut seleshi 350.0000 d01 d01 Finanace B05
e03 Almaz mitiku 700.0000 d02 d02 Personnel B04
e02 bekele mamo 230.0000 d03 d03 sales B03
e05 mammo mesfin 875.0000 d03 d03 sales B03
NULL NULL NULL NULL NULL d04 Project B07
NULL NULL NULL NULL NULL d05 Mang B01

16
Prepared By: Wondwossen Mulugeta, Faculty of Informatics, AAU ([email protected])
SQL Server 2000 Lab Note

¾ Full Join (Full Outer Join)


SELECT * FROM
employee FULL JOIN department
ON employee.edid=department.did

SELECT * FROM
employee FULL OUTER JOIN department
ON employee.edid=department.did

Or using the alias method

SELECT * FROM
employee E FULL JOIN department D
ON E.edid=D.did

SELECT * FROM
employee E FULL OUTER JOIN department D
ON E.edid=D.did

The above four SQL queries will produce the following table
EID FName LName Salary EDID DID DName DLoc
e06 mahlet takele 1250.0000 NULL NULL NULL NULL
e07 belay Kebede 1100.0000 NULL NULL NULL NULL
e01 Abebe Taye 1500.0000 d01 d01 Finanace B05
e04 hirut seleshi 350.0000 d01 d01 Finanace B05
e03 Almaz mitiku 700.0000 d02 d02 Personnel B04
e02 bekele mamo 230.0000 d03 d03 sales B03
e05 mammo mesfin 875.0000 d03 d03 sales B03
NULL NULL NULL NULL NULL d04 Project B07
NULL NULL NULL NULL NULL d05 Mang B01

17
Prepared By: Wondwossen Mulugeta, Faculty of Informatics, AAU ([email protected])

You might also like