You are on page 1of 56

GRAMIN TECHNICAL AND

MANAGEMENT CAMPUS, NANDED

Database
Management
System
Mr. Madale L S (M.
Computer Tech
Engg. CSE)
(Third Semester)
Lecturer in Computer Engg. Department
ByPolytechnic Vishnupuri, Nanded
Gramin

Mr. Madale L. S.
Lecturer in Computer Engg. Department
Introduction to SQL

• Objectives
• Definition of SQL
• Pronouncing SQL: S-Q-L or sequel?
• Types of SQL statements.
• Data Definition Language (DDL)
• Data Manipulation Language (DML)
• Data Control Language (DCL)
• Data Query Language (DQL)
• Transaction Control Language (TCL)
Characteristics of SQL
• SQL is easy to learn.

• SQL is used to access data from relational database management


systems.

• SQL can execute queries against the database.

• SQL is used to describe the data.

• SQL is used to define the data in the database and manipulate it


when needed.

• SQL is used to create and drop the database and table.

• SQL is used to create a view, stored procedure, function in a


database.
SQL Data Types
SQL Data type is used to define the values that a column can contain.
Every column is required to have a name and data type in the
database table.
Binary Data Types
There are Three types of binary Data types which are given below:

• Binary:
It has a maximum length of 8000 bytes. It contains fixed-length
binary data.

• Varbinary:
It has a maximum length of 8000 bytes. It contains variable-
length binary data.

• Image:
It has a maximum length of 2,147,483,647 bytes. It contains
variable-length binary data.
Approximate Numeric Data Type
FLOAT :
-1.79E + 308 to 1.79E + 308
It is used to specify a floating-point value e.g. 6.2, 2.9
etc.

REAL :
-3.40e + 38 to 3.40E + 38
It specifies a single precision floating point number.
Exact Numeric Data Type
The subtypes are given below:

INT :
It is used to specify an integer value.
SMALLINT :
It is used to specify small integer value.
BIT :
It has the number of bits to store.
DECIMAL :
It specifies a numeric value that can have a decimal number.
NUMERIC :
It is used to specify a numeric value.
Character String Data type:
The subtypes are given below:
char
It has a maximum length of 8000 characters. It
contains Fixed-length non-unicode characters.
varchar
It has a maximum length of 8000 characters. It
contains variable-length non-unicode characters.
text
It has a maximum length of 2,147,483,647
characters. It contains variable-length non-unicode
characters.
Date and time Data types :
The subtypes are given below:

Date:
It is used to store the year, month, and days value.

Time:
It is used to store the hour, minute, and second values.

Timestamp:
It stores the year, month, day, hour, minute, and the second
value.
Types of SQL Commands
• There are five types of SQL commands: DDL, DML, DCL, TCL,
and DQL.
Data Definition Language

Data definition language(DDL) provides commands for


defining relation schemas, deleting relations, and modifying
relation schemas.

CREATE – To create schema of database.


DROP – Delete Table from database.
ALTER – Alter the structure of database.
TRUNCATE – Delete all records from table, structure of table
will not drop.
RENAME – Rename the table name.
DESC – To view the structure of table.
Create Table Command
It is used to create a new table in the database.

Syntax :
CREATE TABLE TABLE_NAME (COLUMN_NA
ME1 DATATYPES[SIZE],
COLUMN_NAME2 DATATYPES[SIZE]…….
COLUMN_NAME n DATATYPES[SIZE]);

Example :

CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email


VARCHAR2(100), DOB DATE);
Alter Table Command
It is used to alter the structure of the database. This change could be
either to modify the characteristics of an existing attribute or probably to add a
new attribute.
Syntax :

• To add a new column in the table


ALTER TABLE table_name ADD (Column_name datatype(size));

• To modify existing column in the table:


ALTER TABLE table_name MODIFY (Column_name datatype(size));

• To drop column from existing column in the table:


ALTER TABLE table_name DROP COLUMN Column_name ;
Example :
ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));

ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));


