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

DBMS Unit4

beds

Uploaded by

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

DBMS Unit4

beds

Uploaded by

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

DBMS Unit 4

SQL stands for Structured Query Language which is a computer language for storing,
manipulating and retrieving data stored in a relational database. SQL was developed in the 1970s by
IBM Computer Scientists.SQL is a programming language for Relational Databases. It is designed
over relational algebra and tuple relational calculus. SQL comes as a package with all major
distributions of RDBMS.

SQL Advantages:
1.Allows users to access data in the relational database management systems.
2.Allows users to describe the data.
3.Allows users to define the data in a database and manipulate that data.
4.Allows users to create and drop databases and tables.
5.Allows users to create view, stored procedure, functions in a database.
6.Allows users to set permissions on tables, procedures and views.
Relation instance − A finite set of tuples in the relational database system represents relation instance.
Relation instances do not have duplicate tuples.
Relation schema − A relation schema describes the relation name (table name), attributes, and their
names.
Relation key − Each row has one or more attributes, known as relation key, which can identify the
row in the relation (table) uniquely.

Query is a set of SQL statements used to make changes in the tables of the database
The inner query is called subquery which is placed in the round parentheses after the WHERE clause,
HAVING clause, or FROM clause.

Correlated Subquery is a type of subquery.Correlated Subquery is different from the normal


subquery in terms of execution.In this query, the correlated subquery is evaluated once for each row
of the outer query.

SQL Languages: DDL,DML,DCL

1)Data Definition Language


SQL uses the following set of commands to define database schema −
1)CREATE:
Creates a new table or a view of a table in the database.
For example ;- CREATE TABLE STUDENT (ROLLNO INTEGER NOT NULL PRIMARY
KEY,NAME CHAR(20),COURSE CHAR(10), PLACE CHAR(20));
2)DROP:
Drops commands, views, tables, and databases from RDBMS.
For example−Drop table student;
3)ALTER:
Modifies database schema.
For example−
Alter table student add subject varchar;
4)CREATE VIEW:
5)RENAME:
Columns can be also be given new name with the use of ALTER TABLE.
ALTER TABLE table_name RENAME TO new_table_name;
2)Data Manipulation Language
SQL is equipped with data manipulation language (DML). DML modifies the database
instance by inserting, updating and deleting its data.
1)SELECT
SELECT − This is one of the fundamental query command of SQL. It is similar to the projection
operation of relational algebra. It selects the attributes based on the condition described by WHERE
clause.
WHERE − This clause defines predicate or conditions, which must match in order to qualify the
attributes to be projected.
For example −
Select author_name From book_author Where age > 50;
This command will yield the names of authors from the relation book_author whose age is
greater than 50.
2)INSERT
This command is used for inserting values into the rows of a table (relation).
Syntax−
INSERT INTO table (column1 [, column2, column3 ... ]) VALUES (value1 [, value2, value3 ... ])
Or
INSERT INTO table VALUES (value1, [value2, ... ])
For example −
INSERT INTO article(Author, Subject) VALUES ("anonymous", "computers");
3)UPDATE
This command is used for updating or modifying the values of columns in a table (relation).
Syntax −
UPDATE tablename SET columnname = value [, column_name = value ...] [WHERE condition]
For example −
UPDATE article SET Author="webmaster" WHERE Author="anonymous";
4)DELETE
This command is used for removing one or more rows from a table (relation).
Syntax −
DELETE FROM table_name [WHERE condition];
For example −
DELETE FROM article WHERE Author="unknown";
3)DCL - Data Control Language
DCL commands are used to enforce database security in a multiple user database
environment. Two types of DCL commands are GRANT and REVOKE. Only Database
Administrator's or owner's of the database object can provide/remove privileges on a database object.
SQL GRANT Command
SQL GRANT is a command used to provide access or privileges on the database objects to the users.
The Syntax for the GRANT command is:
GRANT privilege_name ON object_name TO {user_name |PUBLIC |role_name} [WITH GRANT
OPTION];
privilege_name is the access right or privilege granted to the user. Some of the access rights are ALL,
EXECUTE, and SELECT.
object_name is the name of an database object like TABLE, VIEW, STORED PROC and
SEQUENCE.
user_name is the name of the user to whom an access right is being granted.
user_name is the name of the user to whom an access right is being granted.
PUBLIC is used to grant access rights to all users.
ROLES are a set of privileges grouped together.
WITH GRANT OPTION - allows a user to grant access rights to other users.
For Example: GRANT SELECT ON employee TO user1; This command grants a SELECT
permission on employee table to user1.You should use the WITH GRANT option carefully because
for example if you GRANT SELECT privilege on employee table to user1 using the WITH GRANT
option, then user1 can GRANT SELECT privilege on employee table to another user, such as user2
etc. Later, if you REVOKE the SELECT privilege on employee from user1, still user2 will have
SELECT privilege on employee table.
SQL REVOKE Command:
The REVOKE command removes user access rights or privileges to the database objects.
The Syntax for the REVOKE command is:
REVOKE privilege_name ON object_name FROM {user_name |PUBLIC |role_name}
For Example: REVOKE SELECT ON employee FROM user1;This command will REVOKE a
SELECT privilege on employee table from user1.When you REVOKE SELECT privilege on a table
from a user, the user will not be able to SELECT data from that table anymore. However, if the user
has received SELECT privileges on that table from more than one users, he/she can SELECT from
that table until everyone who granted the permission revokes it. You cannot REVOKE privileges if
they were not initially granted by you.
Privileges and Roles:
Privileges: Privileges defines the access rights provided to a user on a database object. There are two
types of privileges.
1) System privileges - This allows the user to CREATE, ALTER, or DROP database objects.
2) Object privileges - This allows the user to EXECUTE, SELECT, INSERT, UPDATE, or DELETE
data from database objects to which the privileges apply.
Few CREATE system privileges are listed below:
System Privileges Description

