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

Rdbms Unit 2

The document provides an overview of SQL, a database query language for managing data in relational databases, detailing its history and standards. It outlines various types of SQL commands, including Data Definition Language, Data Manipulation Language, Data Query Language, Data Control Language, and Transaction Control Language commands, along with their syntax and examples. Additionally, it discusses data types, creating and manipulating tables, and the importance of data constraints in maintaining data integrity.

Uploaded by

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

Rdbms Unit 2

The document provides an overview of SQL, a database query language for managing data in relational databases, detailing its history and standards. It outlines various types of SQL commands, including Data Definition Language, Data Manipulation Language, Data Query Language, Data Control Language, and Transaction Control Language commands, along with their syntax and examples. Additionally, it discusses data types, creating and manipulating tables, and the importance of data constraints in maintaining data integrity.

Uploaded by

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

Subject : [BCS-403] Relational Database Management Systems

Class : SYBSc [CS] - Sem IV By : Ms. Archana Ojha

Unit II : SQL Statements & Working with Tables


2.1 What is SQL ?
An SQL is a database query language for storing & managing data in a Relational
DBMS. In 1970, Edgar Frank Codd [E.F.Codd] proposed the use of query language to
communicate with the database.
IBM[International Business Machine] developed the original version of SQL, originally
called SEQUEL[Simple-English/Structured Query Language]. In 1978, IBM released the first
product of sequel and named it System/R.
In 1986, ANSI[American National Standards Institute] and ISO[International
Organisation for Standardization] published an SQL standard as SQL-86. Also in 1989, an
extended standard was published as SQL-89.
SQL is domain-specific i.e works in a specific domain(area) and declarative language
that has clearly established itself as the standard relational database language.

2.2 Types of SQL Commands :


 Data Definition Language commands
These commands are used to create and define the
structure or schema of the table. All the DDL commands are auto-committed i.e. changes made
by them are automatically saved. Let us describe these commands in brief as:
1. CREATE statement - CREATE statement is used to create the database or its objects like
table, index, function, view, etc.
Syntax: SQL> Create table <tb_name> (Column1 dtype[size], Column2 dtype[size], Column3
dtype[size]);

E.g: SQL> Create table emp_details (Emp_id int, Name


varchar(10), DOB date);

2. ALTER statement - ALTER statement is used to change the structure of table. It could be
modifying the existing structure or adding a new attribute. It performs 5 different
operations as:
i. To add a new column :

Syntax: SQL> ALTER TABLE <tb_name > ADD <Column_name> dtype [size] ;

1
E.g: SQL> Alter table emp_details ADD Email-Id varchar(15);

ii. To change the datatype of existing column:

Alter table <tb_name> Modify <column-name> dtype


Syntax: SQL>
[new size];
Eg: SQL> Alter table emp-details modify name varchar(20);
iii. To drop an existing column:

Syntax: Alter
SQL> table <tb_name> DROP COLUMN
<column_name>;
E.g: SQL> Alter table emp-details DROP COLUMN Email_id ;
iv. To rename an existing column:

Syntax: Alter table <tb_name> RENAME


SQL> COLUMN
<old_column_name> to <new_column_name>;
E.g: SQL> Alter table emp_details rename column NAME to
Emp_name;
v. To rename the table name:

Syntax:SQL> Alter table <tb_name> RENAME to <new


table_name>;
E.g: SQL> Alter table emp_details RENAME to Employee_details;

3. DROP statement- DROP statement is used to delete the table with its overall structure. Once a
table is dropped, its structure no longer exists in the database.

Syntax: SQL> Drop table <table_name>;


E.g: SQL> Drop table Employee_details;

4. TRUNCATE statement: TRUNCATE statement is used to delete all the rows in a table and free
the space of the table. It cannot use WHERE clause to delete a particular record. Using
truncate, the structure of the table is remained as it is.

2
Syntax: SQL>Truncate table <table_name>;
E.g: Truncate table Employee_details;

 Data Manipulation Language Commands


