Вы находитесь на странице: 1из 20

3.

1 Introduction Relational Data Base Management System


(RDBMS) & Structured Query Language (SQL )
3.1.1 Relational Database Management System (RDBMS)

A Data Base Management System that is based on a relational model is called as RDBMS.
Relational model is the most successfully used Data Base Management System Model
(DBMS) model.

Relational model represents data in the form of a table. A table is a two dimensional array
which contains rows and columns.

Consider a scenario of a college where we need to maintain huge amount of student details.
All these student details are stored in a table as mentioned in Figure 3.1.

In Figure 3.1, (as discussed in Section 2 ER model) students is the entity and Name is one of
the attributes of this students entity. Other attributes are RollNo and Phone. The table given
below contains rows and columns. Each row contains data related to an entity/students.
Each column contains the data related to an attribute.

Figure 3.1 : Student Table

Figure 3.1 shows the data represented in relational model and the
terms that are used to refer to various components of a table. The terms mentioned
below are used in relational model.
Tuple / Row

A single row that is available in the table is called as tuple. Each row in the table represents
the data of a single entity. For example, in Figure 3.1 s1, Louis Figo, 454333 represents a
row.

Attribute / Column

A column in the table stores an attribute of the entity. For example, in Students table
(Figure 3.1) Louis Figo, Rahul, etc. are the attributes as highlighted in figure.

Column Name

Each column that is available in the table is given a name. This name is used to refer to
values in the column. In Students table (Figure 3.1), RollNo, Name and Phone are the
column names of the table.

Table Name

Each table is provided with a name. The name that is provided is used to refer to the table.
The name of the table depicts the contents of the table. In the above Figure 3.1, Students is
the name of the table.
3.1.2 Structured Query Language (SQL)

Relational database management systems ( RDBMS) use SQL (Structured Query Language)
for data manipulation and retrieval. SQL is the standard language for relational database
systems. It is a non-procedural language.

Non-procedural language requires the programmer to specify what the program should do,
rather than providing the sequential steps indicating how the program should perform a
task.

SQL Commands are divided into three categories, depending upon what they do:

 DDL (Data Definition Language)

 DML (Data Manipulation Language)

 DCL (Data Control Language)

3.2 Introduction to Data Definition Language(DDL)

Data Definition Language ( DDL) statements are used to create and modify the structure of
your tables and any other objects in the database. Some of the DDL commands are CREATE,
ALTER and DROP.
3.2.1 CREATE statement
A CREATE statement in SQL is used to create a table.

The general syntax of the CREATE statement is given below:

Syntax:

CREATE TABLE table_name

( column_name1 data_type constraints,

column_name2 data_type constraints,

...

column_nameN data_type constraints,

);

where,

table_name - is the name of the table

column_name1, column_name2,.... ,column_nameN- is the name of the columns

data_type - is the data type for the column like char, date, number etc.

constraints - constraints are used to validate or limit the type of data that can go into a

table.

Constraints are optional for the columns.

We will focus on a few constraints now:

 NOT NULL

 PRIMARY KEY

 FOREIGN KEY

 UNIQUE

NOT NULL: The NOT NULL constraint enforces a column to not accept NULL values. This
means that this column must contain some value while inserting or updating a record.

PRIMARY KEY: Primary key uniquely identifies each record in the database. So a primary key
column cannot contain NULL values.(Refer Section 2 for more details about Primary Key).

FOREIGN KEY: A foreign key is a column in a table that matches the primary key column of
another table. The foreign key can be used to map two tables. (Refer Section 2 for more
details about Foreign Key).

UNIQUE: Unique constraints are used to make sure that no duplicate values are entered in
specific columns that do not participate in a primary key. A column defined as UNIQUE can
contain NULL values.
Basic SQL DATA types :

I. CHAR: The CHAR data type is used for storing fixed length character strings with a
maximum size of 2000 bytes. The CHAR(n) holds fixed length of n characters.

II. DATE: It allows to define the Date attributes as Date fields in the database. Here the
DATE data type stores year, month, and day values.