CREATE object allows users to create the specified object in their own schema.

CREATE ANY object allows users to create the specified object in any schema.
The above rules also apply for ALTER and DROP system privileges.
Few of the object privileges are listed below:
Object Privileges Description
INSERT allows users to insert rows into a table.
SELECT allows users to select data from a database object.
UPDATE allows user to update data in a table.
EXECUTE allows user to execute a stored procedure or a function.
Roles: Roles are a collection of privileges or access rights. When there are many users in a database it
becomes difficult to grant or revoke privileges to users. Therefore, if you define roles, you can grant or
revoke privileges to users, thereby automatically granting or revoking privileges. You can either
create Roles or use the system roles pre-defined by oracle.
Some of the privileges granted to the system roles are as given below:
System Role Privileges Granted to the Role
CREATE TABLE, CREATE VIEW, CREATE SYNONYM, CREATE
CONNECT
SEQUENCE, CREATE SESSION etc.
CREATE PROCEDURE, CREATE SEQUENCE, CREATE TABLE, CREATE
RESOURCE TRIGGER etc. The primary usage of the RESOURCE role is to restrict access to
database objects.
DBA ALL SYSTEM PRIVILEGES
Creating Roles:
The Syntax to create a role is:
CREATE ROLE role_name [IDENTIFIED BY password];
For Example: To create a role called "developer" with password as "pwd",the code will be as follows
CREATE ROLE testing [IDENTIFIED BY pwd];
It's easier to GRANT or REVOKE privileges to the users through a role rather than assigning a
privilege directly to every user. If a role is identified by a password, then, when you GRANT or
REVOKE privileges to the role, you definitely have to identify it with the password.
We can GRANT or REVOKE privilege to a role as below.
For example: To grant CREATE TABLE privilege to a user by creating a testing role:
First, create a testing Role
CREATE ROLE testing
Second, grant a CREATE TABLE privilege to the ROLE testing. You can add more privileges to the
ROLE.
GRANT CREATE TABLE TO testing;
Third, grant the role to a user.
GRANT testing TO user1;
To revoke a CREATE TABLE privilege from testing ROLE, you can write:
REVOKE CREATE TABLE FROM testing;
The Syntax to drop a role from the database is as below:
DROP ROLE role_name;
For example: To drop a role called developer, you can write:
DROP ROLE testing;
Aggregate function:
1)SUM :It is used to return the sum of the values of a numeric type column.
SQL> SELECT SUM(MARK1) FROM STUDENT;
2)AVG :It is used to return the average value of the column.
SQL> SELECT AVG(MARK1) FROM STUDENT;
3)MIN :It is used to return the minimum value of an expression.
SQL>SELECT MIN(TOTAL)FROM STUDENT;
4)MAX : It is used to return the maximum value of an expression.