DML commands are used to modify the
original data in the database without changing its structure. It is used to manipulate the data.
These commands are not auto committed i.e. they can be rolled back. Let us describe these
commands in brief as below:

1. INSERT statement: INSERT statement is used to insert data into the row of the table.
A user can insert values of all columns or a specific column.

i. To insert all values:


Syntax:
SQL> Insert into <table_name> values (Value1, Value2,
Value3,..,Value n);
E.g: SQL> Insert into Emp_details values (101, ‘ABC’, ‘1990-01-
25’);
ii. To insert specific columns:
Syntax:SQL> Insert into <table_name>(Column(s)) values
<value(s)>;
E.g: SQL> Insert into Emp_details(Emp_id) values(102);
2. UPDATE statement: UPDATE statement is used to update existing records in a table.
In this statement, WHERE clause specifies which record or records should be updated.
If you omit the WHERE clause, all the records will be updated.

Syntax:
SQL> Update <table_name> SET column_name= value
[where column_name=value];
E.g: SQL> Update Emp_details SET Emp_name=‘PQR’ where
Emp_id= 101;
3. DELETE statement: DELETE statement is used to delete records in a table. In this
statement also WHERE clause specifies which record or records should be deleted. If
you omit the WHERE clause, all records will be deleted. If all records are deleted, the
structure of the table remains as it is with 0 records.
Syntax: SQL> Delete from <table_name> [where column_name=
value]
3
E.g: SQL> Delete from Emp_details where Emp_id= 102;

 Data Query Language Commands


These commands are used to query data from the
database. It uses select command to retrieve data from the database. Either all records can be
retrieved or a user can retrieve specific records.

Syntax: SQL> Select * from <table_name> [where column_name= value];


E.g: SQL> Select * from Emp_details where Emp_id= 101;

 Data Control Language Commands


These commands are used to control the data in the
database by dealing with permissions to users. The DBA is responsible to give and take back the
permissions. It uses two commands to do so:

1. GRANT statement: GRANT statement is used to assign/give the users access permissions to
the database.
Syntax: SQL> Grant <Privileges commands> on <table_name> to
<username>;
E.g: SQL> Grant select, insert on Emp_details to user1;

2. REVOKE statement: Revoke statement is used to take back or remove the granted
permissions from the database users.
Syntax:SQL> Revoke <Privileges commands> on <table_name> from
<username>;
E.g: SQL> Revoke insert on Emp_details from user1;

 Transaction Control Language Commands


These commands are used to manage transactions in
the database. These are used to manage the changes made to the data using DML commands.
1. COMMIT statement: COMMIT statement is used to permanently save DML transactions into
the database. This statement is used so that the changes made on data must not be
restored (UNDO).
Syntax: SQL> Commit;
E.g: SQL> Commit;

2. ROLLBACK statement: ROLLBACK statement is used to restore the database to its last
committed state. For e.g : If we have used update command to make some changes in a

4
table and realize that those changes were not required then we can use the rollback
command to undo the changes.
Syntax: SQL> Rollback:
E.g: SQL> Rollback;

2.3 Datatypes in SQL :


A datatype is defined as the type of data that any column or variable can store and
access. The basic datatypes in SQL can be broadly divided into three categories as :
Datatypes in SQL

String-type Numeric-type Date-type

Char(n) smallint Date


Varchar(n) int(n) Time
Varchar2(n) decimal(p,s) DateTime
Text Boolean
Let us describe the datatypes in SQL in brief as below :

1. String-type :
a) Char(n) : It is a fixed-length character string with user-specified length. Its size
can be between 0-255. The default size is 1.
b) Varchar(n) : It is a variable-length character string with user-specified length. Its
size can be between 0-255. It can contain alphabets, numbers & special
symbols.
c) Varchar2(n) : It is an extended version of varchar datatype, generally used in
Oracle databases. Its size can be between 0-65535 characters.
d) Text : It is used to store huge amount of data in a file upto 2GB.
2. Numeric-type :
a) Smallint : It allows numeric values as whole numbers between the range -32768
to 32767.
b) Int : It allows integers between -2147483628 to 2147483627 i.e -2^31 to 2^31-1.

