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

1. DDL and DML commands

This document provides an introduction to SQL, detailing its history, key features, and types of commands including DDL, DML, and DCL. It explains the creation and manipulation of database tables, including data types, constraints, and examples of SQL commands for creating, altering, and deleting tables. Additionally, it covers data manipulation commands such as insert, update, delete, and select, along with syntax and practical exercises.

Uploaded by

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

1. DDL and DML commands

This document provides an introduction to SQL, detailing its history, key features, and types of commands including DDL, DML, and DCL. It explains the creation and manipulation of database tables, including data types, constraints, and examples of SQL commands for creating, altering, and deleting tables. Additionally, it covers data manipulation commands such as insert, update, delete, and select, along with syntax and practical exercises.

Uploaded by

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

DBMS(Database

Management System

Semester - II
Session 2024-25
Subject Faculty:
Ms. Annu Yadav
Assistant Professor
Introduction To SQL
SQL stands for structured query language. It was developed in
a prototype RDBMS, ‘System R’, by IBM in mid 1970s.
Oracle corporation introduced the first commercially available
implementation of SQL.
ANSI adopted SQL as a standard language for RDBMS, in
october 1986.
Key Features of SQL are :
• Non Procedural Language
•Unified Language
•Common Language for all relational database
Since SQL is a non procedural language, therefore while working
with SQL, we are not required to specify the procedure to perform a
task, just we are required to specify the task which we want to
perform.
SQL COMMAND
SQL defines following three type of commands :
1. DDL
2. DML
3. DCL
1. DDL : DDL stands for Data Definition Language, as the name
represents, the commands which are used to define the
data (such as creating, altering & droping database
structures) are known as DDL commands.
DDL consists of following Commands :
A. Create Table
B. Alter Table
C. Drop Table
A. Create Table : As the name represents, this command is used to create a
table.
Syntax :
Create table <table name> (
<field name1> <data type(size)> <constraints> ,
<field name2> <data type(size)> <constraints> ,
…);
Rules for Table/Field name : While giving a name to table/field, following rules
must be considered :
1. It may consists of alphabets, digits or any special character.
2. It must begin with an alphabet.
3. It must not be a SQL reserved word.
4. They are not case sensitive.
Data Types
Data types are used to specify what type of value will be stored in a field.
Oracle supports following data types :
1. Char(n) : To store fixed length character data of length n, maximum size is 255
bytes.
2. Varchar2(n) : To store variable length character data, maximum size is 2000
bytes.
3. Number(n,p) : To store fixed and floating point numbers.
4. Date : To store date & time. Oracle supports date in ‘dd-mon-yy’ format.
5. Long : To store up to 2GB of characters. Only one long column is allowed in a
table.
6. Raw : To store binary data such as graphics, sound etc.
7. CLOB : Character Large Object
8. BLOB : Binary Large Object
9. NCLOB : National Language Support Character Large Object
10. BFILE : Binary File
Example : Create a table DEPT having following structure :
Field Name Data Type Description
DEPTNO NUMBER(2) Department Number
DNAME VARCHAR2(20) Department Name
LOC VARCHAR2(10) Department Location

Solution : Create table DEPT(deptno number(2),


dname varchar2(20),
loc varchar2(10)
);
Example : Create a table EMP having following structure :
Field Name Data Type Description
EMPNO NUMBER(4) Employee Number
ENAME VARCHAR2(20) Employee Name
JOB CHAR(10) Designation
MGR NUMBER(4) Respective Manager’s EMPNO
HIREDATE DATE Date of Joining
SAL NUMBER(9,2) Basic Salary
COMM NUMBER(7,2) Commission
DEPTNO NUMBER(2) Department Number

Solution : Create table EMP(empno number(4), ename


varchar2(20), job char(10), mgr number(4),
hiredate date, sal number(9,2), comm
number(7,2), deptno number(2)
);
Constraints
Constraints are a part of the table definition that are used to limit the values entered
into its columns.While creating a table, constraints can be placed on the values that will
be entered into its columns. SQL will reject any value that violates the criteria that were
defined.
Two basic type of constraints are ‘Column Level Constraints’ and ‘Table Level
Constraints’. The difference b/w the two is that column constraints apply only to individual
columns, where as table constraints apply to group of two or more columns.
Constraints can be applied to a table in following two ways:
1. At the time of creation of a table with ‘Create Table’ command.
2. After creation of a table with ‘Alter Table’ command.
All the details of constraints are stored in data dictionary. Each
constraint is assigned a name. It is convenient if we give user
defined names to the constraint so that it is easily referenced,
Otherwise, the name is automatically generated of the form :
SYS_Cn
Where n is unique number.
Note : 1. The keyword constraint is used to give a name to a constraint.
2. All constraint names must be unique.
Oracle supports following constraints :
• NOT NULL : Preventing a column from accepting null values.
• UNIQUE : Ensures uniqueness of the values in a column.
• PRIMARY KEY : Unique key with not null constraint. But only one column
per table is allowed.
• CHECK : Controls the value of a column being inserted. This constraint
allows the user to define a condition, that a value entered into the table,
has to satisfy, before it can be accepted. This constraint consist of the
keyword CHECK followed by parenthesized conditions.
• DEFAULT : Assign a default value for the column, at the time of insertion
when no value is given for that column.
• REFERENCES : Assigns a foreign key constraint to maintain “Referential
Integrity”. A foreign key is a combination of columns with values based on
the primary key values from another table. A foreign key constraint
specifies that the values of the foreign key correspond to the actual values
of the primary key in the other table.
Example 1:
Create table Dept
(
Deptno number(2) Primary Key,
Dname varchar2(20) Not Null Unique,
Loc varchar2(10) Default ‘Boston’,
);
Example 2 :
Create table emp
(
Empno number(4) Constraint PK_EMPNO Primary Key,
Ename varchar2(20) Not Null Unique,
Job varchar2(10),
Mgr number(4) References emp(empno),
Hiredate date Default Sysdate,
Sal number(9,2) Check (sal>=10000 and sal<=50000),
Comm number(7,2),
Deptno number(2) References dept(deptno),
);
Example 3 :
Create table Student
(
Fname varchar2(20) ,
Mname varchar2(20) ,
Lname varchar2(20) ,
Address varchar2(50) Not Null,
Primary Key(fname,Mname,Lname)
);
Exercise : Create a table ITEMMAST having following structure :
Field Name Data Type Description
ITNO NUMBER(4) Item Number
NAME VARCHAR2(20) Item Description
QOH NUMBER(5) Quantity on hand
CLASS CHAR(1) Item Category
UOM CHAR(4) Unit of Measurement
ROL NUMBER(5) Reorder Level
ROQ NUMBER(5) Reorder Quantity
RATE NUMBER(8,2) Unit Sale Price

Constraints :
1. ITNO must be primary key.
2. NAME must not be NULL.
3. QOH should be 100, in case the user does not enter any value for it.
4. CLASS of an item is to be only ‘A’ , ‘B’ or ‘C’.
5. RATE of any item under CLASS ‘A’ should be less than 1000.00; CLASS ‘B’ should be more
than 1000.00 but less than 4500.00 and CLASS ‘C’ should be greater than 4500.00
6. ROL & ROQ must be greater than 0.
Exercise : Create a table ITTRAN having following structure :
Field Name Data Type Description
ITNO NUMBER(4) Item Number
TRANTYPE CHAR(1) Transaction Type
TRANDATE DATE Date of Transaction
QTY NUMBER(5) Quantity
Constraints :
1. ITNO must be foreign key from ITEMMAST table.
2. Type of a transaction is to be only ‘I’ or ‘R’.
3. Whenever a record from ITEMMAST table is deleted then all the
corresponding child records must be deleted from ITTRAN table.
Creating a Table with Rows from Another Table
A table can be created with rows derived from another table.
Syntax :
Create table <table name>
[ (<column name1>, <column name2>, …) ]
as SELECT statement
Example 1:
Create Table Employee
as Select empno, ename, job, sal from Emp where deptno=10;

Example 2:
Create Table Salary
(Name, Salary)
as Select ename, sal from Emp;
B. Alter Table : This command is used to modify the structure of a table. That is
, this command can be used to add a new column to the table, change their
data type, change their size and can also add, delete, enable or disable
constraints.
Syntax :
Alter table <table name>
[ ADD <field name> <data type(size)> <constraints>, … ]
[ MODIFY <field name> <data type(size)>, … ]
[ DROP <options> ]
[ ENABLE/DISABLE <constraint name> ] ;
• The ADD Option : This option is used to add a new column or
constraint(Primary Key, Check or References) to a table.
Example 1 : Add a column to the existing table EMP, which will hold the grades for
each employee.
Alter Table EMP ADD grade varchar2(2);
Example 2 : Add a primary key constraint to the table EMP.
Alter Table EMP ADD CONSTRAINT emp_pk PRIMARY KEY (empno);
Example 3 : Add a foreign key constraint to deptno of table EMP refering deptno of
table dept.
Alter Table EMP ADD CONSTRAINT emp_fk FOREIGN KEY (deptno)
REFERENCES dept(deptno);
Example 4 : Add check constraint for SAL (should be greater than 25000) to the
table EMP.
Alter Table EMP ADD CONSTRAINT emp_ck CHECK (SAL>25000);
• The MODIFY Option : This option is used to modify the data type, size of an
existing field of a table or table constraints(DEFAULT, NOT NULL OR NULL)
with the following restrictions.
• The data type and/or size of a field can be changed, if every row for that column is
NULL.
• A NOT NULL column(field) may be added only to a table with no rows.
• An existing field can be modified to NOT NULL only if it has a non-NULL value in every
row.
Example 1 : Modify the width of a column ENAME to 35 of table EMP.
Alter Table EMP MODIFY ename varchar2(35);
Example 2 : Modify the SAL column of the table EMP to NOT NULL.
Alter Table EMP MODIFY sal number(9,2) NOT NULL;
• The DROP Option : This option is used to remove column(s) or constraint
from a table.
Dropping a Column :
Syntax : Alter Table <Table name> DROP COLUMN <Column name>;
Dropping Multiple Columns :
Syntax : Alter Table <Table name> DROP (<Column name1>, <Column name1>, … );
Dropping a Constraint :
Syntax : Alter Table <Table name> DROP CONSTRAINT <Constraint name>;
Example 1 : Alter Table EMP DROP CONSTRAINT emp_ck;
Example 2 : Alter Table EMP DROP Primary Key;
• The ENABLE/DISABLE Option : These options are used to enable or
disable a constraint for a table.
Syntax : Alter Table <Table name> ENABLE/DISABLE CONSTRAINT <constraint
name>;
Example 1 : Alter Table EMP DISABLE CONSTRAINT emp_pk;
Example 2 : Alter Table EMP ENABLE CONSTRAINT emp_pk;
Example 3 : Alter Table EMP DISABLE CONSTRAINT emp_pk
CASCADE ;
NOTE 1: The keyword CASCADE in the above example disables the dependent
constraints also.
NOTE 2: Data dictionary for constraint is USER_CONSTRAINTS and
USER_CONS_COLUMNS.
Example : Select column_name, constraint_name from USER_CONS_COLUMNS
where TABLE_NAME=‘EMP’;
C. Drop Table : This command is used to drop(delete) a table.
Syntax :
Drop table <table name> ;
Example :
Drop Table emp;
Note : CASCADE CONSTRAINTS clause with DROP TABLE command is used to drop
all referential integrity (foreign key) constraints that refer to primary and
unique keys in dropped table. If this option is omitted, and such referential
integrity constraint exists, Oracle returns an error & does not drop the table.
2. DML : DML stands for Data Manipulation Language, as the
name represents, the commands which are used to
manipulate the data (such as inserting, updating, deleting &
retrieving records) are known as DML commands.
DML consists of following Commands :
A. Insert Command
B. Update Command
C. Delete Command
D. Select Command
A. Insert Command : As the name represents, this command is used to insert
a record in a table.
Syntax :
1. Insert into <table name> (<field name1>, <field name2>, … ) Values
(<value1>, <value2>, … );
Example : Insert into Dept (deptno, dname, loc) values (10,
‘Accounting’, ‘New York’);
2. Insert into <table name> Values (<value1>, <value2>, … );
Example : Insert into Dept values (20, ‘Research’, ‘Dallas’);

3. Insert into <table name> Values(<&field name1>, <‘&field name2’>, … ) ;


Example : Insert into Dept values(&deptno, ‘&dname’,
‘&loc’);
Exercise : Insert following data in DEPT table :
Exercise : Insert following data in EMP table :
B. Update Command : As the name represents, this command is used to
modify existing records of a table.
Syntax :
Update <table name> set <field name1=Value1>,
<field name2=Value2>, … [ where <condition> ];

Example1 : Increase everybody salary by 10%.


Update emp set sal = sal + (sal * 0.10) ;

Example2 : Change the department of KING to 40.


Update emp set deptno = 10 where
ename=‘KING’ ;
Exercise
1. Increase the salary of all the clerks by 25%.
2. Increase commission by 500 of all those salesman who are
getting commission less than 1000.
3. Increase salary by 500 and commission by 200 of the
employee “ALLEN”.
4. Change name of employee “CLARK” BY “JOHNSON”.
5. Update commission of all clerks working in deptno. 20 by 300.
C. Delete Command : As the name represents, this command is used to
delete existing records from a table.
Syntax :
Delete from <table name> [ where <condition> ];

Example1 : Delete all records from emp table.


Delete from emp ;

Example2 : Delete records of all clerks from emp table.


Delete from emp where job=‘CLERK’;
Exercise
1. Delete all the records of all employees whose commission is
null.
2. Delete deptno. 10 from dept table (Corresponding records
from emp table should also be deleted).
3. Delete records of all employee working under the manager
having employee no. 7698.
4. Delete all the salesman of deptno. 10 and 20.
5. Delete all analyst getting salary b/w 3000 and 5000.
C. Select Command : This command is also known as query command which
is used to retrieve data from a table.
Syntax :
Select <column-list>/* from <table-name>
[ Where <condition> ]
[ Group by <column-name> ]
[ Having <condition> ]
[ Order by <expression> ];

Example1 : Display all details of all employees.


Select * from emp ;
Example2 : Display all employee names along with their salary.
Select ename,sal from emp ;
Example3 : Display all departments name and their location.

Example4 :Display all department numbers, employee numbers and their manager
numbers in that order.

Example5 :Display all of the jobs available in our organization.

Example6:Display name and total salary of every employee.

WHERE Clause : This clause is used along with the SELECT command to specify the
condition, based on which the rows(data) will be retrieved from a table.
Example1 : Display all employees working in department number 10.
Select * from emp where deptno=10;
Example2 : Display name and salary of all employees whose salary is more than 1000.
Select ename, sal from emp where sal>1000;
Example3 : Display employee number and name of managers.

Example4 : Display name of clerks working in department number 20.

Example5 : Display name of analysts and salesman.

Example6 : Display the details of employees who have joined before the end of
september’ 81.

Example7 : Display name of employees who are not manager.


Example8 : Display name and salary of the employees of department number 20 and
30.

Example9 : Display total salary of all the employees.


Select sum(sal) from emp;

Example10 : Display average salary of all the employees.


Select avg(sal) from emp;

Example11: Display highest salary.


Select max(sal) from emp;

Example12 : Display lowest salary.


Select min(sal) from emp;

Example13 : Count how many employees are working in our organisation.


Select count(empno) from emp;
Operator
s
• Arithmetic Operators (+, -, *, /)
• Relational Operators (<, >, <=, >=, !=, <>, =)
• Logical Operators (AND, OR, NOT)
• Special Operators (IN, BETWEEN, LIKE)
 IN : This operator is used to compare with any of the given values.
Example : Display name of the employees working in department number 10, 20 or
30.
Select ename from emp where deptno IN (10,20,30);

BETWEEN : This operator is used to compare a value with in the given range.
Example : Display name of all the employees who are getting salary b/w 5000 and
10000.
Select ename from emp where sal between 5000 and 10000;
 LIKE : This operator is used to compare for similar match not for exact match.
Therefore, while working with LIKE operator, we are also required to use wild
card characters. Oracle supports following two wild card characters :
1. % (Percentile) : To replace zero or more characters.
2. _ (Underscore) : To replace one character.
Example 1 : Display details of all the employees whose name
begins with “R”.
Select * from emp where ename like ‘R%’;
Example 2 : Display details of all the employees whose name
ends with “T” and four characters long.
Select * from emp where ename like ‘_ _ _ T’;
• Write SQL command to perform following Queries:
 Display name of employees whose names have exactly five characters.

 List the employee names having ”I” as second character.

 List names of all employees who have “LL” and “TT” in their names.

 Display details of all employees whose name having two “M”.


Exercise : Insert following data in ITEMMAST table :
• Write SQL command to perform following Queries:
 Display the names of items belonging to class “A”.
 Display item number, name and quantity on hand of all items where the quantity on hand is more than
100.
 Display the list of item numbers of class “C” and their quantity on hand where rate is greater than Rs.
2000.
 Display the list of items which are to be reordered.
 List out the transactions of items for the month of Jan’94.
 List all issues for item number 1005.
 List the total issues for each item.
 List the average receipt of each item.
 List the items, which have been issued more than 3 times.
 List all the transactions b/w Jan’94 and Aug’94.
 List the different units of measurement available in ITEMMAST table.
 List the minimum, maximum, average and total quantity received for each item.
 List the value of the stock of each item. Make sure that heading will be “VALUE”
 List the items in ascending order of class and within class, in descending order of rate.
 List the total value of stock of items in each class.
 List the minimum, maximum, average and total value of items in each class.

You might also like