III. NUMBER: It allows to define a column as number field. Only number values can be
stored in the database.

Now let's see how to implement the SQL queries with examples:

Example1:

With the help of CREATE statement, let's create Students table with columns as RollNo,
Name and Phone as shown below.

CREATE TABLE Students (

RollNo NUMBER PRIMARY KEY,

Name CHAR(25) NOT NULL,

Phone NUMBER

);

Here "Students" is the name of the table. RollNo, Name and Phone are the columns of the
table. NUMBER and CHAR(25) are the data types which convey what kind of data that
particular column will hold.

Here RollNo is given as PRIMARY KEY which means that this particular column will not
accept any duplicate values. The other two columns are defined as NOT NULL which conveys
that these two columns will not accept NULL values.

Note: NULL specifies that the column doesn't have any value or the column is empty.

Example2:

Let's see another example using the Create Statement.

The query below is used to create "employees" table with columns such as employee_id,
first_name, etc.

CREATE TABLE employees (

employee_id NUMBER PRIMARY KEY,


first_name CHAR(10) NULL,

last_name CHAR(10) NOT NULL,

email CHAR(25) NOT NULL,

phone_number NUMBER NOT NULL,

hire_date DATE NOT NULL,

job_id CHAR(10),

salary NUMBER,

commission_pct NUMBER,

manager_id NUMBER,

department_id NUMBER

);

Example3:

In Example1 and Example2 we explained how to create primary key and NOT NULL
constrains. Now let's see how to implement foreign key constraints. To implement foreign
key we need two tables that are dependent on each other.

In Example 2 we have employees table which contains the department_id as one of the
columns but does not have department details. Now let's create a department table which
contains details of the department such as department_id and department name.

CREATE TABLE department(

department_id NUMBER PRIMARY KEY,

department_name CHAR(10)

);
Consider a scenario where we need to identify the department_name of an employee. In
this case the employees table is dependent on department table to get the department
name based on the common column department_id. Foreign key constraint comes into
picture in this case. The syntax below creates foreign key. (For more details about Foreign
key refer Section 2).

CREATE TABLE employees (

employee_id NUMBER PRIMARY KEY,

first_name CHAR(10) NULL,

last_name CHAR(10) NOT NULL,

email CHAR(25) NOT NULL,

phone_number NUMBER NOT NULL,

hire_date DATE NOT NULL,

job_id CHAR(10),

salary NUMBER,

commission_pct NUMBER,

manager_id NUMBER,

department_id NUMBER FOREIGN KEY REFERENCES


department(department_id )

);

3.2.2 DROP statement

The DROP command is used to remove a table from the database . If you drop a table, all
the rows in the table are deleted and the table structure is removed from the database
permanently. Once a table is dropped using DROP command , we cannot retrieve the data /
table back. So we should be careful while using this command.

Syntax:

DROP TABLE table_name;


Example1:

The following command is used to permanently remove the Students table


structure/definition along with the data that was created.

DROP TABLE Students;

After execution of the above command the entire Students table is removed from the
database. We cannot get back any data about Students table.

Example2:

Let's see how the employees table definition/structure is removed from the database.

DROP TABLE employees;

After execution of the above command the entire employees table is removed from the
database. We cannot get back any data about employees table.
3.2.3 ALTER statement

The ALTER statement helps to modify the structure of an existing table in the database.

Once you've created a table within a database, you may wish to modify it's definition at
some instance. ALTER statement allows you to make changes to the structure of a table
without deleting or recreating it.

General syntax of Alter statement is given below.

Syntax for adding a column to the existing table:

ALTER TABLE table_name ADD column_name data_type;

Example:

Let's see how we can alter or edit the structure of the Students table that we created using
CREATE statement in Section 3.2.1 using SQL queries. Let's assume that we have to add a
new column called 'gender' to the existing Students table .

ALTER TABLE Students ADD gender CHAR(10);

In the above example the "gender" column with the data type as CHAR(10) has been added
to the existing Students table.

Syntax for adding constraints:

