DBMS_bcom_unit-4
DBMS_bcom_unit-4
Features of SQL
1. SQL can be used by a range of users, including those with little or no
programming experience.
2. It is a non procedural language.
3. It reduces the amount of time required for creating and maintaining
systems.
4. It is an English like language.
tables
sequences
views
Database
indexes
synonyms
Advantages of SQL
DBMS Page 1
Reduced training costs: Training in an organization can concentrate on one
language. A large number of professional trained in a common language reduces
retraining when hiring new employee.
Productivity: Professional can learn SQL thoroughly and become proficient with it
from continued use. The company can invest more to help professional become more
productive.
Application Portability: Application can moved from machine to machine when
each machine uses SQL. Also it is economical for the computer software industry to
develop off the self application software when there is a standard language.
Application Longevity: a standard language tends to remain so for a long time ,
hence there will be little pressure to rewrite old application . rather application will be
simply be updated as the standard language is enhanced or new versions of DBMSs
are introduced.
Reduced dependence on a single vendor: when a non proprietary language is used ,
it is easier to use different vendors for the DBMS , training and educational services ,
application software etc.
Cross System Communication: different DBMSs application program can more
easily communicate and cooperate in managing data and processing user programs .
DDL commands
SQL includes commands to create database objects such as tables, indexes and
views as well as commands to define access rights to those database objects. The SQL
DDL provides commands for defining relation schemas, deleting relations , modifying
relation schemas The data definition commands are as follows.
CREATE: This command is used to create database objects like tables, views,
indexes, sequences etc.
Syntax:
create table tablename(col1 datatype(size),col2 datatype(size)…);
create view viewname as select query;
ex:
create table emp(eno number(4),name varchar2(10),sal number(8,2));
create view empview as select * from emp;
ALTER:
DBMS Page 2
Alter command is used to modifying the structure of the table. we can alter an
existing table by adding one or more columns. Occasionally you might want to
modify a table by deleting a column.
Syntax:
alter table tablename add col datatype(size);
alter table tablename drop colname;
Ex:
alter table emp add hra number(8,2);
alter table emp drop hra;
DROP:
This command is used to delete the database object like table, view, index
sequence etc.. from the database permanently.
Syntax:
drop table tablename;
drop view viewname;
Ex:
drop table emp;
drop view empview;
TRUNCATE:
This command is used to delete a table from the database but only difference
between drop and truncate is drop command delete the values along with structure but
truncate command deletes only values but not the structure . we can access the deleted
table using rollback if it is deleted by truncate . It is not possible by drop.
Syntax:
truncate table tablename;
Ex: truncate table emp;
RENAME:
It is used to change the name of the table from one name to another.
Syntax:
rename oldname to newname;
Ex: rename employee to emp;
CREATE DATABASE:
DBMS Page 3
When we create a new database the RDBMS creates the physical files that will
hold the database. when we create a new database the RDBMS automatically create
the data dictionary tables to store the metadata.
Syntax:
create database databasename;
Ex: create database Bsc;
Database Schema:
A schema is a group of database objects such as tables and indexes that are
related to each other. Usually , the schema belongs to a single user or application. A
single database can hold schemas belonging to different users or schemas. It can be
considered as a logical grouping of database objects such as tables, views and
indexes.
Syntax:
create schema authorization{creator};
Ex:
create schema authorization bsc;
DML commands
Data manipulation language (DML) statements are used for managing data
within schema objects. The basic SQL data manipulation commands are as follows
insert
select
commit
update
rollback
delete
Insert
This command is used to enter data into a table. The insert command basic
syntax as follows
Syntax:
Insert into tablename values(val1,val2,val3…);
The SQL insert into clause has actually two parts, the first specifying the table we are
inserting into and giving the list of columns we are inserting values for, and the
DBMS Page 4
second specifying the values inserted in the column list from the first part. While
inserting a row , if you are adding value for all the columns of the table you need not
specify the columns name in the sql query. But you need to make sure the order of the
values is in the same order as the columns in the table. The sql insert query will be as
follows.
Ex: insert into student values(111,’rama’,’bsc’,87,78,93);
Select
The most commonly used SQL command is select command. The SQL select
command is used to retrieve data from database object like table or view in the
database.
Syntax :
Select columnlist from table_name;
The columnlist represents one or more attributes, separated by commas.
Syntax:
Select <col list>from<table_name>[where clause][group by clause][having
clause][order by clause]
table_name is the name of the table from which the information is retrieved.
Col list includes one or more columns from which data is retrieved.
Code with in the brackets is optional.
We could use the *(asterisk) as a wildcard character to list all attributes. A wild
character is a symbol that can be used as a general substitute for other characters or
commands.
Ex:
select * from student;
commit:
Any changes made to the table contents are not saved on disk until you close
the database, close the program you are using, or use the commit command. If the
database is open and a power outage or some other interruption occurs before you
issue the commit command, your changes will be lost and only the original table
contents will be retained.
Syntax:
Commit[work];
Ex: commit;
Update
Update command is used to modify data in a table.
DBMS Page 5
Syntax :
Update <table_name>set col1=val1,col2=val2…[where conditionlist];
If you don’t specify a where condition, the update command will apply the changes to
all rows in the specified table. Confirm the corrections by using select command.
Ex
Update student set total=m1+m2+m3;
Update emp set sal=sal+sal*0.2 where sal<10000;
Rollback
If you have not yet used the commit command to store the changes
permanently in the database, you can restore the database to its previous condition
with the rollback command. Rollback undoes any changes since the last commit
command and brings the data back to the values that existed before the changes were
made.
Syntax:
Rollback;
Delete
Delete command is used to delete rows from atable.
Syntax:
Delete from table_name [where condition_list];
The delete command is a set oriented command. And the where condition is optional .
therefore , if you do not specify a where condition , all rows from the specified table
will be deleted.
Ex:
Delete from student where sno=111;
Delete from student;
Data types available in SQL
SQL data takes shape in several different forms, including character strings,
numbers, file stores and dates. SQL developers call the shots as to what types of data
will be stored inside each and every table column when creating a SQL table. The
developer must specify the column type of each new SQL table column.
Data types
DBMS Page 6
Character Number Date & Time
Long
DBMS Page 7
length semantics is the default and only length semantics for NCHAR and
NVARCHAR2.
Number Datatype
The NUMBER datatype stores fixed and floating point numbers. Numbers of virtually
any magnitude can be stored and are guaranteed portable among different systems
operating database , up to 38 digits of precision.
The following numbers can be stored in a NUMBER column.
Positive numbers.
Negative numbers.
Zero
Positive and negative infinity.
Date Datatype
The DATE data type stores point in time values(dates and times) in a table. The Date
data type stores the year, the month, the day, the hours, the minutes, and the seconds.
BLOB datatype(Binary Large Object)
The BLOB datatype stores unstructured binary data in the database . BLOBs can store
up to 128 TB of binary data.
BLOBS participate fully in transactions . changes made to a BLOB value by the
DBMS_LOB package,PL/SQL, or the OCI can be committed or rolled back.
LONG datatype
The LONG data type stores variable length character strings. When you create a table
with a LONG column, you specify a maximum string length(in bytes or characters)
between 1 byte and 4 GB for the LONG column. Maximum one per table.
Select query/Select Statement:
The most commonly used SQL command is select command. The SQL select
statement is used to query or retrieve data from a table in the database. A query may
retrieve information from from specified columns or from all of the columns in the
table.
Syntax:
Select column_list from tablelist
[where conditionlist]
[group by clause]
[having clause]
[order by clause]
DBMS Page 8
The code within the brackets is optional
From: identifies the tables or views from which columns will be chosen to appear in
the result table, and includes the tables or views needed to join tables to process the
query.
Where: Includes the conditions for row selection within a single table or view , and
the conditions between tables or views for joining.
Group by: this clause is used along with the group functions to retrieve data grouped
according to one or more columns.
Having: it is used to filter data based on the group functions.
Order by: It is used to sort results either in ascending or descending order.
Ex: select * from student where total>450;
SQL Operators:
There are two types of operators, namely comparison operators and logical
operators. These operators are mainly used in the where clause, having clause to filter
the data to be selected.
Comparison operators: these operators are used to compare the column data with
specific values in a condition.
Symbol Meaning
= Equal to
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
<> or != Not equal to
Logical Operators:
SQL allows you to have multiple conditions in a query through the use of
logical operators. The logical operators are AND, OR and NOT.
Operator description
AND for a row to be selected all the specified conditions must be true.
OR for a row to be selected at least one of the conditions must be true.
NOT for a row to be selected the specified condition must be false.
SQL comparison keywords :
There are other comparison keywords available in SQL which are used to
enhance the search capabilities of a SQL query. They are ‘IN’, ‘BETWEEN’, ‘IS
NULL’, ‘LIKE’.
DBMS Page 9
IN used to check whether an attribute value matches any value
with in a value list.
The alter table command can also be used to add table constraints. In those cases
syntax
alter table <tablename>add constraint[add constraint];
DBMS Page 10
Ex:
alter table student add primary key(sno);
We could also use the alter table command to remove a column or table constraint .
Syntax:
alter table <tablename>drop{primary key |column columnname|constraint
constraintname};
Ex:
alter table student drop primarykey;
Note: when removing a constraint we need to specify the name given to the
constraint.
Functions available in SQL
Functions in SQL enable you to perform calculations such as determining the
sum of a column or converting all the characters of a string to uppercase or
lowercase . types of functions available in SQL as follows.
Aggregate functions
Date and Time functions
Numeric functions
String functions
Conversion functions
Aggregate functions
aggregate functions are also called as group functions. They return a value
based on the values in a column.
COUNT
The count function is used to tally the number of non null values of an
attribute. that means it returns the number of rows in the table that satisfies the
condition specified in the where clause. If the where condition is not specified then
the query returns the total number of rows in the table.
DBMS Page 11
Ex:
Select count(*) from student;
SUM
It computes the total sum for any specified attribute, using whatever
condition(s) we have imposed.
Ex:
Select sum(sal) as total_sal from emp;
AVG
DBMS Page 12
This function is used to return the date of the last day of the month given in a
day or last day of a specified month .
Syntax: LAST_DAY(date_value);
Ex:
Select dob, last_day(dob) from student;
MONTHS_BETWEEN
If we want to know how many months fall between month M1 and month M2
we can use MONTHS_BETWEEN function.
Syntax : MONTHS_BETWEEN(M1,M2);
Ex:
Select copen, cclose, months_between(copen,cclose)as academic from college;
Copen- college open date, cclose- college closing date
NEXT_DAY
This function finds the name of the first day of the week that is equal to or
later than another specified date.
Ex: select dob, next_day(dob) from student;
SYSDATE
It returns current system date and time
Numeric Functions: Numeric functions can be grouped in many different
ways such as algebraic, trigonometric, and logarithmic. Numeric functions take one
numeric parameter and return one value.
ABS
The ABS function returns the absolute value of a number you point to.
Syntax: ABS(numeric_value);
Ex: select abs(-1.9) as absolute from dual;
ROUND
It rounds a value to a specified precision
Syntax: ROUND(num_val)
Ex: select eno, name, round(sal,0) from emp;
CEIL and FLOOR
Ceil returns the smallest integer greater than or equal to its argument. Floor
does just the reverse, returns the largest integer equal to or less than its argument .
Syntax: CEIL(num_val), FLOOR(num_val)
Ex: select avg_marks, ceil(avg_marks), floor(avg_marks) from marks;
DBMS Page 13
POWER
We can use power function to raise one number to the power of another. In
this function the first num is raised to the power of the second.
Select x,y,power(x,y) from dual;
SQRT
The function sqrt returns the square root of the given number. You can not use
this function for negative numbers, because the square root of a negative number is
undefined.
Select x, sqrt(x) from dual;
String Functions
SQL provides many functions to manipulate characters and strings.
CHR
It returns the character equivalent of the number it uses as an argument. The
character it returns depends on the character set of the database. For this example the
database is set to ASCII. The column sno includes numbers.
Select sno, chr(sno) from characters;
CONCAT
The || symbol splices two strings together , as does concat.
Select concat(fname,lname) from dual;
INITCAP
It capitalizes the first letter of a word and makes all other characters
lowercase.
Select sname, initcap(sname) from student;
UPPER and LOWER
Upper returns a string in all capital letters and lower returns a string in all
lowercase letters.
Select upper(sname) from emp;
Select lower(sname) from emp;
SUBSTR
It returns a substring or part of a given string parameter .
Syntax : substr(str_val,p,l);
In the above syntax the first argument is the string value , the second
argument is the position of the first character to be output and third argument
is the number of characters to be select.
DBMS Page 14
LENGTH
It returns the number of characters in a string value.
Syntax: length(string);
Ex: select ename, length(ename) from emp;
Conversion Functions:
TO_CHAR
This function is used to convert a number into character.
Syntax: TO_CHAR(numeric_val,format)
TO_NUMBER
Returns a formatted number from a character string , using a given format.
Syntax: TO_NUMBER(char_val,format)
DBMS Page 15
Virtual tables or Views in SQL
A view is a virtual table, which is based on select query. The query can
contain columns, computed columns, aliases, aggregate functions from one or more
tables. The views data is generated dynamically when the view is refreshed. We can
create a view by using the CREATE VIEW command.
Syntax:
Create view <view_name>as select query
Create view <view_name>as <col_list>from<table_name>[where condition];
Ex:
Create view empview as select * from emp where sal>10000;
Advantages:
Security:
Views provide a level of security in the database because the view can restrict
users to only specified columns and specified rows in a table. A user can be permitted
to access the database, only through a small set of views that contain the specific data
the user is authorized to see.
Query simplicity:
A view can draw data from several different tables and present it as single
table, thus effectively turning multi table queries into single table queries.
Structural simplicity:
Views can give a user , a personalized view of the database structure ,
presenting the database as a set of virtual tables that make sense to the user.
Data integrity:
if data is accessed and entered through a view , the DBMS can automatically
check the data to ensure that it meets specified integrity constraints.
Disadvantages:
Performance:
the DBMS translates the queries against the view into queries against the
underlying source tables. If a view is defined by a multi table query, then even a
simple query against view becomes a complicated join and it may take a long time to
complete.
Update restrictions:
When a user tries to update rows of a view, the DBMS must translate the
request into an update on rows of the underlying source tables. This is possible for
simple views, but more complicated views can’t be updated.
Drop view:
This command is used to drop a view.
Syntax: drop view <view_name>;
Ex: drop view emp_view;
DBMS Page 16
Relational set operators available in SQL
Relational set operators are used to combines results from two or more
queries, using some relation between them.
In SQL we have UNION, INTERSECT, MINUS to implement the union, intersect
and difference relational operators. UNION, INTERSECT, MINUS work properly
only if relations are union compatible i.e all the statements concatenated with sets
must have the same structure. This means that they need to have the same number of
columns and corresponding columns must have the same or compatible data types .
UNION
The union statement combines rows from two or more queries without
including duplicate rows .
Syntax: query1 union query2;
Select <col_list> from tabl1 union select <col_list> from table2;
Ex:
Select * from student1
Union
select * from student2;
The column names in the result of a union are always the same as the column names
in the first select statement in the union.
UNION ALL
The union operator by default removes duplicate rows from the result set. The
union all query can be used to produce a relation that retains the duplicate rows.
Syntax:
Query1 union all Query2;
Select<col_list> from table1 union all select <col_list> from table2;
Ex:
Select * from student1
union all
select * from student2;
INTERSECT
The intersect statement can be used to combine rows from two queries,
returning only the rows that appear in both sets.
Syntax:
Query1 intersect Query2;
DBMS Page 17
Select <col_list>from table1 intersect select<col_list>from table2;
Ex:
Select * from student1
intersect
select * from student2;
MINUS
The minus statement in SQL combines rows from two queries and returns only
the rows that appear in the first set but not in the second set.
Syntax:
Query1 minus Query2;
Select<col_list>from table1 minus select <col_list>from table2;
Ex:
Select * from student1
Minus
Select * from student2;
Different constraints that can be placed on a SQL table
Constraints are used to limit the type of data that can go into a table.
Constraints can be specified when a table is created(with the create table statement)or
after the table is created(with the alter table statement).
Table level and column level constraints:
The table level constraints are part of the table definition. An integrity
constraint defined at the table level can impose rules on any column in the table
whereas column level constraint being a part of the column definition can be imposed
only on the column on which it is defined.
Syntax:
create table <table name>(col1 datatype[column constraint],…..[table constraint][…..]
);
Not null constraint
By default all columns in a table allow Null values. The not null specification
for the attributes ensure that a data entry will be made.when it is crucial to have the
data available, the not null specification will not allow the end user to leave the
attribute empty.because this specification is made at the table leveland stored in the
data dictionary,application programs can use this information to create the data
DBMS Page 18
dictionary validation automatically. Not null constraint can be given only at column
level and not at the table level.
Ex: name varchar2(10)not null
Unique constraint
The unique specification creates a unique indexe in the respective
attribute.This constraint is used to prevent the duplication of values within the rows of
a specified column or a set of columns in a table. Columns defined with this constraint
can also allow null values. If unique constraint is defined in more than one column, it
is said to be composite unique key.
Syntax: colname datatype[unique]
Ex: sno number(5)unique
Default constraint
Default constraint specifies default value of a particular column. The default
constraint assigns a value to an attribute when a new row is added to a table . the end
user may , of course , enter a value other than the default value.
Ex: tot number(4)default 0
Check constraint
The check constraint is used to validate data when an attribute value is
entered. The check constraint does precisely what its name suggests, it checks to see
that a specified condition exists.
Ex: sal number(8,2)check sal>10000
If the check constraint is met for the specified attribute (i.e the condition is true), the
data are accepted for that attribute. If the condition is found false, an error message is
generated and the data are not accepted.
Primary key constraint
A primary key is used to identify uniquely each row in a table. The primary
key can consist of one or more fields on a table. The primary key attributes contains
both a not null and a unique specification. When multiple fields are used as a primary
key , they are called a composite key.
Syntax: colname datatype[primary key]
Ex: sno number(5) primary key
Foreign key constraint
The referential integrity constraint enforces relationship between tables. It
designates a column or combination of columns as a foreign key. The foreign key
establishes a relationship with a specified primary key or unique key in another table,
DBMS Page 19
called the referenced key. In this relationship,the table containing the foreign key is
called the child table and the table containing the referenced key is called the parent
table.
To implement this the common column must be defined in the parent table as
a primary key and in the child table as a foreign key.
Ex: deptno number(5)references emp(deptno)
DBMS Page 20
DBMS Page 21