5
c) Decimal(p,s) : It accepts numeric decimal values using precision and scale
values. Precision is a positive integer that indicates the number of digits while
scale indicates the number of digits after the decimal point, as decimal(2,3).
d) Boolean : It accepts only one value either true or false as 1 or 0 respectively. No
parameters are required at declaration.
3. Date-type :
a) Date : It accepts date values. No parameters are required while declaring date
datatype. Value assigned to date should be enclosed in single quotes. The
default format of date is YYYY-MM-DD.
b) Time : It accepts time values. No parameters are required while declaring date
datatype. Value assigned to time should be enclosed in single quotes. The
default format of time is HH:MM:SS.
c) DateTime : It accepts a date & time combination. It is mostly used to get or
update system’s current date and time.

2.4 Creating Tables :

SQL CREATE TABLE statement is used to create table in a database. If you want to
create a table, you should name the table and define its column and each column's data
type.

The basic syntax of the CREATE TABLE statement is as follows −

Create Table "Tb_name" ("column1" "data type", "column2" "data ty


pe", .. "columnN" "data type");

CREATE TABLE is the keyword telling the database system what you want to do. In this
case, you want to create a new table. The unique name or identifier for the table follows
the CREATE TABLE statement.
Then in brackets comes the list defining each column in the table and what sort of data
type it is. The syntax becomes clearer with the following example.

SQL> Create table emp_details (Emp_id int, Name varchar(10),


DOB date);

6
2.5 Selecting from Tables, WHERE Clause, DISTINCT Clause, Column Aliasing :

A query is a question asking for any information. An SQL


query SELECT is used to retrieve desired information from the database. The Basic structure of
an SQL Query consists of three clauses: SELECT, FROM and WHERE. A typical SQL query can be
given as:
SQL> SELECT A1, A2, …, An
FROM r1, r2, …, rn
[where P];
Where, A refers to Attribute/Column, r refers to the relation/table and
P refers to the predicate (condition/expression)
The SELECT clause specifies the list of attributes that will appear in the
output table. If all attributes should appear then instead of specifying each attribute, a user can
use an asterisk (*) symbol.
The FROM clause specifies the list of tables that contain the attributes
to be displayed.
For e.g: Consider a relation student as:

R_no Name Class


1 Aaa FY
2 Bbb SY
3 Ccc TY
Table. STUDENT

If the user wants to retrieve all columns of the table, he can use the SQL query as:

SQL> Select * from STUDENT;

 WHERE clause :
The SQL WHERE clause is used to specify a condition where
retrieving data from a single or multiple tables. Data values are retrieved only if the condition
satisfies.
WHERE clause can also be used with UPDATE and DELETE
statements to fetch the necessary records.
For e.g: If only Name attribute is to be retrieved of a student whose
Roll no is 3 then use the query as:
SQL> Select Name from student where Roll_no = 3;

 DISTINCT clause :
The DISTINCT clause in select statement is used to retrieve only
distnct i.e unique values. This clause eliminates duplicate records from the output.
Syntax: SQL> Select distinct <column_name> from <table_name>;
7
E.g: SQL> Select distinct Name from student;

 Using Column Aliases


Aliases are the temporary names given to a column or a table for
a particular query. The column or table is renamed for temporary purpose which does not
change the original name in the database.
Aliases are useful when table or column names are big or difficult.
These are mostly used when there are more than one table in a single query.

1. Column Alias :
Syntax: SQL> Select <column> AS <Alias name> from <table_name>;
E.g: SQL> select RNO AS id, name as Student_name from STUDENT ;

2. Table Alias :
 Single Table
Syntax: SQL> Select<Alias_Name>.<column_Name> from <table name> <Alias_Name>;
E.g: SQL> select S.RNO, S.NAME from STUDENT S ;

 For multiple tables


Syntax: SQL> Select <Alias_name>.Column(s) from <table_name> <Alias_name> [where
column=value];
E.g: SQL> SELECT S.RNO, S.NAME, S.CLASS, M.MARKS FROM STUDENT S, MARKS M WHERE
S.RNO=M.RNO ;

2.6 Manipulating Table Data :


Oracle provides Data Manipulation Language commands to exercise data operations
in the database. Data operations can be populating the database tables with the
application or business data, modifying the data and removing the data from the database,
whenever required.
DML commands are used to modify the original data in the database without changing
its structure. It is used to manipulate the data.
Let us describe these commands in brief as below :

1. INSERT statement: INSERT statement is used to insert data into the row of the table.
A user can insert values of all columns or a specific column.
2. UPDATE statement: UPDATE statement is used to update existing records in a table.
In this statement, WHERE clause specifies which record or records should be updated.
If you omit the WHERE clause, all the records will be updated.
3. DELETE statement: DELETE statement is used to delete records in a table. In this
statement also WHERE clause specifies which record or records should be deleted. If
you omit the WHERE clause, all records will be deleted. If all records are deleted, the
structure of the table remains as it is with 0 records.

8
2.7 Altering Table Structure :

The ALTER TABLE statement is used to add, delete, or modify columns in an existing
table. It is also used to rename a table.

The ALTER TABLE statement is also used to add and drop various constraints on an
existing table.

i. To add a new column :


Syntax: SQL> ALTER TABLE <tb_name > ADD <Column_name> dtype [size] ;
E.g: SQL> Alter table emp_details ADD Email-Id varchar(15);

ii. To change the datatype of existing column:


Syntax: SQL> Alter table <tb_name> Modify <column-name> dtype [new size];
Eg: SQL> Alter table emp-details modify name varchar(20);
iii. To drop an existing column:
Syntax: SQL> Alter table <tb_name> DROP COLUMN <column_name>;
E.g: SQL> Alter table emp-details DROP COLUMN Email_id ;
iv. To rename an existing column:
Syntax: SQL> Alter table <tb_name> RENAME COLUMN <old_column_name> to
<new_column_name>;

E.g: SQL> Alter table emp_details rename column NAME to Emp_name;

v. To rename the table name:

Syntax: SQL> Alter table <tb_name> RENAME to <new table_name>;


E.g: SQL> Alter table emp_details RENAME to Employee_details;

2.8 Data Constraints :


The rules which are used to control and maintain data integrity are called
Data Constraints. Constraints apply limits to the data or type of data that can be
inserted/updated/deleted from a table. Constraints are the rules that we can apply on the
type of data in a table. The whole purpose of constraints is to maintain the data
integrity during an update/delete/insert into a table.
This ensures the accuracy and reliability of the data in the database.
Constraints could be either on a column level or a table level. The column level
constraints are applied only to one column, whereas the table level constraints are
applied to the whole table.
Data constraints are system dependent rules i.e., Constraints applied for
one system are not applicable for other. Database without data constraints may store
data with errors and also generate reports with errors.
9
Once data constraints are applied on the database table, Each DML
operation must be according to data constraint.
All the data constraints in oracle are classified as :

Data Constraints

I / O Constraints Business Rule

Not Null Check

Unique

Primary Key

Foreign Key

Default

 I / O Constraints
Constraints of this category when applied on database table will maintain data
accuracy while performing I/ O operations.
1. Not Null
According to integrity rule 1, if a table has unique identifier, such field should not
contain Null value. By default, oracle allows Null value in each column in every created
table. When NOT NULL constraint is assigned, such a column cannot accept or store
NULL value.
a.) Using Create Table
SQL> Create table <tb_name> (col_name dataype[size] NOT NULL, - , - ,) ;
SQL> Create table SDetails (RNO Int NOT NULL, SName Varchar2(20),
Class Varchar2(10));