ALTER TABLE table_name ADD CONSTRAINT clause ;


where: A CONSTRAINT clause is optional in the above ALTER TABLE statement for defining
the constraint.

Example:

In the example below Unique constraint is applied to Phone column in order to avoid
duplicate phone numbers getting inserted into the table.

ALTER TABLE employees ADD UNIQUE Phone;

The constraint UNIQUE has been added on column Phone of employees table to show
unique data.

3.3 Introduction to Data Manipulation Language (DML)

Data manipulation language (DML) is a family of computer language that includes


commands which permit users to manipulate data in a database. This manipulation involves
inserting data into database tables, retrieving existing data, deleting data from existing
tables and modifying existing data.

DML commands:

 INSERT - To add a new row into a table

 UPDATE - To update existing records within a table

 DELETE - To delete records in a table

 SELECT - To retrieve records from a table


3.3.1 INSERT Statement

The INSERT statement inserts new rows into an existing table.

The syntax for INSERT statement is as follows.

Syntax:

INSERT INTO table_name (col1,col2,col3,....)

VALUES (vallue1,value2,value3,.....);

Example 1:

Now let's see how to insert the details of students into Students table. The following is the
structure of the Students table. Let's see how to insert the details of a student named David.
Name Null? Type
RollNo NOT NULL NUMBER
Name NOT NULL CHAR(25)
Phone NUMBER
Gender CHAR(10)
Table 3.1

In the query given below RollNo, Name, Phone and Gender are the columns defined in the
Students table. Using INSERT statement the corresponding values 100, David, 9830028200,
Male are inserted into those columns.

INSERT INTO Students(RollNo, Name, Phone, Gender)

VALUES (100,'David',9830028200,'Male');

Similarly, we can insert details of another student named 'Peter'. Let's try to ignore a
column which accepts NULL value during insertion.

INSERT INTO Students(RollNo, Name, Gender) VALUES (200,'Peter','Male');

In the above query we have given values only for three columns (RollNo, Name, Gender).
Though we didn't mention Phone, the record will be successfully inserted because it is not
mandatory to provide values for the columns which can accept NULL values during
insertion. In Students table Phone and Gender are the columns which can accept NULL
values. For Peter's record Phone column will be empty.

The data we inserted is represented in the table below:


RollNo Name Phone Gender
100 David 9830028200 Male
200 Peter Male
Table 3.2

In the query given below RollNo, Name, Phone and Gender are the columns defined in the
Students table. Using INSERT statement the corresponding values 100, David, 9830028200,
Male are inserted into those columns.

INSERT INTO Students(RollNo, Name, Phone, Gender)

VALUES (100,'David',9830028200,'Male');

Similarly, we can insert details of another student named 'Peter'. Let's try to ignore a
column which accepts NULL value during insertion.

INSERT INTO Students(RollNo, Name, Gender) VALUES (200,'Peter','Male');


In the above query we have given values only for three columns (RollNo, Name, Gender).
Though we didn't mention Phone, the record will be successfully inserted because it is not
mandatory to provide values for the columns which can accept NULL values during
insertion. In Students table Phone and Gender are the columns which can accept NULL
values. For Peter's record Phone column will be empty.

The data we inserted is represented in the table below:


RollNo Name Phone Gender
100 David 9830028200 Male
200 Peter Male
Table 3.2

Example 2:

Let us assume employees table structure as below:


Name Null? Type
Employee_Id NOT NULL NUMBER
First_Name CHAR(10)
Last_Name NOT NULL CHAR(10)
Email NOT NULL CHAR(25)
Phone_Number NOT NULL NUMBER
Hire_Date NOT NULL DATE
Job_ID NOT NULL CHAR(10)
Salary NUMBER
Commission_PCT NUMBER
Manager_ID NUMBER
Age NUMBER
Department_ID NUMBER
Table 3.3

Query:

INSERT INTO employees (First_Name,Last_Name,Email,Phone_Number,

Hire_Date,Job_ID,Salary,Commission_PCT,Manager_ID,Age,Department_ID)

