SQL & PL/SQL: Commands and Concepts
SQL & PL/SQL: Commands and Concepts
Systems
If the variable stored for name is ‘Sanjay’ the extra 43 fields are
padded with blanks
String Data
• Variable Length string is specified with maximum length of
characters possible in the string, however, the allocation is sized
to the size of the data stored in memory.
• Syntax:
Varchar(n) – n is the maximum length of data possible for the type
There may be a restriction in the maximum length of the data that you
can specify in the declaration which will vary according to the
database.
All character data has to be enclosed in single quotes during
specification.
Numeric Data Types
• Store all the data related to purely numeric data.
• Some numeric data may also be stored as a character field e.g. zip
codes
• Common Numeric Types:
– Decimal Floating point number
– Float Floating point number
– Integer(size) Integer of specified length
– Money A number which contains exactly two
digits after the decimal point
– Number A standard number field that can hold
a floating point data
Note: Different databases name their numeric fields differently and may
not support all numeric types. They may also support additional
numeric types.
Temporal Data Types
• These represent the dates and time:
• Three basic types are supported:
– Dates
– Times
– Date-Time Combinations
Large Data Objects
• These are used for storing data objects like files and images:
• There are two types:
– Character Large Objects (clobs)
– Binary Large Objects (blobs)
Alter Statement
• Alter Statement:
– used to make changes to the schema of the table. Columns can be
added and the data type of the columns changed as long as the
data in those columns conforms to the data type specified.
• Syntax:
ALTER TABLE table_name
ADD column_name datatype;
• Example:
ALTER TABLE stud
ADD (Age number(2),
ADD Mark1 number(3),
ADD Mark2 number(3));
The stud table is already exist and then we added three more
columns Age ,Mark1 and Mark2 respectively, by the use of above
command.
Alter Statement(contd..)
2. ALTER TABLE - DROP COLUMN
• Syntax:
ALTER TABLE table_name
DROP COLUMN column_name;
• Example:
ALTER TABLE stud
DROP COLUMN Mark2;
This command will drop particular column mark2.
• Syntax:
DROP TABLE table_name;
• Example:
DROP TABLE stud;
This will destroy the table and all data which will be recorded in
it.
Truncate Table Statement
TRUNCATE TABLE
-Truncates the contents in an existing table in a database.
• Syntax:
TRUNCATE TABLE table_name;
• Example:
TRUNCATE TABLE stud;
This will delete the contents in the table. But structure remains
the same
Rename Table Statement
RENAME TABLE
-Truncates the contents in an existing table in a database.
• Syntax:
RENAME OldTableName
TO NewTableName;
• Example:
RENAME stud
TO student;
The old name table was stud now new name is the student.
DML-Data Manipulation
Language
Select Statement
• To display only selected fields
Syntax:
SELECT column1, column2, ... FROM table_name;
Here, column1, column2, ... are the field names of the table you want
to select data from
Example
SELECT name, age FROM stud;
• foreign key (Ak1 , Ak2, . . . , Akn ) references s: The values of attributes (Ak1 ,
Ak2, . . . , Akn ) for any tuple in the relation must correspond to values of the
primary key attributes of some tuple in relation s.
Constraints
Example:
create table department
(dept name varchar (20),
building varchar (15),
budget numeric (12,2),
primary key (dept name));
Example:
create table instructor
(ID varchar (5),
name varchar (20) not null,
dept name varchar (20),
salary numeric (8,2),
primary key (ID),
foreign key (dept name) references department);
Constraints
Unique Constraint
• unique (Aj1 , Aj2, . . . , Ajm )
• attributes Aj1 , Aj2, . . . , Ajm form a candidate
key; that is, no two tuples in the relation can be
equal on all the listed attributes.
Constraints
The check Clause
• The clause check(P) specifies a predicate P that must be satisfied by every
tuple in a relation.
• ensure that attribute values satisfy specified conditions
• Example:
create table section
(course id varchar (8),
sec id varchar (8),
semester varchar (6),
year numeric (4,0),
building varchar (15),
room number varchar (7),
time slot id varchar (4),
primary key (course id, sec id, semester, year),
check (semester in (’Fall’, ’Winter’, ’Spring’, ’Summer’)));
Constraints
Referential Integrity
• ensure that a value in one relation for a given set of attributes also appears for
a certain set of attributes in another relation.
• Foreign keys can be specified as part of the SQL create table statement by
using the foreign key clause
• Example: “foreign key (dept name) references department”
• Let r1 and r2 be relations whose set of attributes are R1 and R2, respectively,
with primary keys K1 and K2. The subset of R2 is a foreign key referencing K1
in relation r1 if it is required that, for every tuple t2 in r2, there must be a
tuple t1 in r1 such that t1.K1 = t2..
Constraints
Referential Integrity
create table department
(dept name varchar (20),
building varchar (15),
budget numeric (12,2) check (budget > 0),
primary key (dept name))
SELECT Name,
ABS(500 - ReorderPoint)
ReorderPointDeviation
FROM
production.Product
WHERE ABS(500 -
ReorderPoint) > 200
Function Categories
Numeric Functions – perform advanced calculations and round numbers.
String Functions – change text values to all upper case, or remove the
trailing spaces from values.
Conversion Functions – Convert data with CAST and CONVERT
Group Functions- functions that operate on groups of rows and return one
value for the entire group
Date Functions – add days or months to a date. Calculate the day of the
week from the date.
Numeric Functions
Function Input Argument Value Returned
ABS ( m ) m = value Absolute value of m
MOD ( m, n ) m = value, n = divisor Remainder of m divided by n
POWER ( m, n ) m = value, n = exponent m raised to the nth power
ROUND ( m [, n ] ) m = value, n = number of decimal places, default 0 m rounded to the nth decimal place
TRUNC ( m [, n ] ) m = value, n = number of decimal places, default 0 m truncated to the nth decimal place
SIN ( n ) n = angle expressed in radians sine (n)
COS ( n ) n = angle expressed in radians cosine (n)
TAN ( n ) n = angle expressed in radians tan (n)
ASIN ( n ) n is in the range -1 to +1 arc sine of n in the range -π/2 to +π/2
ACOS ( n ) n is in the range -1 to +1 arc cosine of n in the range 0 to π
ATAN ( n ) n is unbounded arc tangent of n in the range -π/2 to + π/2
SINH ( n ) n = value hyperbolic sine of n
COSH ( n ) n = value hyperbolic cosine of n
TANH ( n ) n = value hyperbolic tangent of n
SQRT ( n ) n = value positive square root of n
EXP ( n ) n = value e raised to the power n
LN ( n ) n>0 natural logarithm of n
LOG ( n2, n1 ) base n2 any positive value other than 0 or 1, n1 any positive value logarithm of n1, base n2
CEIL ( n ) n = value smallest integer greater than or equal to n
FLOOR ( n ) n = value greatest integer smaller than or equal to n
SIGN ( n ) n = value -1 if n < 0, 0 if n = 0, and 1 if n > 0
Here are some examples of the use of some of these numeric functions:
select
• String Functions
Function Input Argument Value Returned
LPAD ( s1, n [, s2] ) s1 and s2 are character strings and n is an integer value Returns s1 right justified and padded left with n
characters from s2; s2 defaults to space.
RPAD ( s1, n [, s2] ) s1 and s2 are character strings and n is an integer value Returns s1 left justified and padded right with n
characters from s2; s2 defaults to space.
LTRIM ( s [, set ] ) s is a character string and set is a set of characters Returns s with characters removed up to the first
character not in set; defaults to space
RTRIM ( s [, set ] ) s is a character string and set is a set of characters Returns s with final characters removed after the
last character not in set; defaults to space
String Functions
Returns s with every occurrence of search_s
REPLACE ( s, search_s [, s = character string, search_s = target string,
in s replaced by replace_s; default removes
replace_s ] ) replace_s = replacement string
search_s
Returns a substring from s, beginning in
SUBSTR ( s, m [, n ] ) s = character string, m = beginning position, n = position m and n characters long; default
number of characters returns to end of s.
LENGTH ( s ) s = character string Returns the number of characters in s.
Returns the position of the nth occurrence of
INSTR ( s1, s2 [, m [, n ] ] ) s1 and s2 are character strings, m = beginning
s2 in s1, beginning at position m, both m and
position, n = occurrence of s2 in s1
n default to 1.
select initcap ("now is the time for all good men to come to the aid
of the party") as "SLOGAN" from dual;
TO_CHAR ( m [, fmt ] ) m = numeric value, fmt = format Number m converted to character string as specified by
the format
TO_NUMBER ( s [, fmt ] ) s = character string, fmt = format Character string s converted to a number as specified by
the format
CORR ( e1, e2 ) e1 and e2 are column names Correlation coefficient between the two
columns after eliminating nulls
MEDIAN ( col ) col = column name Middle value in the sorted column,
interpolating if necessary
STDDEV ( [ DISTINCT | ALL ] col ) col = column name Standard deviation of the column ignoring
NULL values
VARIANCE ( [ DISTINCT | ALL ] col ) col = column name Variance of the column ignoring NULL
values
SQL AVG():
This function is used to get the average value of a numeric column.
To get the average salary, the query would be
SELECT AVG (salary) FROM employee;
NEW_TIME ( d, a, b ) d = date, a = time zone (char), b = time The date and time in time zone b when date d
zone (char) is for time zone a
NEXT_DAY ( d, day ) d = date, day = day of the week Date of the first day of the week after d
SYSDATE none Current date and time
GREATEST ( d1, d2, ..., dn ) d1 ... dn = list of dates Latest of the given dates
LEAST ( d1, d2, ..., dn ) d1 ... dn = list of dates Earliest of the given dates
TO_CHAR ( d [, fmt ] ) d = date value, fmt = format for string The date d converted to a string in the
given format
TO_DATE ( s [, fmt ] ) s = character string, fmt = format for date String s converted to a date value
ROUND ( d [, fmt ] ) d = date value, fmt = format for string Date d rounded as specified by the
format
TRUNC ( d [, fmt ] ) d = date value, fmt = format for string Date d truncated as specified by the
format
Date Formats
Format Code Description Range of Values
DD Day of the month 1 - 31
DY Name of the day in 3 uppercase letters SUN, ..., SAT
DAY Complete name of the day in uppercase, padded to 9 characters SUNDAY, ..., SATURDAY
MM Number of the month 1 - 12
MON Name of the month in 3 uppercase letters JAN, ..., DEC
MONTH Name of the month in uppercase padded to a length of 9 characters JANUARY, ..., DECEMBER
RM Roman numeral for the month I, ..., XII
YY or YYYY Two or four digit year 71 or 1971
HH:MI:SS Hours : Minutes : Seconds 10:28:53
HH 12 or HH 24 Hour displayed in 12 or 24 hour format 1 - 12 or 1 - 24
MI Minutes of the hour 0 - 59
SS Seconds of the minute 0 - 59
AM or PM Meridian indicator AM or PM
SP A suffix that forces the number to be spelled out. e.g. TWO THOUSAND NINE
TH A suffix meaning that the ordinal number is to be added e.g. 1st, 2nd, 3rd, ...
FM Prefix to DAY or MONTH or YEAR to suppress padding e.g. MONDAY with no extra spaces at the end
Here are some examples of the use of the Date functions:
Unit 3 DBMS
Subqueries
• A query can be processed inside another
query.
• A subquery is select statement that is
embedded in the clause of another select
statement
• Inner query and outer query : inner query
returns a value that is used by outer query.
Unit 3 DBMS
Syntax for subquery
Unit 3 DBMS
Ex..
• Who is earning more salary than Mr.John?
• Need to find the John salary first (inner query)
then compare the value with others salary
(outer query)
SQL> select empname from employees where salary =(select min(salary) from
employees);
EMPNAME
--------------------
Mark
Nadia
Nadal
Diwaagar
Charles
Unit 3 DBMS
SUB-QUERIES OR NESTED QUERIES
EMPNAME DOB
-------------------- ---------
charles 29-DEC-98
Unit 3 DBMS
Using Having clause..
Select departmentid,min(salary) from emp
group by departmentid
Having min(salary) >
(select min(salary) from emp where
departmentid=50);
Unit 3 DBMS
Set Operations
• Find all customers who have a loan, an account, or both:
(select customer-name from depositor)
union
(select customer-name from borrower)
Find all customers who have both a loan and an account.
(select customer-name from depositor)
intersect
(select customer-name from borrower)
Find all customers who have an account but no loan.
Unit 3 DBMS
Views
• It is not necessary for all users to see the entire logical model (that is, all
the actual relations stored in the database.)
• Consider a person who needs to know an instructors name and
department, but not the salary. This person should see a relation
described, in SQL, by
• A view provides a mechanism to hide certain data from the view of certain
users.
• Any relation that is not of the conceptual model but is made visible to a
user as a “virtual relation” is called a view.
Unit 3 DBMS
View Creation
• A view is defined using the create view statement which has the form
create view v as < query expression >
where <query expression> is any legal SQL expression. The view name is
represented by v.
• Once a view is defined, the view name can be used to refer to the virtual
relation that the view generates.
• View definition is not the same as creating a new relation by evaluating
the query expression
– Rather, a view definition causes the saving of an expression; the
expression is substituted into queries using the view.
Unit 3 DBMS
Display view details
• A view of instructors without their salary
create view faculty as
select ID, name, dept_name
from instructor
• Find all instructors in the Biology department
select name
from faculty
where dept_name = 'Biology'
• Create a view of department salary totals
create view departments_total_salary(dept_name, total_salary) as
select dept_name, sum (salary)
from instructor
group by dept_name;
Unit 3 DBMS
• One view may be used in the expression defining another view
Unit 3 DBMS
Materialized Views
• Certain database systems allow view relations to be physically stored.
• If relations used in the query are updated, the materialized view result becomes out of
date
– Need to maintain the view, by updating the view whenever the underlying
Unit 3 DBMS
View Update
• Add a new tuple to faculty view which we defined earlier
insert into faculty
Unit 3 DBMS
Update Views Rules
– The select clause contains only attribute names of the relation, and
– Any attribute not listed in the select clause can be set to null
Unit 3 DBMS
Transaction
• A transaction consists of a sequence of query and/or update statements
and is a “unit” of work
• The SQL standard specifies that a transaction begins implicitly when an
SQL statement is executed.
• The transaction must end with one of the following statements:
– Commit work. The updates performed by the transaction become
permanent in the database.
– Rollback work. All the updates performed by the SQL statements in
the transaction are undone.
• Atomic transaction
– either fully executed or rolled back as if it never occurred
• Isolation from concurrent transactions
Unit 3 DBMS
Triggers
• A trigger is a stored procedure in database which automatically invokes
whenever a special event in the database occurs. For example, a trigger
can be invoked when a row is inserted into a specified table or when
certain table columns are being updated.
• Triggers are composed to be executed in light of any of the
accompanying occasions.
A database control (DML) statement (DELETE, INSERT, or UPDATE).
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
IF sql%notfound THEN
total_rows := sql%rowcount;
END IF;
END;
Advantages of Triggers
•Auditing
• Evaluation
query.
Basic Steps in Query Processing : Optimization
salary(salary75000(instructor))
• Each relational algebra operation can be evaluated using one of
several different algorithms
– Correspondingly, a relational-algebra expression can be evaluated
in many ways.
• Annotated expression specifying detailed evaluation strategy is called
an evaluation-plan.
– E.g., can use an index on salary to find instructors with salary <
75000,
– or can perform complete relation scan and discard instructors
with salary 75000
Basic Steps: Optimization (Cont.)
database catalog
A block is the basic unit from which all PL/SQL programs are built. A block
can be named (functions and procedures) or anonymous
• Sections of block
1- Header Section
2- Declaration Section
3- Executable Section
4- Exception Section
Structure of PL/SQL
HEADER
DECLARE
BEGIN
EXCEPTION
Exception handlers
END;
Structure of PL/SQL
DECLARE
a number;
text1 varchar2(20);
text2 varchar2(20) := “HI”;
BEGIN
---------- ---------- ----------
END;
Variable_name Table_name.Column_name%type;
• Conditional controls
• Iterative or loop controls.
• Exception or error controls
• Conditional Controls
IF....THEN....END IF;
IF....THEN...ELSE....END IF;
IF....THEN...ELSIF....THEN....ELSE....END IF;
PL/SQL Control Structure
• LOOP
...SQL Statements...
EXIT;
END LOOP;
• WHILE loops
• WHILE condition LOOP
...SQL Statements...
END LOOP;
• FOR loops
• FOR <variable(numeric)> IN [REVERSE] <lowerbound>..<upperbound>
LOOP .... ..... END LOOP;
Cont..
• PL/SQL is a completely portable, high-
performance transaction-processing
language.
• PL/SQL provides a built-in, interpreted and
OS independent programming
environment.
• PL/SQL can also directly be called from
the command-line SQL*Plus interface.
DECLARE message varchar2(20):= 'Hello, World!'; BEGIN dbms_output.put_line(message); END; /
Cont..
• DECLARE ;
• BEGIN IF(CONDITION)
• THEN ;
• END;
Cont..
• Coding for If Statement:
• DECLARE
• b number;
• c number;
• BEGIN
• B:=10;
• C:=20;
• if(C>B) THEN
• dbms_output.put_line('C is maximum');
• end if;
• end;
• /
PL/SQL Control Structure
• Cursor
DECLARE
name varchar2(20);
Cursor c1 is
select t.name
from table t
where date is not null;
BEGIN
OPEN c1;
LOOP
FETCH c1 into name;
exit when c1%NOTFOUND;
END LOOP;
CLOSE c1;
END;
Debuging
• show error
• DBMS_OUTPUT.PUT_LINE(‘ .. ‘);
Execution
• How to execute a function in PL/SQL?
Var issue_flag number;
exec :issue_flag:=fun_name(arg1,arg2,. . . .);
PRINT :issue_flag;
• How to execute a procedure in PL/SQL?
Exec procedure_name(arg1,arg2,. . . .);
PL_SQL CURSOR
• A cursor is a pointer to this context area.
• PL/SQL controls the context area through
a cursor.
• A cursor holds the rows (one or more)
returned by a SQL statement.
• There are two types of cursors :
1. Implicit cursors
2. Explicit cursors
Cont..
Explicit cursor
CURSOR cursor_name IS
select_statement;
OPEN c_customers;
FETCH c_customers INTO c_id, c_name, c_addr;
CLOSE c_customers;
Cursor program
DECLARE c_id emp.eid%type;
c_name emp.ename%type;
c_sal emp.salary%type;
CURSOR c_customers is SELECT eid, ename, salary FROM emp;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_sal;
EXIT
WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' ||
c_sal);
END LOOP;
CLOSE c_customers;
END;
/
References
1. http://www.csee.umbc.edu/help/oracle8/server.815/a67842/01_oview.htm#740
2. http://en.wikipedia.org/wiki/PL/SQL
3. http://www.skillbuilders.com/Tutorials-V2/ora9i_Intro_to_PLSQL/ora9i_Intro_to_PLSQL.cfm
4. http://www.databasejournal.com/features/mysql/article.php/ 3569846/MySQL-Stored-Functions.htm
5. http://www.mysqltutorial.org/mysql-stored-function/
6. https://dev.mysql.com/doc/refman/5.7/en/create- procedure.html
THANK YOU