Drop Table Command
It is used to delete both the structure and record stored in the table.

Syntax :

DROP TABLE Table_Name ;

Example :

DROP TABLE EMPLOYEE;


Truncate Table Command
It is used to delete all the rows from the table and free the space
containing the table.

Syntax :

TRUNCATE TABLE table_name;

Example :

TRUNCATE TABLE EMPLOYEE;


Describe Table Command
It is used to view the structure of the table.

Syntax :

DESCRIBE TABLE table_name;


OR
DESC TABLE table_name;

Example :

DESCRIBE TABLE EMPLOYEE;


OR
DESC TABLE EMPLOYEE;
Rename Table Command
It is used to rename the existing table.

Syntax :

RENAME TABLE table_name to new_table_name;

Example :

RENAME TABLE EMPLOYEE TO EMP;


Data Integrity Constraints
The constraints makes sure that only authorized user will make
modification to database and changes should not lead to loss of
data consistency and correctness.

Types of Data Integrity Constraints :

• Domain Relational Constraints


• Relational Constraints
• Referential Relational Constraints
Domain Relational Constraints
 Domain constraints allow us to test whether the values
inserted into the database are correct or not.
 The create table command may also include domain
constraints which can check integrity of database.

Types of Domain Integrity Constraints :

• Null Constraints / Required Data Constraints(Not Null)


• Check Constraints / User defined Constraint
• Default Constraint
Domain Relational Constraints
• Null Constraints / Required Data Constraints(Not Null)
• Database may have some attributes mandatory like, user
registration must have email address or phone no.
• These attributes in a database are not allowed to contain
NULL value or blanks.

• Syntax :
• Create table table_name(column_name1 datatype(size) Null
or Not Null constraint, column_name2 datatype(size)…..);

• Example :
• Create table student(roll number(5) Not Null, name
varchar(20),…);
Domain Relational Constraints
• Check Constraints / User defined Constraints
• The Check Constraints is used to ensure that attribute
value satisfies specific condition as specified by data
requirements.
• The DBMS can prevent user from entering incorrect or
other data in database table.

• Syntax :
• Create table table_name(column_name1 datatype(size)
Check Constraint, column_name2 datatype(size)…..);
• Example :

• Table with student entity having gender which can be M or F.


• Create table student(roll number(5) , name varchar(20),
gender varchar(1) check (gender in (‘M’,’F’)),…… );
Domain Relational Constraints
• Default Constraints :
• The Default keyword is used to add a default specified
value, if no attribute value is provided by user.
• It avoids addition of NULL value by inserting default
value as specified.

• Syntax :
• Create table table_name(column_name1 datatype(size)
Default ‘unknown’, column_name2 datatype(size)…..);
• Example :

• Table with student entity having gender which can be M or F.


• Create table student(roll number(5) , name varchar(20),
gender varchar(1) Default ‘unknown’,…… );
Entity Relational Constraints
• Entity constraints allow us to test whether the tuple
inserted into the database are correct or not.
• The create table command may also include entity
constraints which can be the primary key of table.
• Primary Key Constraint :
• Unique Constraints
Data Manipulation Language

Interactive Data Manipulation language (DML) : it includes


commands to insert tuples into, delete tuples from and
modify tuples in the database.
SELECT – retrieve data from the database
INSERT – insert data into a table.
UPDATE – updates existing data within a table.
DELETE – delete existing rows.
Data Control Language

DCL :
Data control language is used to control various user actions
like inserting data, updating data, deleting data or viewing
data.
To perform any operation in the database user needs
privileges like creating table, indexes or views.
DCL is set of commands used to,
GRANT
REVOKE
Data Control Language

GRANT:
A system privilege is the right to perform a particular action or
to perform an action on any schema objects or a particular type.
An authorized user may pass on this authorization to other
users. This process is called as Granting of privileges.

Syntax :

GRANT<All | privilege list>


ON<Table Name or view name>
TO< User | role list | public >
[with GRANT OPTION]
Data Control Language