VALUES ('George', 'Gordon','GGORDON',6505062222,

'01-JAN-07','SA_REP',9000,.1,148,25,80);

Result:

ERROR at line 1:
ORA-01400: cannot insert NULL into
("E668292"."EMPLOYEES"."EMPLOYEE_ID")

In the above query we are trying to insert the details of an employee without providing
value for Employee_ID column. Employee_ID column is a NOT NULL column. So it is
mandatory to provide value for the same. Since we tried to insert some data excluding the
NOT NULL column value, the execution of the query gives an error. Since we didn't give any
value for the Employee_ID column the value that will get into the table would be NULL. So it
has thrown as error as "cannot insert NULL into EMPLOLYEE_ID column".

Let's now insert a row by providing Employee_ID column value.

INSERT INTO employees

(Employee_ID,First_Name,Last_Name,Email,Phone_Number,

Hire_Date,Job_ID,Salary,Commission_PCT,Manager_ID,Age,Department_ID)

VALUES (10,'George', 'Gordon','GGORDON',6505062222,

'01-JAN-07','SA_REP',9000,.1,148,25,80);

Inserting another employee:

INSERT INTO employees

(Employee_ID,First_Name,Last_Name,Email,Phone_Number,

Hire_Date,Job_ID,Salary,Commission_PCT,Manager_ID,Age,Department_ID)

VALUES (11,'James', 'Keats','j_keats@gm',6505062221,

'01-JAN-07','SA_REP',7000,.1,148,25,80);

The inserted data is represented in table format below:


Employe First_N Last_N Phone_Nu Hire_D Job_ Sala Commissio Manage Ag Departme
Email
e_Id ame ame mber ate ID ry n_PCT r_ID e nt_ID
GGordo 65050622 01/01/ SA_R 900
10 George Gordon 5 148 25 80
n 22 07 EP 0
j_keats
65050622 01/01/ SA_R 700
11 James Keats @gmail. 5 148 25 80
21 07 EP 0
com
Table 3.4
3.3.2 SELECT Statement
Select statement is used to retrieve the data from the database table.

General syntax of the Select statement is given below:

Syntax:

SELECT column_list FROM table_name WHERE search_condition

where

 column_list includes one or more columns from which data is retrieved.

 table_name is the name of the table from which the information is retrieved.

 search_condition specifies the conditions based on which rows will be retrieved.

The three clauses used in the SELECT statement:


Clause Description
Describes the columns that will be included in the
SELECT
result set.
Names the table from which the query will retrieve
FROM
the data.
Specifies the conditions that must be met for a row
WHERE to be included in the result set. This clause is
optional.
Table 3.5

Example 1:

If we want to view the details of all students after inserting the values in the Students table,
the query below can be executed.

SELECT * FROM Students;

Result:
RollNo Name Phone Gender
100 David 9830093024 Male
200 Peter Male
Table 3.6
Here * denotes all the columns and rows of the table.

Example 2:

Let's assume that we want to select a row from Students table whose roll no is 200.

To retrieve this the following query is executed.

SELECT name FROM Students WHERE RollNo=200;

Result:
Name
Peter
Table 3.7

Example 3:

Now let's consider a scenario where we need to retrieve the Salary from employees table
whose first name is George. The query for the scenario will be as follows:

SELECT Salary FROM employees WHERE first_name= 'George' ;

There are chances that there are more than one employees with first name as George. The
above query will retrieve all the employees whose first name is George. But if we need only
one specific employee whose first name is George then we can add one more condition in
WHERE clause which will help in retrieving the exact required data.

SELECT Salary FROM employees

WHERE first_name= 'George' AND employee_id= 10 ;

Result:
Salary
9000
Table 3.8
In the above query we have added two conditions with the help of the "AND" key word.
AND checks for both the conditions and will retrieve the record which matches both. So
salary of the employee(i.e George as shown in result) is retrieved from the employees table
whose FIRST_NAME is "George" and EMPLOYEE_ID is equal to 10.

So far we saw how to retrieve data from one table. Now let's see how to retrieve data from
more than one table.