b.) Using Alter Table


SQL>Alter table <tb_name> Modify col_name dataype[size] NOT NULL ;
SQL>Alter table SDetails Modify RNO Int NOT NULL ;
While applying constraints using ALTER statement, if table contains records, these
records must be satisfying the constraints otherwise, the constraint cannot be applied.
To remove NOT NULL constraint from any table field, ALTER table statement can
be used as :

SQL> Alter table <tb_name> Modify col_name datatype NULL ;


SQL> Alter table SDetails Modify RNO Int NULL ;

 Errors while using NOT NULL :


1. Give the oracle error while inserting NULL value in a column having NOT NULL
constraint :

10
ORA–01400 : Cannot insert NULL into
(“User_name”.”Table_name”.”Col_name”).

2. Give the oracle error while applying NOT NULL constraint to a column having
NULL values :
ORA – 02296 : Cannot enable (“User_name”) – null values found.

2. Unique
When NOT NULL constraint is applied , it restricts only NULL value entry, but
allows duplicate values. According to Integrity Rule 1, Unique identifier should not
contain duplicate values.
When Unique constraint is assigned to a table field, it cannot accept and store
duplicate values.

a. Using Create Table


SQL> Create table <tb_name> (col_name dataype[size] CONSTRAINT
<Const_name> Unique, - , - ,) ;
SQL> Create table SDetails (RNO Int CONSTRAINT SD_RNO_UN Unique,
SName Varchar2(20), Class Varchar2(10));

