DBMS Unit 3
DBMS Unit 3
SQL | Constraints
Constraints are the rules that we can apply on the type of data in a table. That is, we can specify the limit on
the type of data that can be stored in a particular column in a table using constraints.
The available constraints in SQL are:
• NOT NULL: This constraint tells that we cannot store a null value in a column. That is, if a column is specified
as NOT NULL then we will not be able to store null in this particular column any more.
• UNIQUE: This constraint when specified with a column, tells that all the values in the column must be
unique. That is, the values in any row of a column must not be repeated.
• PRIMARY KEY: A primary key is a field which can uniquely identify each row in a table. And this
constraint is used to specify a field in a table as primary key.
• FOREIGN KEY: A Foreign key is a field which can uniquely identify each row in a another table. And this
constraint is used to specify a field as Foreign key.
• CHECK: This constraint helps to validate the values of a column to meet a particular condition. That is, it
helps to ensure that the value stored in a column meets a specific condition.
• DEFAULT: This constraint specifies a default value for the column when no value is specified by the
user.
Syntax:
Below is the syntax to create constraints using CREATE TABLE statement at the time of creating the table.
//Primary Key
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);
• The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
• A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table.
• The table with the foreign key is called the child table, and the table with the primary key is called the referenced
or parent table.
Persons PersonID LastName FirstName Age
Table 1 Hansen Ola 30
2 Svendson Tove 23
3 Pettersen Kari 20
• The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
• The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign key column, because it has
to be one of the values contained in the parent table.
• If you define a CHECK constraint on a column it will allow only certain values for this column.
• If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other
columns in the row.
• The default value will be added to all new records, if no other value is specified.
• Indexes are used to retrieve data from the database more quickly than otherwise. The users cannot see the
indexes, they are just used to speed up searches/queries.
Syntax:
Example Queries(INNER JOIN)
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1 This query will show the names and age of students enrolled
INNER JOIN table2 in different courses.
ON table1.matching_column = table2.matching_column;
SELECT StudentCourse.COURSE_ID, Student.NAME,
Student.AGE FROM Student
table1: First table. INNER JOIN StudentCourse
table2: Second table ON Student.ROLL_NO = StudentCourse.ROLL_NO;
matching_column: Column common to both the tables.
Consider the two tables below as follows:
StudentCourse
Student
Output:
B. LEFT JOIN
• This join returns all the rows of the table on the left side of the join and matches rows for the table on the right
side of the join. For the rows for which there is no matching row on the right side, the result-set will contain null.
LEFT JOIN is also known as LEFT OUTER JOIN.
SELECT Student.NAME,StudentCourse.COURSE_ID
Syntax: FROM Student
LEFT JOIN StudentCourse
SELECT table1.column1,table1.column2,table2.column1,.... ON StudentCourse.ROLL_NO = Student.ROLL_NO;
FROM table1
LEFT JOIN table2 Output:
ON table1.matching_column = table2.matching_column;
Syntax:
Example Queries(FULL JOIN):
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1 SELECT Student.NAME,StudentCourse.COURSE_ID
FULL JOIN table2 FROM Student
ON table1.matching_column = table2.matching_column; FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
HARSH 1
PRATIK 2
RIYANKA 2
DEEP 3
SAPTARHI 1
DHANRAJ NULL
ROHIT NULL
NIRAJ NULL
NULL 4
NULL 5
NULL 4
SET Operators in SQL
SET operators are special type of operators which are used to combine the result of two queries.
Operators covered under SET operators are:
1.UNION
2.UNION ALL
3.INTERSECT
4.MINUS
Example 1:
Write a query to perform union between the table t_employees and the table t2_employees.
Query:
1.mysql> SELECT *FROM t_employees UNION SELECT *FROM t2_employees;
Here, in a single query, we have written two SELECT queries. The first SELECT query will fetch the records from the
t_employees table and perform a UNION operation with the records fetched by the second SELECT query from the
t2_employees table.
ID Name Department Salary Year_of_Experience
UPDATE table
SET column_name = new_value
[WHERE OPERATOR [VALUE](SELECT COLUMN_NAME FROM TABLE_NAME [WHERE]);
UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25 ID NAME AGE ADDRESS SALARY
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
1 Ramesh 32 Ahmedabad 500.00
WHERE AGE >= 27 );
2 Khilan 25 Delhi 1500.00
SELECT * FROM CUSTOMERS;
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 2125.00
6 Komal 22 Hyderabad 4500.00
10000.0
7 Muffy 24 Indore
0
Subqueries with the DELETE Statement
Basics of PL/SQL
• PL/SQL stands for Procedural Language extensions to the Structured Query Language (SQL).
• PL/SQL is a combination of SQL along with the procedural features of programming languages.
• Oracle uses a PL/SQL engine to processes the PL/SQL statements.
• PL/SQL includes procedural language elements like conditions and loops. It allows declaration of constants
and variables, procedures and functions, types and variable of those types and triggers.
Disadvantages of SQL:
• SQL doesn’t provide the programmers with a technique of condition checking, looping and branching.
• SQL statements are passed to Oracle engine one at a time which increases traffic and decreases speed.
• SQL has no facility of error checking during manipulation of data.
Features of PL/SQL:
• PL/SQL is basically a procedural language, which provides the functionality of decision making, iteration and many
more features of procedural programming languages.
• PL/SQL can execute a number of queries in one block using single command.
• One can create a PL/SQL unit such as procedures, functions, packages, triggers, and types, which are stored in the
database for reuse by applications.
• PL/SQL provides a feature to handle the exception which occurs in PL/SQL block known as exception handling
block.
• Applications written in PL/SQL are portable to computer hardware or operating system where Oracle is
operational.
• PL/SQL Offers extensive error checking.
Differences between SQL and PL/SQL:
SQL PL/SQL
SQL is a single query that is used to perform DML and PL/SQL is a block of codes that used to write the
DDL operations. entire program blocks/ procedure/ function, etc.
It is declarative, that defines what needs to be done, PL/SQL is procedural that defines how the things
rather than how things need to be done. needs to be done.
DECLARE
declaration statements;
BEGIN
executable statements
EXCEPTIONS
exception handling statements
END;
• Declare section starts with DECLARE keyword in which variables, constants, records as cursors can be declared
which stores data temporarily. It basically consists definition of PL/SQL identifiers. This part of the code is
optional.
• Execution section starts with BEGIN and ends with END keyword. This is a mandatory section and here the
program logic is written to perform any task like loops and conditional statements. It supports all DML
commands, DDL commands and SQL*PLUS built-in functions as well.
• Exception section starts with EXCEPTION keyword. This section is optional which contains statements that are
executed when a run-time error occurs. Any exceptions can be handled in this section.
SQL is a single query that is used to perform DML and DDL PL/SQL is a block of codes that used to write the entire
operations. program blocks/ procedure/ function, etc.
It is declarative, that defines what needs to be done, rather PL/SQL is procedural that defines how the things needs to be
than how things need to be done. done.
Cannot contain PL/SQL code in it. It is an extension of SQL, so it can contain SQL inside it.
SELECT TOP 1 ConsultationFees
FROM(
SELECT TOP N ConsultationFees
FROM PatientsCheckup
ORDER BY ConsultationFees DESC) AS FEES
ORDER BY ConsultationFees ASC;
SELECT ConsultationFees
FROM PatientsCheckup F1
WHERE N-1 = (
SELECT COUNT( DISTINCT ( F2.ConsultationFees ) )
FROM PatientsCheckup F2
WHERE F2.ConsultationFees > F1.ConsultationFees );
PL/SQL - Triggers
Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers are, in
fact, written to be executed in response to any of the following events −
• A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
• A database definition (DDL) statement (CREATE, ALTER, or DROP).
• A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
Benefits of Triggers
Triggers can be written for the following purposes −
• Generating some derived column values automatically
• Enforcing referential integrity
• Event logging and storing information on table access
• Auditing
• Synchronous replication of tables
• Imposing security authorizations
• Preventing invalid transactions
Creating Triggers
• CREATE [OR REPLACE] TRIGGER trigger_name − Creates or
The syntax for creating a trigger is − replaces an existing trigger with the trigger_name.
• {BEFORE | AFTER | INSTEAD OF} − This specifies when the
CREATE [OR REPLACE ] TRIGGER trigger_name trigger will be executed. The INSTEAD OF clause is used for
{BEFORE | AFTER | INSTEAD OF } creating trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE} • {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the
[OF col_name] DML operation.
ON table_name • [OF col_name] − This specifies the column name that will be
[REFERENCING OLD AS o NEW AS n] updated.
[FOR EACH ROW] • [ON table_name] − This specifies the name of the table
WHEN (condition) associated with the trigger.
DECLARE • [REFERENCING OLD AS o NEW AS n] − This allows you to
Declaration-statements refer new and old values for various DML statements, such
BEGIN as INSERT, UPDATE, and DELETE.
Executable-statements • [FOR EACH ROW] − This specifies a row-level trigger, i.e., the
EXCEPTION trigger will be executed for each row being affected.
Exception-handling-statements Otherwise the trigger will execute just once when the SQL
END; statement is executed, which is called a table level trigger.
• WHEN (condition) − This provides a condition for rows for
which the trigger would fire. This clause is valid only for
row-level triggers.
Example
To start with, we will be using the CUSTOMERS table we had created and used in the previous
chapters −
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON customers
Select * from customers; FOR EACH ROW
WHEN (NEW.ID > 0)
+----+----------+-----+-----------+----------+ DECLARE
| ID | NAME | AGE | ADDRESS | SALARY | sal_diff number;
+----+----------+-----+-----------+----------+ BEGIN
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | sal_diff := :NEW.salary - :OLD.salary;
| 2 | Khilan | 25 | Delhi | 1500.00 | dbms_output.put_line('Old salary: ' || :OLD.salary);
| 3 | kaushik | 23 | Kota | 2000.00 | dbms_output.put_line('New salary: ' || :NEW.salary);
| 4 | Chaitali | 25 | Mumbai | 6500.00 | dbms_output.put_line('Salary difference: ' || sal_diff);
| 5 | Hardik | 27 | Bhopal | 8500.00 | END;
| 6 | Komal | 22 | MP | 4500.00 | /
+----+----------+-----+-----------+----------+
%FOUND
1 Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows or
a SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.
%NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE
2
statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise,
it returns FALSE.
%ISOPEN
3 Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.
%ROWCOUNT
4 Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or
returned by a SELECT INTO statement.
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected
Select * from customers;
');
END IF;
+----+----------+-----+-----------+----------+
END;
| ID | NAME | AGE | ADDRESS | SALARY |
/
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+
Explicit Cursors
• Explicit cursors are programmer-defined cursors for gaining more control over the context area. An explicit cursor
should be defined in the declaration section of the PL/SQL Block. It is created on a SELECT Statement which returns
more than one row.
• The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;
Working with an explicit cursor includes the following steps −