To retrieve or combine data from more than one table we use Joins.

Joins:

Join command is used to combine records from two or more tables in a database. Join
command creates a set that can be saved as a table or used as it is.

A Join is a means of combining fields from two tables by using values common to each
other.

A Join condition can be used in the WHERE clause of SELECT, UPDATE, DELETE statements.
(Refer Section 2 in this document for more details)

The following is the syntax for joining two tables:

SELECT col1, col2, col3... FROM table_name1, table_name2

WHERE table_name1.col2 = table_name2.col1;

Example:

Let's assume that Department table has the following data.


Department_ID Department_Name
80 Sales
Table 3.9

The employees table has the following data:


Employ First Last Commissi Manag Departme
Phone Hire Job_I Salar Ag
ee _Nam _Nam Email on er nt
_Number _Date D y e
_Id e e _PCT _ID _ID
Georg Gordo 65050622 01/01/ SA_RE
10 GGordon 9000 5 148 25 80
e n 22 07 P
j_keats
65050622 01/01/ SA_RE
11 James Keats @gmail.co 7000 5 148 25 80
21 07 P
m
Table 3.10
The column that is common between the two tables is Department_ID. So using
Department_ID we can join Department table and employees table. Please find below query
for the same.

SELECT employee_Id, first_name,department_name,department_id

FROM department,employees

WHERE department.department _id = employees.department_id;

Result:
Employee_Id First_Name Department_Name Department_ID
10 George Sales 80
11 James Sales 80
Table 3.11

Here data from employees table and department table are joined and displayed.

Department_Id from department table is compared with Department_Id from employees


table and the records that have same value for Department_ Id(i,e. 80) have been displayed.
3.3.3 UPDATE Statement

Let' see how to modify the existing rows in a table.

In Section 3.3.1 we saw how to insert the records into a table. Here we will see how to
update the inserted records.

The UPDATE statement modifies the set of existing table rows.

General syntax for the UPDATE statement is given below.

Syntax:

UPDATE table_name

SET (column_name1 = value,column_name2=value,..)

WHERE condition;

Note: The WHERE clause in the above syntax specifies which record or records should be
updated. All records will be updated, if we omit the WHERE clause in UPDATE statement.

Let's see a few examples for the UPDATE statement.


Example 1:

RollNo Name Phone Gender


100 David 9830093024 Male
200 Peter Male
Table 3.12

Let's update the Name "David" in the students tables to "John".

We use the below query for the same.

UPDATE students SET name = 'John' WHERE rollno = 100;

Result:

1 row updated.

Students table will look like this now:


RollNo Name Phone Gender
100 John 9830093024 Male
200 Peter Male
Table 3.13

Example 2:

employees table has the following data:


Employ First Last Commissi Manag Departme
Phone Hire Job_I Salar Ag
ee _Nam _Nam Email on er nt
_Number _Date D y e
_Id e e _PCT _ID _ID
Georg Gordo 65050622 01/01/ SA_RE
10 GGordon 9000 5 148 25 80
e n 22 07 P
j_keats
65050622 01/01/ SA_RE
11 James Keats @gmail.co 7000 5 148 25 80
21 07 P
m
Table 3.14

Now we want to update the salary of the employee whose manager_ID is 148.

We use the below query for the same.

UPDATE employees SET salary = 10500 WHERE manager_id = 148;


Result:

2 rows updated.

In the above query employees table is updated with the salary value 10500 for the rows
which have the manager_id as 148.

There were two rows which had manager_id as 148 and they have been updated with salary
value as 10500 from 9000 and 7000 respectively.

employees table will look like this now:


Employ First Last Commissi Manag Departme
Phone Hire Job_I Salar Ag
ee _Nam _Nam Email on er nt
_Number _Date D y e
_Id e e _PCT _ID _ID
Georg Gordo 65050622 01/01/ SA_RE 1050
10 GGordon 5 148 25 80
e n 22 07 P 0
j_keats
65050622 01/01/ SA_RE 1050
11 James Keats @gmail.co 5 148 25 80
21 07 P 0
m
Table 3.15
3.3.4 DELETE Statement