b. Using Alter Table


SQL>Alter table <tb_name> ADD CONSTRAINT <Const_name> Unique
(col_name) ;
SQL>Alter table SDetails ADD CONSTRAINT SD_RNO_UN Unique (RNO) ;
To remove Unique constraint from any table field, ALTER table statement
can be used as :
SQL> Alter table <tb_name> DROP Constraint <Const_name> ;
SQL> Alter table SDetails DROP Constraint SD_RNO_UN ;

 Errors while using Unique :


1. Give the oracle error while inserting duplicate value in a column having Unique
constraint :
ORA–00001 : Unique constraint (“User_name”.”const_name”) violated

2. Give the oracle error while applying Unique constraint to a column having
duplicate values :
ORA – 02299 : Cannot validate (“User_name”.”const
_name”) – duplicate keys found.

11
3. Primary key
A PRIMARY KEY is a combination of not null & unique constraints i.e. does
not allow null and duplicate values in the column. Primary key constraint uniquely
identifies each record in a database. Multiple UNIQUE constraints can be defined
on a table, whereas only one PRIMARY KEY constraint can be defined on a table.
a. Using Create Table
SQL> Create table <tb_name> (col_name dataype[size] CONSTRAINT
<Const_name> Primary key, - , - ,) ;
SQL> Create table SDetails (RNO Int CONSTRAINT SD_RNO_UN Primary
key, SName Varchar2(20), Class Varchar2(10));

b. Using Alter Table


SQL>Alter table <tb_name> ADD CONSTRAINT <Const_name> Primary
key (col_name) ;
SQL>Alter table SDetails ADD CONSTRAINT SD_RNO_PK Primary key
(RNO) ;

To remove Primary key constraint from any table field, ALTER table
statement can be used as :
SQL> Alter table <tb_name> DROP Constraint <Const_name> ;
SQL> Alter table SDetails DROP Constraint SD_RNO_PK;

 Errors while using Primary Key :


1. Give the oracle error while inserting NULL value in a column assigned with
Primary key constraint :
ORA–01400 : Cannot insert NULL into (“User_name”.”const
_name”).

2. Give the oracle error while inserting Duplicate value in a column assigned
with Primary key constraint :
ORA – 00001 : Unique constraint (“User_name”.”const_name”) violated

3. Give the oracle error while applying primary key constraint to a column
containing NULL values :
ORA–01449 : Cannot contain NULL values ; Cannot alter to NOT NULL.

4. Give the oracle error while applying primary key constraint to a column
containing Duplicate values:
ORA – 02299 : Cannot validate (“User_name”.”const
_name”) – Primary key violated.

12
4. Foreign key
Foreign Key is a field in a table which uniquely identifies each row of a
another table i.e. this field points to primary key of another table. The relationship
between 2 tables matches the Primary Key in one of the tables with a Foreign Key
in the second table. FOREIGN KEY constraint applied column must have same data
type as the reference on another table column.

a. Using Create Table