SQL>SELECT MAX(TOTAL)FROM STUDENT;


5)COUNT :It is used to return the number of rows where expression is not null.
SQL>SELECT COUNT(MARK1)FROM STUDENT;

Clauses used with SQL Commands:


LIKE : It is used along with SELECT Command and used for pattern matching % matches a string
and _ matches any single character.
SQL>SELECT ROLLNO,NAME FROM STUDENT WHERE NAME LIKE ‘A%’

ORDER BY: It is used to sort the data in ascending or descending order, based on one or more
columns.
SQL>SELECT * FORM STUDENT ORDER BY NAME;
SQL>SELECT * FROM STUDENT ORDER BY NAME DESC; (for descending order)

GROUP BY ,HAVING: The GROUP BY clause , group rows based on the distinct values that exists
for the specified columns.
SQL>SELECT COURSE,COUNT(*) FROM STUDENT GROUP BY COURSE HAVING
COURSE=’COMMERCE’;
Distinct is a keyword used with SELECT command to avoid duplication of rows in the selection.
A View is a virtual table that consists of columns from one or more tables. Though it is similar to a
table ,it is not physically stored in the database.
CREATE VIEW EMP1 AS SELECT * FROM EMP WHERE JOB = ‘CLERK’;
Like:
This Operator applies only to text fields .It searches a character field to see a part of it matches a
string supplied with LIKE.
SELECT * FROM EMP WHERE ENAME LIKE 'S%';
The above query displays details of employees whose name starts with the letter ‘S’
SQL Logical Operators
1.ALL
The ALL operator is used to compare a value to all values in another value set.
2.AND
The AND operator allows the existence of multiple conditions in an SQL statement's WHERE clause.
3.ANY
The ANY operator is used to compare a value to any applicable value in the list as per the condition.
4.BETWEEN
The BETWEEN operator is used to search for values that are within a set of values, given the
minimum value and the maximum value.
5.EXISTS
The EXISTS operator is used to search for the presence of a row in a specified table that meets a
certain criterion.
6.IN
The IN operator is used to compare a value to a list of literal values that have been specified
7.LIKE
The LIKE operator is used to compare a value to similar values using wildcard operators.
8.NOT
The NOT operator reverses the meaning of the logical operator with which it is used. Eg: NOT
EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.
9.OR
The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause.
10.IS NULL
The NULL operator is used to compare a value with a NULL value.
11.UNIQUE
The UNIQUE operator searches every row of a specified table for uniqueness (no duplicates).

SQL Constraints:
Constraints are the rules enforced on data columns on table. These are used to limit the type of data
that can go into a table. This ensures the accuracy and reliability of the data in the database.
Constraints could be column level or table level. Column level constraints are applied only to one
column where as table level constraints are applied to the whole table.
Following are commonly used constraints available in SQL:
▪ NOT NULL Constraint: Ensures that a column cannot have NULL value.
▪ DEFAULT Constraint: Provides a default value for a column when none is specified.
▪ UNIQUE Constraint: Ensures that all values in a column are different.
▪ PRIMARY Key: Uniquely identified each rows/records in a database table.
▪ FOREIGN Key: Uniquely identified a rows/records in any another database table.
▪ CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy certain
conditions.
Join in SQL
SQL Join is used to fetch data from two or more tables, which is joined to appear as single set
of data. SQL Join is used for combining column from two or more tables by using values common to
both tables. Join Keyword is used in SQL queries for joining two or more tables. Minimum required
condition for joining table, is (n-1) where n, is number of tables. A table can also join to itself known
as, Self Join.
Types of Join
The following are the types of JOIN that we can use in SQL.
 Cross join
 Inner join