The DELETE statement is used to delete the rows from a table.

The DELETE statement syntax is given below.

Syntax:

DELETE FROM table_name WHERE condition ;

If we include the WHERE clause, the statement deletes only those records that satisfy the
condition. If we omit the WHERE clause, the statement deletes all records from the table,
but the table still exists without records.

Example 1:

Students table has the data as shown below:


RollNo Name Phone Gender
100 John 9830093024 Male
200 Peter Male
Table 3.16

If we want to delete a row from the above table whose RollNo is 100, we use the below
query.

DELETE FROM Students WHERE ROLLNO = 100;


Result:

1 row deleted.

After deleting the record, Students table will look like this:
RollNo Name Phone Gender
200 Peter Male
Table 3.17

Example 2:

employees table has the following data:


Employ First Last Commissi Manag Departme
Phone Hire Job_I Salar Ag
ee _Nam _Nam Email on er nt
_Number _Date D y e
_Id e e _PCT _ID _ID
Georg Gordo 65050622 01/01/ SA_RE 1050
10 GGordon 5 148 25 80
e n 22 07 P 0
j_keats
65050622 01/01/ SA_RE 1050
11 James Keats @gmail.co 5 148 25 80
21 07 P 0
m
Table 3.18

Now let's delete the employee details whose hire date is 1st Jan 07.

DELETE FROM employees WHERE hire_date = '01-JAN-07';

Result:

2 rows deleted.

Two rows which have the Hire_Date value as '01-JAN-07' have been deleted from
employees table (Refer Example 2 of Sec3.2.1).

Note : The DELETE statement is different from the DROP statement. The DELETE statement
deletes some (or all) data from the table but the table exists in the data base. The DROP
statement removes the table permanently from the data base.
3.4 Introduction to DCL(Data Control Language)

The Data Control Language (DCL) component of the SQL language and it is used to provide
privileges to the users to access or to manipulate the database. The following are two main
commands:

 GRANT - This command is used to grant privileges to a user.

 REVOKE - This command is used to revoke (remove) privileges from a user.


3.4.1 GRANT command
In order to do anything within a database you must be given the appropriate privileges.
Database operates in a closed system where you cannot perform any action at all unless you
have been authorized to do so. This includes logging onto the database, creating tables,
manipulating data (ie select, insert, update and delete) in tables created by other users, etc.

Syntax:

GRANT privilege_name ON table_name TO user_name;

Where,

privilege_name is the access right or privilege granted to the user.

table_name is the name of the table in the database.

user_name is the name of the user to whom an access right is being granted.

Example:

GRANT SELECT ON employees TO user10;

This command grants a SELECT permission on employees table to user10.


3.4.2 REVOKE command

The SQL command is used to revoke a privilege on a table.

Syntax:

REVOKE privilege_name ON table_name FROM user_name;

Where,

 privilege_name is the access right or privilege revoked from the user.

 table_name is the name of the table in the database.

 user_name is the name of the user from whom an access right is being revoked.

Example:

REVOKE SELECT ON employees FROM user10;

This command will REVOKE a SELECT privilege on employees table from user10. If you
REVOKE SELECT privilege on a table from a user, then the user is not able to SELECT data
from that table anymore.
Summary:

DDL

Data Definition Language (DDL) statements are used to define, modify


or remove the table structure.
Commands:
CREATE - This command is used to create objects in the database
ALTER - It alters the structure of the database
DROP - This command is used to delete the object from the database
DML

Data Manipulation Language (DML) statements are used for managing


data within the database.

Commands:
SELECT - retrieve data from the table
INSERT - The data is insert into a table
UPDATE - It updates existing data with new data within a table
DELETE - It deletes the records from a table but the space for the
records remain

DCL
Data Control Language (DCL) statements:
Commands:
GRANT - It gives the user's access privileges to database
REVOKE - withdraw access privileges which was already provided to
the user

Вам также может понравиться