Example :

Granting user u1,u2,u3 the select privilege on emp relation.

GRANT select , insert


ON emp
TO u1,u2,u3
Data Control Language
 REVOKE :

 REVOKE is used to reject the privileges given to particular user.


 Syntax :

REVOKE<All | privilege list>


ON<Table Name or view name>
FROM< User | role list | public >
[RESTRICT/CASCADE]

 CASCADE : Will revoke all privileges along with all dependent grant
privilege.
 RESTRICT : Will not revoke all related grants only removes that
GRANT only.
Data Control Language

Example :

Revoke user u1,u2,u3 the select privilege on emp relation.

REVOKE select , insert


ON emp
FROM u1,u2,u3
Transaction Control Language
 TCL commands can only use with DML commands like INSERT,
DELETE and UPDATE only.
 These operations are automatically committed in the database that's
why they cannot be used while creating tables or dropping them.

• Here are some commands that come under TCL:


• COMMIT
• ROLLBACK
• SAVEPOINT
Transaction Control Language
COMMIT COMMAND :

Commit command is used to save all the transactions


to the database.

Syntax:
COMMIT;

Example :
DELETE FROM CUSTOMERS
WHERE AGE = 25;
COMMIT;
Transaction Control Language
ROLLBACK COMMAND:
Rollback command is used to undo transactions that
have not already been saved to the database.

Syntax:
ROLLBACK;

Example :

DELETE FROM CUSTOMERS


WHERE AGE = 25;
ROLLBACK;
Transaction Control Language
SAVEPOINT COMMAND:
It is used to roll the transaction back to a certain
point without rolling back the entire transaction.

Syntax:

SAVEPOINT SAVEPOINT_NAME;

Example :

SAVEPOINT S1;
Data Query Language
DQL is used to fetch the data from the database.

• It uses only one command:


• SELECT
This is the same as the projection operation of relational algebra. It is
used to select the attribute based on the condition described by WHERE
clause.
Syntax:

SELECT expressions
FROM TABLES
WHERE conditions;

Example:

SELECT emp_name
FROM employee
WHERE age > 20;
Practice Queries
Consider the table
Student (name, marks, dept, age, place, phone, birthdate)
Write SQL query for following :
(i) To list students having place as ‘Pune’ or ‘Jalgaon’.

(ii) To list students having same department (dept) as that of


‘Rachana’.

Select * from student where dept=


(Select dpet from student where name
=‘Rachana’);
Practice Queries
Consider following schema :
EMP (empno, deptno, ename, salary, designation,
join_date, DOB, dept_location). Write down SQL
queries for following :
(i) Display employees name & number in decreasing
order of salary.
(ii) Display employee name & employee number
whose designation is Manager.
(iii) Display age of employees with ename.
(iv) Display total salary of all employees.
(v) Display employee names having deptno as 20 and
dept_location is Mumbai.
(vi) Display name of employee who earned lowest
salary.
Practice Queries
Consider the structure for book table as Book-Master
(bookid, bookname, author, no_of copies, price)

Write down SQL queries for following