SQL> Create table <tb_name> (col_name dataype[size] CONSTRAINT
<Const_name> References <Primary_key_table> (col_name), - , - ,) ;
SQL> Create table SDetails (RNO Int CONSTRAINT SD_RNO_FK References
SDetails (RNO), SName Varchar2(20), Class Varchar2(10));

b. Using Alter Table


SQL>Alter table <tb_name> ADD CONSTRAINT <Const_name> Foreign key
(col_name) References <Primary_key_table> (col_name) ;
SQL>Alter table SDetails ADD CONSTRAINT SD_RNO_FK Foreign key (RNO)
References SDetails (RNO) ;

To remove Foreign key constraint from any table field, ALTER table
statement can be used as :
SQL> Alter table <tb_name> DROP Constraint <Const_name> ;
SQL> Alter table SDetails DROP Constraint SD_RNO_FK ;

 Errors while using Foreign Key :


1. Give the oracle error while creating a foreign table with non existing Primary
key table :
ORA–02270 : No matching unique or primary key for this column list.

2. Give the oracle error while inserting a value in a foreign key column which is
not present in Primary key :
ORA–02291 : Integrity Constraint (“User_name”.”const
_name”) – Parent key not found.

3. Give the oracle error while applying foreign key constraint to a column
having values which are not present in primary key column :
ORA–02298 : Cannot validate (“User_name”.”const
_name”) – Parent keys not found.

4. Give the oracle error while deleting a value from primary table which is also
present in foreign table :
ORA–02292 : Integrity Constraint (“User_name”.”const
_name”) Violated – Child record found.

13
5. Check
Using the CHECK constraint we can specify a condition for a field, which
should be satisfied at the time of entering values for this field. Check constraint is
used to restrict the value of a column between a range. It performs check on the
values, before storing them into the database.
For example, the below query creates a table Student and specifies the
condition for the field AGE as (AGE >= 18), i.e. the user will not be allowed to enter
any record in the table with AGE < 18.

a. Using Create Table


SQL> Create table <tb_name> (col_name dataype[size] CONSTRAINT
<Const_name> CHECK (<Exp.>)- , - ,) ;
SQL> CREATE TABLE ORD_DETAILS (ORD_ID INT, QTY_ORD INT
CONSTRAINT OD_QO_CHK CHECK (QTY_ORD > 0), ODATE DATE);

b. Using Alter Table


SQL>Alter table <tb_name> ADD CONSTRAINT <Const_name> CHECK
(<Exp.>) ;
SQL> ALTER TABLE ORD_DETAILS ADD CONSTRAINT OD_STA_CHK CHECK
(STATUS IN ('C', 'P')) ;

To remove CHECK constraint from any table field, ALTER table statement
can be used as :
SQL> Alter table <tb_name> DROP Constraint <Const_name> ;
SQL> ALTER TABLE ORD_DETAILS DROP CONSTRAINT OD_STA_CHK ;

 Errors while using CHECK :

1. Give the oracle error while inserting such value in a column with check
constraint which is not in its domain :
ORA-02290 : check constraint (“User_name”.”const
_name”) violated.

2. Give the oracle error while inserting a value in a foreign key column which is
not present in Primary key :
ORA-02293 : cannot validate (XE.OD_STA_CHK) - check constraint violated.

6. Default
This constraint is used to provide a default value for the fields. That is, if at
the time of entering new records in the table if the user does not specify any value
for these fields then the default value will be assigned to them.

14
a. Using Create Table
SQL> Create table <tb_name> (col_name dataype[size] DEFAULT ‘VALUE’,-
, - ,) ;
SQL> CREATE TABLE STUDENT(RNO INT, NAME VARCHAR2(10), CLASS
VARCHAR2(5), COUNTRY VARCHAR2(10) DEFAULT 'INDIA');
To remove DEFAULT constraint from any table field, ALTER table
statement can be used as :
SQL> Alter table <tb_name> MODIFY Col_name <Const_name> NULL ;
SQL> ALTER TABLE STUDENT MODIFY COUNTRY DEFAULT NULL ;

15

You might also like