1.Natural join
 Outer
1.Left outer join
2.Right outer join
3.Full outer join
Cross JOIN or Cartesian Product
This type of JOIN returns the Cartesian product of rows from the tables in Join. It will return a table
which consists of records which combines each row from the first table with each row of the second
table.
Cross JOIN Syntax is,
SELECT column-name-list from table-name1 CROSS JOIN table-name2;
INNER Join or EQUI Join
This is a simple JOIN in which the result is based on matched data as per the equality condition
specified in the query.
Student Class
Regno Name
Regno Place
100 A
100 Calicut
101 B
101 Malappuram
102 C
102 Thrissur
103 D
The resulting table is
Reg Na Reg Place
no me no
100 A 100 Calicut
101 B 101 Malappuram
102 C 102 Thrissur

Inner Join Syntax is,


SELECT column-name-list from table-name1 INNER JOIN table-name2 WHERE table-
name1.column-name = table-name2.column-name;
Natural JOIN
Natural Join is a type of Inner join which is based on column having same name and same datatype
present in both the tables to be joined.
Using the above example,The resulting table is
Regno Name Place
100 A Calicut
101 B Malappuram
102 C Thrissur

Natural Join Syntax is,


SELECT *from table-name1 NATURAL JOIN table-name2;
Outer JOIN
Outer Join is based on both matched and unmatched data. Outer Joins subdivide further into,
Left Outer Join,Right Outer Join,Full Outer Join
Left Outer Join
The left outer join returns a result table with the matched data of two tables then remaining
rows of the left table and null for the right table's column.
Student Class
Regno Place
Regno Name 100 Malappuram
100 A 101 Thrissur
101 B 102 Calicut
102 C 105 Palakkad
103 D 107 Kannur
104 E
The resulting table is
Regno Name Regno Place
100 A 100 Malappuram
101 B 101 Thrissur
102 C 102 Calicut
103 D Null Null
104 E Null Null
Left Outer Join syntax is,
SELECT column-name-list from table-name1 LEFT OUTER JOIN table-name2 on table-
name1.column-name = table-name2.column-name;
Right Outer Join
The right outer join returns a result table with the matched data of two tables then remaining
rows of the right table and null for the left table's columns.
Using the above example,The resulting table is
Regno Name Regno Place
100 A 100 Malappuram
101 B 101 Thrissur
102 C 102 Calicut
Null Null 105 Palakkad
Null Null 107 Kannur

Right Outer Join Syntax is,


select column-name-list from table-name1 RIGHT OUTER JOIN table-name2on table-name1.column-
name = table-name2.column-name;
Full Outer Join
The full outer join returns a result table with the matched data of two table then remaining
rows of both left table and then the right table.
Using the above example, The resulting table is
Regno Name Regno Place
100 A 100 Malappuram
101 B 101 Thrissur
102 C 102 Calicut
103 D Null Null
104 E Null Null
Null Null 105 Palakkad
Null Null 107 Kannur

Full Outer Join Syntax is,


select column-name-list from table-name1 FULL OUTER JOIN table-name2on table-
name1.column-name = table-name2.column-name;
Built-in Functions
1.String Functions
CHAR -Returns a character for an ASCII value.
LEN-Returns a specified number of characters from a character string.
LOWER-Converts a string to lower case.
UPPER-Returns a string of repeated spaces.
SPACE-Returns a string of repeated spaces.
2.DateTime Functions
DATEDIFF-Returns the difference in datepart between two given dates.
DAY-Returns the Day as an integer representing the Day part of a specified date.
MONTH-Returns the Month as an integer representing the Month part of a specified date.
YEAR-Returns the Year as an integer representing the Year part of a ISDATE-specified date.
Determines whether the input is a valid date, time or datetime value.
3.Numeric Functions
ABS-Returns the absolute value of a number.
AVG-Returns the average value of an expression/column values.
COUNT-Returns the number of records
MAX-Returns the maximum value in an expression.
MIN-Returns the minimum value in an expression.
SUM-Returns the sum of all the value

You might also like