(i) Write a command to create Book_master table.
(ii) Get authorwise list of all books.
(iii) Display all books whose price is between ` 500 & `
800.
(iv) Display all books with details whose name start
with ‘D’.
(v) Display all books whose price is above ` 700.
(vi) Display all books whose number of copies are less
than 10.
Operators used in SQL

• Objectives

• How to use of operators in SQL Query


• Types of operators
• Example
SQL Operator

SQL Operators:
The SQL operators are used to perform operations
on data.
Types of Operators
 Arithmetic
ArithmeticOperators
Operators
 Comparison Operators
 Set Operators
 Range Searching Operators
 Pattern Marching Operators
SQL Operator : Arithmetic Operators
Arithmetic Operators:
To perform various arithmetic operations we use these
operators.
Result of arithmetic operators is numeric value.

Sr No. Symbol Operation


1 + Addition
2 - Subtraction
3 * Multiplication
4 / Division
5 % Mod
SQL Operator : Comparison Operators

Comparison Operators:
The comparison operator is used to compare
attribute value of tuple with arithmetic comparisons.
A comparison operator is a mathematical symbol
used to compare two values in mathematical
expression.
Comparison operators in conditions will be used to
evaluate expression.
Types of Comparison Operators
Sr No. Symbol Operation

1 = Equals to

2 < Less Then

3 <= Less Then Equal to

4 > Greater Then

5 >= Greater Then Equal to

6 <> Not Equal to


SQL Operator : Logical Operators

Logical Operators:

The logical operator will accept expression and


return result as true or false to combine one or more
true or false values.
Types of Logical Operators

Basically there are three types,


AND Operator :
Logical AND compares between two expressions to returns true
when both expressions are true otherwise false.

Syntax :
Select * from Table_name
where expression1 AND expression2;
Example:
Select * from emp
where address=‘Pune’ AND salary >50000;
Types of Logical Operators

Basically there are three types,


OR Operator :
Logical OR compares between tow expressions to return true
when one of the expression is true otherwise false.

Syntax :
Select * from Table_name
where expression1 OR expression2;
Example:
Select * from emp
where address=‘Pune’ OR salary >50000;
Types of Logical Operators

Basically there are three types,


NOT Operator :
Logical NOT takes a single expression and changes its value
from false to true or from true to false.

Syntax :
Select * from Table_name
where NOT expression;
Example:
Select * from emp
where NOT salary >50000;
SQL Operators : SET Operators

SET Operators:
The results of two queries can be combined using
the set operation
Types of Set Operators
 Union operation
 Intersect operation
 Except operation
 Nesting SET operation
Types of SET Operators

Basically there are three types,


UNION Operator :
Union effectively appends the result of Query2 the result of
Query1.
Furthermore it eliminates all duplicate rows using DISTINCT.
All: Duplicate row shown only once.
Syntax :
Select * from Table_name1 minus or except
Select * from Table_name2;
Example:
Select * from emp UNION
Table 1 Table 2
Select * from Dept;
Range Searching Operators
Between Operators:
The Between operator can be used to find out all
tuples whose attribute value is ganging between
given range of value.
Syntax :
Select * from Table_name1
where column name BETWEEN value1 AND value2;

Example:
Select * from emp
where eid between 1 and 4;
Pattern Matching Operators

Pattern Matching Operator : LIKE


Pattern matching statements are used to fine out particular
string in attribute value.
LIKE is a keyword that is used in the where clause for
pattern matching.
SQL given two wildcard characters for use with LIKE.
Percentage Sign(%):
The % sign means any string of zero or more characters.
It is used to define start and end of string.
Underscore Sign ( _ ):
The underscore sign means a single character.
It us used to determine letter at particular position.
Pattern Matching Operators
Syntax :
Select * from Table_name1
where column name LIKE(‘pattern’)

Example:
Select * from emp
Where EmpName LIKE ‘S%’;

Determine a string which end with a given letter.(‘%h’)


Determine a string contains given a letter.(’%a%’)
Find all employees whose names second letter is ‘a’ contains
letter ‘e’ and name ending with letter ‘h’.(‘_a%e%h’)
Find all employees whose names second letter is a(‘_a%’)
Find all employees whose names second last letter is a. (‘%s_’)
Find all faculties whose name do not contains ‘a’.(not
link’%a%)
Assignment No 1
Sr. No Questions

1 What is SQL? List its types.

2 State characteristics of SQL.

3 Explain data types used in SQL.

4 Explain DDL Commands with example.

5 Explain DML commands with example.

6 Explain Null and Not Null Constraints with example.

7 Explain Check constraints with example.


Assignment No 2
Sr. No Questions

1 Explain primary key constraints.

2 Explain GRANT and REVOKE commands with


example.
3 Explain All TCL commands.

4 Explain DQL Commands with it options.

5 Explain operators used in SQL.

6 Explain pattern matching operator with example.

You might also like