SlideShare a Scribd company logo
1 of 54
Download to read offline
Database Management System
Part-3
Dr. K ADISESHA
Introduction
SQL Quaries
SQL Operators
PL/SQL
Relational Keys
2
SQL Programming
Prof. K. Adisesha
Prof. K. Adisesha
Introduction to SQL
Prof. K. Adisesha
3
SQL Programming:
DDL: SQL was developed at IBM by Donald D. Chamberlin and Raymond F. Boyce in
the early 1970s.
➢ This was initially called SEQUEL(Structured English QUEry Language).
➢ The main objective of SQL is to update, store, manipulate and retrieve data stored in a
relational database.
➢ SQL is a standard language which is used to operate on database in the form of
queries. But MySQL is Open Source Database Management System or simply a
Database Software
Introduction to SQL
Prof. K. Adisesha
4
Numeric Data Types:
Data Types: SQL Data Type is an attribute that specifies the type of data of any object.
Each column, variable and expression has a related data type in SQL.
➢ You should use only the type and size of field you really need to use.
➢ SQL uses many different data types broken into three categories −
❖ Numeric
❖ Date and Time
❖ String Types
Data Type Range
BIT Signed values range from -128 to 127. Unsigned values range from 0 to 255.
INTEGER(m) / Int(m) Signed values range from -2147483648 to 2147483647.
Unsigned values range from 0 to 4294967295.
DECIMAL(m,d) /
DEC(m,d)/NUMERIC(m,d)
Unpacked fixed point number. m defaults to 10,d defaults to 0, if not specified.
FLOAT(m,d) Single precision floating point number.
DOUBLE(m,d)/REAL(m,d) Double precision floating point number.
BOOL/ BOOLEAN Treated as a Boolean data type where a value of 0 is considered to be FALSE and any
other value is considered to be TRUE.
Introduction to SQL
Prof. K. Adisesha
5
Numeric Data Type:
These data types can include the exact numeric data types (For example, integer,
decimal, numeric, etc.),
Introduction to SQL
Prof. K. Adisesha
6
Date and Time :
Date and Time Data Types: SQL Data Type is an attribute that specifies the type of data
of any object. Each column, variable and expression has a related data type in SQL.
➢ Note − Here, datetime has 3.33 milliseconds accuracy
where as smalldatetime has 1 minute accuracy.
DATA TYPE FROM TO FORMAT
datetime Jan 1, 1753 Dec 31, 9999 YYYY-MM-DD hh:mm:ss
smalldatetime Jan 1, 1900 Jun 6, 2079 YYYY-MM-DD
date Stores a date like June 30, 1991 YYYY-MM-DD
time Stores a time of day like 12:30 P.M. hh:mm:ss
Introduction to SQL
Prof. K. Adisesha
7
Date and Time :
The following are the Date/Time Datatypes in MySQL:
Data Type Syntax Maximum Size Explanation
DATE Values range from '1000-01-01' to '9999-12-31'. Displayed as 'YYYY-MM-DD'.
DATETIME
Values range from '1000-01-01 00:00:00' to
'9999-12-31 23:59:59'.
Displayed as 'YYYY-MM-DD
HH:MM:SS'.
TIMESTAMP(m)
Values range from '1970-01-01 00:00:01' UTC
to '2038-01-19 03:14:07' UTC.
Displayed as 'YYYY-MM-DD
HH:MM:SS'.
TIME Values range from '-838:59:59' to '838:59:59'. Displayed as 'HH:MM:SS'.
YEAR[(2|4)] Year value as 2 digits or 4 digits. Default is 4 digits.
Introduction to SQL
Prof. K. Adisesha
8
String Data Type:
Although the numeric and date types are most data you'll store will be in a string format.
Data Type Syntax Maximum Size Explanation
CHAR(size) Maximum size of 255 characters.
Where size is the number of characters to store.
Fixed-length strings. Space padded on right to
equal size characters.
VARCHAR(size) Maximum size of 255 characters.
Where size is the number of characters to store.
Variable-length string.
TEXT(size) Maximum size of 65,535 characters. Where size is the number of characters to store.
LONGTEXT(size) Maximum size of 4GB or 4,294,967,295 characters. Where size is the number of characters to store.
BINARY(size) Maximum size of 255 characters.
Where size is the number of binary characters to
store. Fixed-length strings. Space padded on right to
equal size characters.
VARBINARY(size) Maximum size of 255 characters.
Where size is the number of characters to store.
Variable-length string
SQL Programming
Prof. K. Adisesha
9
SQL Programming:
DDL: A data definition language or data description language (DDL) is syntax similar
to a computer programming language for defining data structures, especially database
schemas.-
➢ Commands in DDL are:
❖ CREATE
❖ DROP
❖ TRUNCATE
❖ RENAME
❖ ALTER
❖ BACKUP DATABASE
SQL Programming
Prof. K. Adisesha
10
Data Definition Language :
DDL:
➢ Syntax:
❖ CREATE Statement: Create table tablename (column_name1 data_ type constraints,
column_name2 data_ type constraints);
➢ Example:
❖ Query to create a table employee with empno, ename, designation, and salary.
✓ SQL>CREATE TABLE EMP (EMPNO NUMBER (4), ENAME VARCHAR2 (10),
DESIGNATIN VARCHAR2 (10), SALARY NUMBER (8,2));
❖ Query for create a from an existing table with all the fields.
✓ SQL> CREATE TABLE EMP1 AS SELECT * FROM EMP;
SQL Programming
Prof. K. Adisesha
11
Data Definition Language:
DDL:
➢ Syntax:
❖ CREATE Statement: Create table tablename (column_name1 data_ type constraints,
column_name2 data_ type constraints);
➢ Example:
1.CREATE TABLE students
2.(
3.S_Id int(4) NOT NULL PRIMARY KEY,
4. S_Name varchar (255) NOT NULL,
5.Address varchar (255),
6.City varchar (255),
7.)
✓ SQL> DESC Students
Name Null? Type
----------------------------------------- --------
S_Id NOT NULL NUMBER (4)
S_NAME NOT NULL VARCHAR2 (255)
Address VARCHAR2 (255)
City VARCHAR2 (255)
SQL Programming
Prof. K. Adisesha
12
Data Definition Language:
SYNTAX:
❖ DROP:DROP TABLE table_name;
❖ TRUNCATE: TRUNCATE TABLE table_name;
❖ RENAME: RENAME TABLE {tbl_name} TO {new_tbl_name};
❖ ALTER:
✓ Add column to Table: ALTER TABLE table_name ADD column_name column-definition;
✓ Modify column in Table: ALTER TABLE table_name MODIFY column_namecolumn_type;
✓ Drop column in Table:ALTER TABLE table_name DROP COLUMN column_name;
SQL Programming
Prof. K. Adisesha
13
Data Definition Language:
Alter Command:
Example:
❖ Query to Alter the column EMPNO NUMBER(4) TO EMPNO NUMBER(6).
✓ SQL>ALTER TABLE EMP MODIFY EMPNO NUMBER (6);
❖ Query to add a new column in to employee.
✓ SQL> ALTER TABLE EMP ADD QUALIFICATION VARCHAR2(6);
❖ Query to drop a column from an existing table employee.
✓ SQL> ALTER TABLE EMP DROP COLUMN DOJ;
❖ Query to drop an existing table employee.
✓ SQL> DROP table employee;
SQL Programming
Prof. K. Adisesha
14
Data Definition Language:
BACKUP DATABASE: This statement is used to create a full backup of an existing
database.
❖ Syntax.
✓ BACKUP DATABASE DatabaseName TO DISK = 'filepath';
❖ Example.
✓ BACKUP DATABASE Employee TO DISK = 'C:Desktop';
➢ You can also use a differential back up. This type of back up only backs up the parts of the
database, which have changed since the last complete backup of the database.
❖ Syntax.
✓ BACKUP DATABASE DatabaseName TO DISK = 'filepath’WITH DIFFERENTIAL;
❖ Example:
✓ BACKUP DATABASE Employee TO DISK = ‘C:Desktop’WITH DIFFERENTIAL;
SQL Programming
Prof. K. Adisesha
15
Different Types Of Keys In Database:
There are mainly 7 types of Keys, that can be considered in a database.
➢ Candidate Key – A set of attributes which can uniquely identify a table can be termed as a
Candidate Key.
➢ Super Key – The set of attributes which can uniquely identify a tuple is known as Super Key.
➢ Primary Key – A set of attributes which are used to uniquely identify every tuple is also a primary key.
➢ Alternate Key – Alternate Keys are the candidate keys, which are not chosen as a Primary key.
➢ Unique Key – The unique key is similar to the primary key, but allows one NULL value in the
column.
➢ Foreign Key – An attribute that can only take the values present as the values of some other
attribute, is the foreign key to the attribute to which it refers.
➢ Composite Key – A composite key is a combination of two or more columns that identify each tuple
uniquely.
SQL Programming
Prof. K. Adisesha
16
Constraints Used In Database:
Constraints are used in a database to specify the rules for data in a table. The following are
the different types of constraints:
➢ NOT NULL: This constraint ensures that a column cannot have a NULL value.
➢ UNIQUE: This constraint ensures that all the values in a column are unique.
➢ CHECK: This constraint ensures that all the values in a column satisfy a specific condition.
➢ DEFAULT: This constraint consists of a set of default values for a column when no value is
specified
➢ INDEX: This constraint is used to create indexes in the table, through which you can create and
retrieve data from the database very quickly.
SQL Programming
Prof. K. Adisesha
17
Data Manipulation Language :
DML: A data manipulation language (DML) is a family of syntax elements similar to a
computer programming language used for selecting, inserting, deleting and updating
data in a database.
➢ Performing read-only queries of data is sometimes also considered a component of
DML.
➢ Commands in DML are:
❖ USE
❖ INSERT
❖ UPDATE
❖ DELETE
❖ SELECT
SQL Programming
Prof. K. Adisesha
18
Data Manipulation Language:
USE: The USE statement is used to select the database on which you want to perform
operations.
➢ Syntax:
USE DatabaseName;
➢ Example:
USE EmployeeDB;
DELETE: It is used to remove one or more row from a table.
➢ Syntax:
DELETE FROM table_name [WHERE condition];
➢ Example:
DELETE FROM employee WHERE Author="Sunny";
SQL Programming
Prof. K. Adisesha
19
Data Manipulation Language :
INSERT: The INSERT statement is a SQL query. It is used to insert data into the row
of a table.
➢ Syntax:
INSERT INTO TABLE_NAME (col1, col2, col3,.... col N)
VALUES (value1, value2, value3, .... valueN);
Or
INSERT INTO TABLE_NAME
VALUES (value1, value2, value3, .... valueN);
➢ Example:
INSERT INTO Studentdb (RegNo, Name) VALUES (“001", “Sunny");
SQL Programming
Prof. K. Adisesha
20
Data Manipulation Language:
UPDATE: This command is used to update or modify the value of a column in the
table.
➢ Syntax:
UPDATE table_name SET [column_name1= value1,...column_nameN = valueN]
[WHERE CONDITION]
➢ Example:
UPDATE students
SET User_Name = ‘Sunny'
WHERE Student_Id = '3’;
SQL Programming
Prof. K. Adisesha
21
Data Manipulation Language:
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 or SELECT * FROM employee;
FROM employee
WHERE age > 20;
SQL Programming
Prof. K. Adisesha
22
Data Manipulation Language:
SELECT: Apart from just using the SELECT keyword individually, you can use the
following keywords with the SELECT statement:
➢ DISTINCT
➢ ORDER BY
➢ GROUP BY
➢ HAVING Clause
➢ INTO
SQL Programming
Prof. K. Adisesha
23
Data Manipulation Language:
SELECT DISTINCT: This statement is used to return only different values.
➢ Syntax: SELECT DISTINCT Column1, Column2, ...ColumnN FROM TableName;
➢ Example: SELECT DISTINCT PhoneNumber FROM Student_Info;
ORDER BY: The ‘ORDER BY’ statement is used to sort the required results in
ascending or descending order. The results are sorted in ascending order by default.
➢ Syntax:
SELECT Column1, Column2, ...ColumnN FROM TableName
ORDER BY Column1, Column2, ... ASC|DESC;
➢ Example:
SELECT * FROM Student_Info ORDER BY ContactName DESC;
SQL Programming
Prof. K. Adisesha
24
Data Manipulation Language:
GROUP BY: This ‘GROUP BY’ statement is used with the aggregate functions to group
the result-set by one or more columns.
➢ Syntax: SELECT Column1, Column2,..., ColumnN FROM TableName WHERE Condition
GROUP BY ColumnName(s);
➢ Example: SELECT COUNT(Studient_ID), City FROM Student_Info GROUP BY City;
SELECT INTO: The ‘SELECT INTO’ statement is used to copy data from one table to
another.
➢ Syntax:
SELECT * INTO NewTable [IN ExternalDB] FROM OldTable WHERE Condition;
➢ Example:
SELECT * INTO BCA_Student FROM Student_info WHERE Course = ‘BCA';
SQL Programming
Prof. K. Adisesha
25
Data Manipulation Language:
‘HAVING’ Clause: The ‘HAVING’ clause is used in SQL because the WHERE
keyword cannot be used everywhere.
➢ Syntax:
SELECT ColumnName(s) FROM TableName WHERE Condition
GROUP BY ColumnName(s)
HAVING Condition
ORDER BY ColumnName(s);
➢ Example: SELECT COUNT(Student_ID), City FROM Student_Info
GROUP BY Course
HAVING COUNT(Marks) >75
ORDER BY COUNT(Marks) DESC;
SQL Programming
Prof. K. Adisesha
26
Operators in SQL:
The different set of operators available in SQL are as follows:.
Arithmetic Operators Comparison Operators Logical Operators
❖ AND
❖ OR
❖ NOT
❖ BETWEEN
❖ LIKE
❖ IN
❖ EXISTS
❖ ALL
❖ ANY
SQL Programming
Prof. K. Adisesha
27
Arithmetic Operators:
We can use various Arithmetic Operators on the data stored in the tables.
➢ Example Arithmetic Operators:
❖ SELECT employee_id, employee_name, salary, salary + 100
AS "salary + 100" FROM addition;
❖ SELECT employee_id, employee_name, salary, salary - 100
AS "salary - 100" FROM subtraction;
❖ SELECT employee_id, employee_name, salary, salary * 100
AS "salary * 100" FROM addition;
SQL Programming
Prof. K. Adisesha
28
Comparison Operators:
In SQL, there are six comparison operators available which help us run queries to
perform various operations. We will use the WHERE command along with the
conditional operator to achieve this in SQL.
➢ Syntax :
❖ SELECT * FROM TABLE_NAME WHERE
ATTRIBUTE CONDITION_OPERATOR GIVEN_VALUE;
➢ Example :
❖ SELECT employee_id, employee_name, salary
WHERE salary > 10000;
❖ SELECT * FROM Studient_info WHERE MARKS<40;
SQL Programming
Prof. K. Adisesha
29
Logical Operators:
A logical operator like the Comparison operator used to test for the truth of the
condition returns a boolean value of TRUE, FALSE, or UNKNOWN.
❖ AND : TRUE if both Boolean expressions are TRUE.
❖ IN : TRUE if the operand is equal to one of a list of expressions.
❖ NOT : Reverses the value of any other Boolean operator.
❖ OR : TRUE if either Boolean expression is TRUE.
❖ LIKE : TRUE if the operand matches a pattern.
❖ ALL : TRUE if all of a set of comparisons are TRUE.
❖ ANY : TRUE if any one of a set of comparisons is TRUE.
❖ EXISTS : TRUE if a subquery contains any rows.
❖ SOME : TRUE if some of a set of comparisons are TRUE.
❖ BETWEEN:TRUE if the operand is within a range.
SQL Programming
Prof. K. Adisesha
30
Logical Operators:
A logical operator like the Comparison operator used to test for the truth of the
condition returns a boolean value of TRUE, FALSE, or UNKNOWN.
❖ AND : TRUE if both Boolean expressions are TRUE.
SELECT * FROM Employee_Info
WHERE City='Mumbai' AND City='Hyderabad';
❖ IN : TRUE if the operand is equal to one of a list of expressions.
SELECT * FROM Employee_Info
WHERE City IN ('Mumbai', 'Bangalore', 'Hyderabad');
❖ NOT : Reverses the value of any other Boolean operator.
SELECT * FROM Employee_Info
WHERE NOT City='Mumbai';
SQL Programming
Prof. K. Adisesha
31
Logical Operators:
A logical operator like the Comparison operator used to test for the truth of the
condition returns a boolean value of TRUE, FALSE, or UNKNOWN.
❖ OR : TRUE if either Boolean expression is TRUE.
SELECT * FROM Employee_Info
WHERE City='Mumbai' OR City='Hyderabad';
❖ LIKE : TRUE if the operand matches a pattern.
SELECT * FROM Employee_Info
WHERE EmployeeName LIKE 'S%';
❖ ALL : TRUE if all of a set of comparisons are TRUE.
SELECT EmployeeName FROM Employee_Info
WHERE EmployeeID = ALL (SELECT EmployeeID FROM Employee_Info
WHERE City = 'Hyderabad');
SQL Programming
Prof. K. Adisesha
32
Logical Operators:
A logical operator like the Comparison operator used to test for the truth of the
condition returns a boolean value of TRUE, FALSE, or UNKNOWN.
❖ ANY : TRUE if any one of a set of comparisons is TRUE.
SELECT EmployeeName FROM Employee_Info
WHERE EmployeeID = ANY (SELECT EmployeeID FROM Employee_Info
WHERE City = 'Hyderabad' OR City = 'Kolkata');
❖ EXISTS : TRUE if a subquery contains any rows.
SELECT EmergencyContactName FROM Employee_Info
WHERE EXISTS (SELECT EmergencyContactName FROM Employee_Info
WHERE EmployeeId = 05 AND City = 'Kolkata');
❖ BETWEEN:TRUE if the operand is within a range.
SELECT * FROM Employee_Salary
WHERE Salary BETWEEN 40000 AND 50000;
SQL Programming
Prof. K. Adisesha
33
Data Control Language:
Data Control Language: DCL commands are used to grant and take back authority
from any database user.
➢ Here are some commands that come under DCL:
❖ Grant
❖ Revoke
➢ Grant: It is used to give user access privileges to a database.
Example
GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;
➢ Revoke: It is used to take back permissions from the user.
Example
REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;
SQL Programming
Prof. K. Adisesha
34
Data Control Language:
Grant: This command is used to provide access or privileges on the database and its
objects to the users.
➢ Syntax:
❖ GRANT PrivilegeName ON ObjectName
TO {UserName |PUBLIC |RoleName}
[WITH GRANT OPTION];
➢ Example
-- To grant SELECT permission to Employee_Info table to user1
GRANT SELECT ON Employee_Info TO user1;
where,
✓ PrivilegeName – Is the privilege/right/access granted to the user.
✓ ObjectName – Name of a database object like TABLE/VIEW /
STORED PROC.
✓ UserName – Name of the user who is given the access/ rights/
privileges.
✓ PUBLIC – To grant access rights to all users.
✓ RoleName – The name of a set of privileges grouped together.
✓ WITH GRANT OPTION – To give the user access to grant other
users with rights.
SQL Programming
Prof. K. Adisesha
35
Data Control Language:
REVOKE: This command is used to withdraw the user’s access privileges given by
using the GRANT command.
➢ Syntax:
❖ REVOKE PrivilegeName
❖ ON ObjectName
❖ FROM {UserName |PUBLIC |RoleName}
➢ Example
-- To revoke the granted permission from user1
REVOKE SELECT ON Employee_Info TO user1;
SQL Programming
Prof. K. Adisesha
36
Transaction Control Language:
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
SQL Programming
Prof. K. Adisesha
37
Transaction Control Language:
Commit: Commit command is used to save all the transactions to the database.
➢ Syntax:
COMMIT;
➢ Example:
INSERT INTO Student_info VALUES(05, ‘Prajwal’,20);
COMMIT;
SQL Programming
Prof. K. Adisesha
38
Transaction Control Language:
Rollback: Rollback command is used to undo transactions that have not already been
saved to the database.
➢ Syntax: ROLLBACK;
➢ Example: DELETE FROM Student_info WHERE AGE = 21;
ROLLBACK;
SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back
the entire transaction.
➢ Syntax: SAVEPOINT SAVEPOINT_NAME;
➢ Example: UPDATE Student_info SET name = ‘Sunny' WHERE id = '05’;
SAVEPOINT S1;
SQL Programming
Prof. K. Adisesha
39
SQL Joins:
JOINS are used to combine rows from two or more tables, based on a related column
between those tables.
➢ The following are the types of joins:
❖ INNER JOIN: This join returns those records which have matching values in both the tables.
❖ FULL JOIN: This join returns all those records which either have a match in the left or the
right table.
❖ LEFT JOIN: This join returns records from the left table, and also those records which satisfy
the condition from the right table.
❖ RIGHT JOIN: This join returns records from the right table, and also those records which
satisfy the condition from the left table.
SQL Programming
Prof. K. Adisesha
40
SQL Joins:
JOINS are used to combine rows from two or more tables, based on a related column
between those tables.
➢ The following are the types of joins:
❖ INNER JOIN: This join returns those records which have matching values in both the tables.
❖ FULL JOIN: This join returns all those records which either have a match in the left or the
right table.
❖ LEFT JOIN: This join returns records from the left table, and also those records which satisfy
the condition from the right table.
❖ RIGHT JOIN: This join returns records from the right table, and also those records which
satisfy the condition from the left table.
SQL Programming
Prof. K. Adisesha
41
SQL Joins:
JOINS are used to combine rows from two or more tables, based on a related column
between those tables.
❖ INNER JOIN: This join returns those records which have matching values in both the tables.
Syntax
SELECT column_name(s) FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Example
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
SQL Programming
Prof. K. Adisesha
42
SQL Joins:
JOINS are used to combine rows from two or more tables, based on a related column
between those tables.
❖ FULL JOIN: This join returns all those records which either have a match in the left or the
right table.
Syntax SELECT column_name(s) FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
Example
SELECT Customers.CustomerName, Orders.OrderID FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
SQL Programming
Prof. K. Adisesha
43
SQL Joins:
JOINS are used to combine rows from two or more tables, based on a related column
between those tables.
❖ LEFT JOIN: This join returns records from the left table, and also those records which satisfy
the condition from the right table.
Syntax: SELECT column_name(s) FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
Example
SELECT Customers.CustomerName, Orders.OrderID FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
SQL Programming
Prof. K. Adisesha
44
SQL Joins:
JOINS are used to combine rows from two or more tables, based on a related column
between those tables.
❖ RIGHT JOIN: This join returns records from the right table, and also those records which
satisfy the condition from the left table.
Syntax: SELECT ColumnName(s)
FROM Table1
RIGHT JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;
Example
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;
SQL Programming
Prof. K. Adisesha
45
SQL UNION Operator:
The UNION operator is used to combine the result-set of two or more SELECT
statements.
➢ Every SELECT statement within UNION must have the same number of columns
➢ The columns must also have similar data types
➢ The columns in every SELECT statement must also be in the same order.
Syntax: SELECT column_name(s) FROM table1
UNION SELECT column_name(s) FROM table2;
Example
SELECT City FROM Customers UNION
SELECT City FROM Suppliers
ORDER BY City;
SQL Programming
Prof. K. Adisesha
46
SQL GROUP BY Statement:
The GROUP BY statement groups rows that have the same values into summary rows,
like "find the number of customers in each country".
➢ The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(),
SUM(), AVG()) to group the result-set by one or more columns.
Syntax: SELECT column_name(s) FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Example
SELECT COUNT(CustomerID), Country FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
SQL Programming
Prof. K. Adisesha
47
SQL HAVING Clause:
The GROUP BY statement groups rows that have the same values into summary rows,
like "find the number of customers in each country".
➢ The HAVING clause was added to SQL because the WHERE keyword cannot be used with
aggregate functions.
Syntax: SELECT column_name(s) FROM table_name
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s));
Example
SELECT COUNT(CustomerID), Country FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
PL/SQL
Prof. K. Adisesha
48
PL/SQL Programming:
The PL/SQL programming language was developed by Oracle Corporation in the late
1980s as procedural extension language for SQL and the Oracle relational database. .
➢ Following are certain notable facts about PL/SQL −
❖ 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.
❖ Direct call can also be made from external programming language calls to database.
❖ PL/SQL's general syntax is based on that of ADA and Pascal programming language.
PL/SQL
Prof. K. Adisesha
49
Features of PL/SQL:
PL/SQL has the following features −
➢ PL/SQL is tightly integrated with SQL.
➢ It offers extensive error checking.
➢ It offers numerous data types.
➢ It offers a variety of programming structures.
➢ It supports structured programming through functions and procedures.
➢ It supports object-oriented programming.
➢ It supports the development of web applications and server pages.
PL/SQL
Prof. K. Adisesha
50
Advantages of PL/SQL:
➢ SQL is the standard database language and PL/SQL is strongly integrated with SQL.
PL/SQL supports both static and dynamic SQL. Static SQL supports DML operations
and transaction control from PL/SQL block. In Dynamic SQL, SQL allows embedding
DDL statements in PL/SQL blocks.
➢ PL/SQL allows sending an entire block of statements to the database at one time. This
reduces network traffic and provides high performance for the applications.
➢ PL/SQL gives high productivity to programmers as it can query, transform, and update
data in a database.
➢ PL/SQL saves time on design and debugging by strong features, such as exception
handling, encapsulation, data hiding, and object-oriented data types.
PL/SQL Procedure
Prof. K. Adisesha
51
PL/SQL Procedure:
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs
one or more specific tasks. It is just like procedures in other programming languages.
➢ The procedure contains a header and a body.
❖ Header: The header contains the name of the procedure and the parameters or variables passed to the
procedure.
❖ Body: The body contains a declaration section, execution section and exception section similar to a
general PL/SQL block. CREATE [OR REPLACE] PROCEDURE procedure_name [ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name];
Introduction
Prof. K. Adisesha
52
PL/SQL - Basic Syntax:
PL/SQL which is a block-structured language in which PL/SQL programs are divided
and written in logical blocks of code.
➢ Each block consists of three sub-parts
❖ Declarations: This section starts with the keyword DECLARE. It is an
optional section and defines all variables, cursors, subprograms, and
other elements to be used in the program.
❖ Executable Commands: This section is enclosed between the keywords
BEGIN and END and it is a mandatory section. It consists of the
executable PL/SQL statements of the program.
❖ Exception Handling: This section starts with the keyword EXCEPTION.
This optional section contains exception(s) that handle errors in the
program.
Introduction
Prof. K. Adisesha
53
PL/SQL Comments:
Program comments are explanatory statements that can be included in the PL/SQL
code that you write and helps anyone reading its source code.
➢ All characters available inside any comment are ignored by the PL/SQL compiler.
➢ The PL/SQL supports single-line and multi-line comments.
❖ The PL/SQL single-line comments start with the
delimiter -- (double hyphen)
❖ multi-line comments are enclosed by /* and */.
Discussion
Prof. K. Adisesha (Ph. D)
54
Queries ?
Prof. K. Adisesha
9449081542

More Related Content

Similar to DBMS unit-3.pdf

Similar to DBMS unit-3.pdf (20)

lovely
lovelylovely
lovely
 
Ankit
AnkitAnkit
Ankit
 
SQL: Structured Query Language
SQL: Structured Query LanguageSQL: Structured Query Language
SQL: Structured Query Language
 
SQL for interview
SQL for interviewSQL for interview
SQL for interview
 
Introduction to SQL..pdf
Introduction to SQL..pdfIntroduction to SQL..pdf
Introduction to SQL..pdf
 
SQL ppt.pptx
SQL ppt.pptxSQL ppt.pptx
SQL ppt.pptx
 
SQL SERVER Training in Pune Slides
SQL SERVER Training in Pune SlidesSQL SERVER Training in Pune Slides
SQL SERVER Training in Pune Slides
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Dbms Basics
Dbms BasicsDbms Basics
Dbms Basics
 
SQL_NOTES.pdf
SQL_NOTES.pdfSQL_NOTES.pdf
SQL_NOTES.pdf
 
Dbms
DbmsDbms
Dbms
 
SQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredSQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics Covered
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
Oracle Introduction
Oracle Introduction Oracle Introduction
Oracle Introduction
 
Dbmsunit v
Dbmsunit vDbmsunit v
Dbmsunit v
 
unit-ii.pptx
unit-ii.pptxunit-ii.pptx
unit-ii.pptx
 
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytxjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
 
SQL2.pptx
SQL2.pptxSQL2.pptx
SQL2.pptx
 
Module02
Module02Module02
Module02
 
SQL: Data Definition Language commands.pptx
SQL: Data Definition Language commands.pptxSQL: Data Definition Language commands.pptx
SQL: Data Definition Language commands.pptx
 

More from Prof. Dr. K. Adisesha

Software Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdfSoftware Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdfProf. Dr. K. Adisesha
 
Software Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdfSoftware Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdfProf. Dr. K. Adisesha
 
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdfSoftware Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdfProf. Dr. K. Adisesha
 
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdfSoftware Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdfProf. Dr. K. Adisesha
 
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdfSoftware Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdfProf. Dr. K. Adisesha
 
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdfSoftware Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdfProf. Dr. K. Adisesha
 
Computer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. AdiseshaComputer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. AdiseshaProf. Dr. K. Adisesha
 
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. AdiaeshaCCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. AdiaeshaProf. Dr. K. Adisesha
 
CCN Unit-3 Data Link Layer by Dr. K. Adisesha
CCN Unit-3 Data Link Layer by Dr. K. AdiseshaCCN Unit-3 Data Link Layer by Dr. K. Adisesha
CCN Unit-3 Data Link Layer by Dr. K. AdiseshaProf. Dr. K. Adisesha
 
CCN Unit-4 Network Layer by Dr. K. Adisesha
CCN Unit-4 Network Layer by Dr. K. AdiseshaCCN Unit-4 Network Layer by Dr. K. Adisesha
CCN Unit-4 Network Layer by Dr. K. AdiseshaProf. Dr. K. Adisesha
 
CCN Unit-5 Transport & Application Layer by Adi.pdf
CCN Unit-5 Transport & Application Layer by Adi.pdfCCN Unit-5 Transport & Application Layer by Adi.pdf
CCN Unit-5 Transport & Application Layer by Adi.pdfProf. Dr. K. Adisesha
 

More from Prof. Dr. K. Adisesha (20)

Software Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdfSoftware Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdf
 
Software Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdfSoftware Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdf
 
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdfSoftware Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
 
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdfSoftware Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
 
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdfSoftware Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
 
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdfSoftware Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
 
Computer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. AdiseshaComputer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. Adisesha
 
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. AdiaeshaCCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
 
CCN Unit-3 Data Link Layer by Dr. K. Adisesha
CCN Unit-3 Data Link Layer by Dr. K. AdiseshaCCN Unit-3 Data Link Layer by Dr. K. Adisesha
CCN Unit-3 Data Link Layer by Dr. K. Adisesha
 
CCN Unit-4 Network Layer by Dr. K. Adisesha
CCN Unit-4 Network Layer by Dr. K. AdiseshaCCN Unit-4 Network Layer by Dr. K. Adisesha
CCN Unit-4 Network Layer by Dr. K. Adisesha
 
CCN Unit-5 Transport & Application Layer by Adi.pdf
CCN Unit-5 Transport & Application Layer by Adi.pdfCCN Unit-5 Transport & Application Layer by Adi.pdf
CCN Unit-5 Transport & Application Layer by Adi.pdf
 
Introduction to Computers.pdf
Introduction to Computers.pdfIntroduction to Computers.pdf
Introduction to Computers.pdf
 
R_Programming.pdf
R_Programming.pdfR_Programming.pdf
R_Programming.pdf
 
Scholarship.pdf
Scholarship.pdfScholarship.pdf
Scholarship.pdf
 
Operating System-2 by Adi.pdf
Operating System-2 by Adi.pdfOperating System-2 by Adi.pdf
Operating System-2 by Adi.pdf
 
Operating System-1 by Adi.pdf
Operating System-1 by Adi.pdfOperating System-1 by Adi.pdf
Operating System-1 by Adi.pdf
 
Operating System-adi.pdf
Operating System-adi.pdfOperating System-adi.pdf
Operating System-adi.pdf
 
Data_structure using C-Adi.pdf
Data_structure using C-Adi.pdfData_structure using C-Adi.pdf
Data_structure using C-Adi.pdf
 
JAVA PPT -2 BY ADI.pdf
JAVA PPT -2 BY ADI.pdfJAVA PPT -2 BY ADI.pdf
JAVA PPT -2 BY ADI.pdf
 
JAVA PPT -5 BY ADI.pdf
JAVA PPT -5 BY ADI.pdfJAVA PPT -5 BY ADI.pdf
JAVA PPT -5 BY ADI.pdf
 

Recently uploaded

Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 

Recently uploaded (20)

Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 

DBMS unit-3.pdf

  • 2. Introduction SQL Quaries SQL Operators PL/SQL Relational Keys 2 SQL Programming Prof. K. Adisesha Prof. K. Adisesha
  • 3. Introduction to SQL Prof. K. Adisesha 3 SQL Programming: DDL: SQL was developed at IBM by Donald D. Chamberlin and Raymond F. Boyce in the early 1970s. ➢ This was initially called SEQUEL(Structured English QUEry Language). ➢ The main objective of SQL is to update, store, manipulate and retrieve data stored in a relational database. ➢ SQL is a standard language which is used to operate on database in the form of queries. But MySQL is Open Source Database Management System or simply a Database Software
  • 4. Introduction to SQL Prof. K. Adisesha 4 Numeric Data Types: Data Types: SQL Data Type is an attribute that specifies the type of data of any object. Each column, variable and expression has a related data type in SQL. ➢ You should use only the type and size of field you really need to use. ➢ SQL uses many different data types broken into three categories − ❖ Numeric ❖ Date and Time ❖ String Types
  • 5. Data Type Range BIT Signed values range from -128 to 127. Unsigned values range from 0 to 255. INTEGER(m) / Int(m) Signed values range from -2147483648 to 2147483647. Unsigned values range from 0 to 4294967295. DECIMAL(m,d) / DEC(m,d)/NUMERIC(m,d) Unpacked fixed point number. m defaults to 10,d defaults to 0, if not specified. FLOAT(m,d) Single precision floating point number. DOUBLE(m,d)/REAL(m,d) Double precision floating point number. BOOL/ BOOLEAN Treated as a Boolean data type where a value of 0 is considered to be FALSE and any other value is considered to be TRUE. Introduction to SQL Prof. K. Adisesha 5 Numeric Data Type: These data types can include the exact numeric data types (For example, integer, decimal, numeric, etc.),
  • 6. Introduction to SQL Prof. K. Adisesha 6 Date and Time : Date and Time Data Types: SQL Data Type is an attribute that specifies the type of data of any object. Each column, variable and expression has a related data type in SQL. ➢ Note − Here, datetime has 3.33 milliseconds accuracy where as smalldatetime has 1 minute accuracy. DATA TYPE FROM TO FORMAT datetime Jan 1, 1753 Dec 31, 9999 YYYY-MM-DD hh:mm:ss smalldatetime Jan 1, 1900 Jun 6, 2079 YYYY-MM-DD date Stores a date like June 30, 1991 YYYY-MM-DD time Stores a time of day like 12:30 P.M. hh:mm:ss
  • 7. Introduction to SQL Prof. K. Adisesha 7 Date and Time : The following are the Date/Time Datatypes in MySQL: Data Type Syntax Maximum Size Explanation DATE Values range from '1000-01-01' to '9999-12-31'. Displayed as 'YYYY-MM-DD'. DATETIME Values range from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'. Displayed as 'YYYY-MM-DD HH:MM:SS'. TIMESTAMP(m) Values range from '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC. Displayed as 'YYYY-MM-DD HH:MM:SS'. TIME Values range from '-838:59:59' to '838:59:59'. Displayed as 'HH:MM:SS'. YEAR[(2|4)] Year value as 2 digits or 4 digits. Default is 4 digits.
  • 8. Introduction to SQL Prof. K. Adisesha 8 String Data Type: Although the numeric and date types are most data you'll store will be in a string format. Data Type Syntax Maximum Size Explanation CHAR(size) Maximum size of 255 characters. Where size is the number of characters to store. Fixed-length strings. Space padded on right to equal size characters. VARCHAR(size) Maximum size of 255 characters. Where size is the number of characters to store. Variable-length string. TEXT(size) Maximum size of 65,535 characters. Where size is the number of characters to store. LONGTEXT(size) Maximum size of 4GB or 4,294,967,295 characters. Where size is the number of characters to store. BINARY(size) Maximum size of 255 characters. Where size is the number of binary characters to store. Fixed-length strings. Space padded on right to equal size characters. VARBINARY(size) Maximum size of 255 characters. Where size is the number of characters to store. Variable-length string
  • 9. SQL Programming Prof. K. Adisesha 9 SQL Programming: DDL: A data definition language or data description language (DDL) is syntax similar to a computer programming language for defining data structures, especially database schemas.- ➢ Commands in DDL are: ❖ CREATE ❖ DROP ❖ TRUNCATE ❖ RENAME ❖ ALTER ❖ BACKUP DATABASE
  • 10. SQL Programming Prof. K. Adisesha 10 Data Definition Language : DDL: ➢ Syntax: ❖ CREATE Statement: Create table tablename (column_name1 data_ type constraints, column_name2 data_ type constraints); ➢ Example: ❖ Query to create a table employee with empno, ename, designation, and salary. ✓ SQL>CREATE TABLE EMP (EMPNO NUMBER (4), ENAME VARCHAR2 (10), DESIGNATIN VARCHAR2 (10), SALARY NUMBER (8,2)); ❖ Query for create a from an existing table with all the fields. ✓ SQL> CREATE TABLE EMP1 AS SELECT * FROM EMP;
  • 11. SQL Programming Prof. K. Adisesha 11 Data Definition Language: DDL: ➢ Syntax: ❖ CREATE Statement: Create table tablename (column_name1 data_ type constraints, column_name2 data_ type constraints); ➢ Example: 1.CREATE TABLE students 2.( 3.S_Id int(4) NOT NULL PRIMARY KEY, 4. S_Name varchar (255) NOT NULL, 5.Address varchar (255), 6.City varchar (255), 7.) ✓ SQL> DESC Students Name Null? Type ----------------------------------------- -------- S_Id NOT NULL NUMBER (4) S_NAME NOT NULL VARCHAR2 (255) Address VARCHAR2 (255) City VARCHAR2 (255)
  • 12. SQL Programming Prof. K. Adisesha 12 Data Definition Language: SYNTAX: ❖ DROP:DROP TABLE table_name; ❖ TRUNCATE: TRUNCATE TABLE table_name; ❖ RENAME: RENAME TABLE {tbl_name} TO {new_tbl_name}; ❖ ALTER: ✓ Add column to Table: ALTER TABLE table_name ADD column_name column-definition; ✓ Modify column in Table: ALTER TABLE table_name MODIFY column_namecolumn_type; ✓ Drop column in Table:ALTER TABLE table_name DROP COLUMN column_name;
  • 13. SQL Programming Prof. K. Adisesha 13 Data Definition Language: Alter Command: Example: ❖ Query to Alter the column EMPNO NUMBER(4) TO EMPNO NUMBER(6). ✓ SQL>ALTER TABLE EMP MODIFY EMPNO NUMBER (6); ❖ Query to add a new column in to employee. ✓ SQL> ALTER TABLE EMP ADD QUALIFICATION VARCHAR2(6); ❖ Query to drop a column from an existing table employee. ✓ SQL> ALTER TABLE EMP DROP COLUMN DOJ; ❖ Query to drop an existing table employee. ✓ SQL> DROP table employee;
  • 14. SQL Programming Prof. K. Adisesha 14 Data Definition Language: BACKUP DATABASE: This statement is used to create a full backup of an existing database. ❖ Syntax. ✓ BACKUP DATABASE DatabaseName TO DISK = 'filepath'; ❖ Example. ✓ BACKUP DATABASE Employee TO DISK = 'C:Desktop'; ➢ You can also use a differential back up. This type of back up only backs up the parts of the database, which have changed since the last complete backup of the database. ❖ Syntax. ✓ BACKUP DATABASE DatabaseName TO DISK = 'filepath’WITH DIFFERENTIAL; ❖ Example: ✓ BACKUP DATABASE Employee TO DISK = ‘C:Desktop’WITH DIFFERENTIAL;
  • 15. SQL Programming Prof. K. Adisesha 15 Different Types Of Keys In Database: There are mainly 7 types of Keys, that can be considered in a database. ➢ Candidate Key – A set of attributes which can uniquely identify a table can be termed as a Candidate Key. ➢ Super Key – The set of attributes which can uniquely identify a tuple is known as Super Key. ➢ Primary Key – A set of attributes which are used to uniquely identify every tuple is also a primary key. ➢ Alternate Key – Alternate Keys are the candidate keys, which are not chosen as a Primary key. ➢ Unique Key – The unique key is similar to the primary key, but allows one NULL value in the column. ➢ Foreign Key – An attribute that can only take the values present as the values of some other attribute, is the foreign key to the attribute to which it refers. ➢ Composite Key – A composite key is a combination of two or more columns that identify each tuple uniquely.
  • 16. SQL Programming Prof. K. Adisesha 16 Constraints Used In Database: Constraints are used in a database to specify the rules for data in a table. The following are the different types of constraints: ➢ NOT NULL: This constraint ensures that a column cannot have a NULL value. ➢ UNIQUE: This constraint ensures that all the values in a column are unique. ➢ CHECK: This constraint ensures that all the values in a column satisfy a specific condition. ➢ DEFAULT: This constraint consists of a set of default values for a column when no value is specified ➢ INDEX: This constraint is used to create indexes in the table, through which you can create and retrieve data from the database very quickly.
  • 17. SQL Programming Prof. K. Adisesha 17 Data Manipulation Language : DML: A data manipulation language (DML) is a family of syntax elements similar to a computer programming language used for selecting, inserting, deleting and updating data in a database. ➢ Performing read-only queries of data is sometimes also considered a component of DML. ➢ Commands in DML are: ❖ USE ❖ INSERT ❖ UPDATE ❖ DELETE ❖ SELECT
  • 18. SQL Programming Prof. K. Adisesha 18 Data Manipulation Language: USE: The USE statement is used to select the database on which you want to perform operations. ➢ Syntax: USE DatabaseName; ➢ Example: USE EmployeeDB; DELETE: It is used to remove one or more row from a table. ➢ Syntax: DELETE FROM table_name [WHERE condition]; ➢ Example: DELETE FROM employee WHERE Author="Sunny";
  • 19. SQL Programming Prof. K. Adisesha 19 Data Manipulation Language : INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a table. ➢ Syntax: INSERT INTO TABLE_NAME (col1, col2, col3,.... col N) VALUES (value1, value2, value3, .... valueN); Or INSERT INTO TABLE_NAME VALUES (value1, value2, value3, .... valueN); ➢ Example: INSERT INTO Studentdb (RegNo, Name) VALUES (“001", “Sunny");
  • 20. SQL Programming Prof. K. Adisesha 20 Data Manipulation Language: UPDATE: This command is used to update or modify the value of a column in the table. ➢ Syntax: UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE CONDITION] ➢ Example: UPDATE students SET User_Name = ‘Sunny' WHERE Student_Id = '3’;
  • 21. SQL Programming Prof. K. Adisesha 21 Data Manipulation Language: 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 or SELECT * FROM employee; FROM employee WHERE age > 20;
  • 22. SQL Programming Prof. K. Adisesha 22 Data Manipulation Language: SELECT: Apart from just using the SELECT keyword individually, you can use the following keywords with the SELECT statement: ➢ DISTINCT ➢ ORDER BY ➢ GROUP BY ➢ HAVING Clause ➢ INTO
  • 23. SQL Programming Prof. K. Adisesha 23 Data Manipulation Language: SELECT DISTINCT: This statement is used to return only different values. ➢ Syntax: SELECT DISTINCT Column1, Column2, ...ColumnN FROM TableName; ➢ Example: SELECT DISTINCT PhoneNumber FROM Student_Info; ORDER BY: The ‘ORDER BY’ statement is used to sort the required results in ascending or descending order. The results are sorted in ascending order by default. ➢ Syntax: SELECT Column1, Column2, ...ColumnN FROM TableName ORDER BY Column1, Column2, ... ASC|DESC; ➢ Example: SELECT * FROM Student_Info ORDER BY ContactName DESC;
  • 24. SQL Programming Prof. K. Adisesha 24 Data Manipulation Language: GROUP BY: This ‘GROUP BY’ statement is used with the aggregate functions to group the result-set by one or more columns. ➢ Syntax: SELECT Column1, Column2,..., ColumnN FROM TableName WHERE Condition GROUP BY ColumnName(s); ➢ Example: SELECT COUNT(Studient_ID), City FROM Student_Info GROUP BY City; SELECT INTO: The ‘SELECT INTO’ statement is used to copy data from one table to another. ➢ Syntax: SELECT * INTO NewTable [IN ExternalDB] FROM OldTable WHERE Condition; ➢ Example: SELECT * INTO BCA_Student FROM Student_info WHERE Course = ‘BCA';
  • 25. SQL Programming Prof. K. Adisesha 25 Data Manipulation Language: ‘HAVING’ Clause: The ‘HAVING’ clause is used in SQL because the WHERE keyword cannot be used everywhere. ➢ Syntax: SELECT ColumnName(s) FROM TableName WHERE Condition GROUP BY ColumnName(s) HAVING Condition ORDER BY ColumnName(s); ➢ Example: SELECT COUNT(Student_ID), City FROM Student_Info GROUP BY Course HAVING COUNT(Marks) >75 ORDER BY COUNT(Marks) DESC;
  • 26. SQL Programming Prof. K. Adisesha 26 Operators in SQL: The different set of operators available in SQL are as follows:. Arithmetic Operators Comparison Operators Logical Operators ❖ AND ❖ OR ❖ NOT ❖ BETWEEN ❖ LIKE ❖ IN ❖ EXISTS ❖ ALL ❖ ANY
  • 27. SQL Programming Prof. K. Adisesha 27 Arithmetic Operators: We can use various Arithmetic Operators on the data stored in the tables. ➢ Example Arithmetic Operators: ❖ SELECT employee_id, employee_name, salary, salary + 100 AS "salary + 100" FROM addition; ❖ SELECT employee_id, employee_name, salary, salary - 100 AS "salary - 100" FROM subtraction; ❖ SELECT employee_id, employee_name, salary, salary * 100 AS "salary * 100" FROM addition;
  • 28. SQL Programming Prof. K. Adisesha 28 Comparison Operators: In SQL, there are six comparison operators available which help us run queries to perform various operations. We will use the WHERE command along with the conditional operator to achieve this in SQL. ➢ Syntax : ❖ SELECT * FROM TABLE_NAME WHERE ATTRIBUTE CONDITION_OPERATOR GIVEN_VALUE; ➢ Example : ❖ SELECT employee_id, employee_name, salary WHERE salary > 10000; ❖ SELECT * FROM Studient_info WHERE MARKS<40;
  • 29. SQL Programming Prof. K. Adisesha 29 Logical Operators: A logical operator like the Comparison operator used to test for the truth of the condition returns a boolean value of TRUE, FALSE, or UNKNOWN. ❖ AND : TRUE if both Boolean expressions are TRUE. ❖ IN : TRUE if the operand is equal to one of a list of expressions. ❖ NOT : Reverses the value of any other Boolean operator. ❖ OR : TRUE if either Boolean expression is TRUE. ❖ LIKE : TRUE if the operand matches a pattern. ❖ ALL : TRUE if all of a set of comparisons are TRUE. ❖ ANY : TRUE if any one of a set of comparisons is TRUE. ❖ EXISTS : TRUE if a subquery contains any rows. ❖ SOME : TRUE if some of a set of comparisons are TRUE. ❖ BETWEEN:TRUE if the operand is within a range.
  • 30. SQL Programming Prof. K. Adisesha 30 Logical Operators: A logical operator like the Comparison operator used to test for the truth of the condition returns a boolean value of TRUE, FALSE, or UNKNOWN. ❖ AND : TRUE if both Boolean expressions are TRUE. SELECT * FROM Employee_Info WHERE City='Mumbai' AND City='Hyderabad'; ❖ IN : TRUE if the operand is equal to one of a list of expressions. SELECT * FROM Employee_Info WHERE City IN ('Mumbai', 'Bangalore', 'Hyderabad'); ❖ NOT : Reverses the value of any other Boolean operator. SELECT * FROM Employee_Info WHERE NOT City='Mumbai';
  • 31. SQL Programming Prof. K. Adisesha 31 Logical Operators: A logical operator like the Comparison operator used to test for the truth of the condition returns a boolean value of TRUE, FALSE, or UNKNOWN. ❖ OR : TRUE if either Boolean expression is TRUE. SELECT * FROM Employee_Info WHERE City='Mumbai' OR City='Hyderabad'; ❖ LIKE : TRUE if the operand matches a pattern. SELECT * FROM Employee_Info WHERE EmployeeName LIKE 'S%'; ❖ ALL : TRUE if all of a set of comparisons are TRUE. SELECT EmployeeName FROM Employee_Info WHERE EmployeeID = ALL (SELECT EmployeeID FROM Employee_Info WHERE City = 'Hyderabad');
  • 32. SQL Programming Prof. K. Adisesha 32 Logical Operators: A logical operator like the Comparison operator used to test for the truth of the condition returns a boolean value of TRUE, FALSE, or UNKNOWN. ❖ ANY : TRUE if any one of a set of comparisons is TRUE. SELECT EmployeeName FROM Employee_Info WHERE EmployeeID = ANY (SELECT EmployeeID FROM Employee_Info WHERE City = 'Hyderabad' OR City = 'Kolkata'); ❖ EXISTS : TRUE if a subquery contains any rows. SELECT EmergencyContactName FROM Employee_Info WHERE EXISTS (SELECT EmergencyContactName FROM Employee_Info WHERE EmployeeId = 05 AND City = 'Kolkata'); ❖ BETWEEN:TRUE if the operand is within a range. SELECT * FROM Employee_Salary WHERE Salary BETWEEN 40000 AND 50000;
  • 33. SQL Programming Prof. K. Adisesha 33 Data Control Language: Data Control Language: DCL commands are used to grant and take back authority from any database user. ➢ Here are some commands that come under DCL: ❖ Grant ❖ Revoke ➢ Grant: It is used to give user access privileges to a database. Example GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER; ➢ Revoke: It is used to take back permissions from the user. Example REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;
  • 34. SQL Programming Prof. K. Adisesha 34 Data Control Language: Grant: This command is used to provide access or privileges on the database and its objects to the users. ➢ Syntax: ❖ GRANT PrivilegeName ON ObjectName TO {UserName |PUBLIC |RoleName} [WITH GRANT OPTION]; ➢ Example -- To grant SELECT permission to Employee_Info table to user1 GRANT SELECT ON Employee_Info TO user1; where, ✓ PrivilegeName – Is the privilege/right/access granted to the user. ✓ ObjectName – Name of a database object like TABLE/VIEW / STORED PROC. ✓ UserName – Name of the user who is given the access/ rights/ privileges. ✓ PUBLIC – To grant access rights to all users. ✓ RoleName – The name of a set of privileges grouped together. ✓ WITH GRANT OPTION – To give the user access to grant other users with rights.
  • 35. SQL Programming Prof. K. Adisesha 35 Data Control Language: REVOKE: This command is used to withdraw the user’s access privileges given by using the GRANT command. ➢ Syntax: ❖ REVOKE PrivilegeName ❖ ON ObjectName ❖ FROM {UserName |PUBLIC |RoleName} ➢ Example -- To revoke the granted permission from user1 REVOKE SELECT ON Employee_Info TO user1;
  • 36. SQL Programming Prof. K. Adisesha 36 Transaction Control Language: 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
  • 37. SQL Programming Prof. K. Adisesha 37 Transaction Control Language: Commit: Commit command is used to save all the transactions to the database. ➢ Syntax: COMMIT; ➢ Example: INSERT INTO Student_info VALUES(05, ‘Prajwal’,20); COMMIT;
  • 38. SQL Programming Prof. K. Adisesha 38 Transaction Control Language: Rollback: Rollback command is used to undo transactions that have not already been saved to the database. ➢ Syntax: ROLLBACK; ➢ Example: DELETE FROM Student_info WHERE AGE = 21; ROLLBACK; SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back the entire transaction. ➢ Syntax: SAVEPOINT SAVEPOINT_NAME; ➢ Example: UPDATE Student_info SET name = ‘Sunny' WHERE id = '05’; SAVEPOINT S1;
  • 39. SQL Programming Prof. K. Adisesha 39 SQL Joins: JOINS are used to combine rows from two or more tables, based on a related column between those tables. ➢ The following are the types of joins: ❖ INNER JOIN: This join returns those records which have matching values in both the tables. ❖ FULL JOIN: This join returns all those records which either have a match in the left or the right table. ❖ LEFT JOIN: This join returns records from the left table, and also those records which satisfy the condition from the right table. ❖ RIGHT JOIN: This join returns records from the right table, and also those records which satisfy the condition from the left table.
  • 40. SQL Programming Prof. K. Adisesha 40 SQL Joins: JOINS are used to combine rows from two or more tables, based on a related column between those tables. ➢ The following are the types of joins: ❖ INNER JOIN: This join returns those records which have matching values in both the tables. ❖ FULL JOIN: This join returns all those records which either have a match in the left or the right table. ❖ LEFT JOIN: This join returns records from the left table, and also those records which satisfy the condition from the right table. ❖ RIGHT JOIN: This join returns records from the right table, and also those records which satisfy the condition from the left table.
  • 41. SQL Programming Prof. K. Adisesha 41 SQL Joins: JOINS are used to combine rows from two or more tables, based on a related column between those tables. ❖ INNER JOIN: This join returns those records which have matching values in both the tables. Syntax SELECT column_name(s) FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name; Example SELECT Orders.OrderID, Customers.CustomerName FROM Orders INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
  • 42. SQL Programming Prof. K. Adisesha 42 SQL Joins: JOINS are used to combine rows from two or more tables, based on a related column between those tables. ❖ FULL JOIN: This join returns all those records which either have a match in the left or the right table. Syntax SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name = table2.column_name WHERE condition; Example SELECT Customers.CustomerName, Orders.OrderID FROM Customers FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName;
  • 43. SQL Programming Prof. K. Adisesha 43 SQL Joins: JOINS are used to combine rows from two or more tables, based on a related column between those tables. ❖ LEFT JOIN: This join returns records from the left table, and also those records which satisfy the condition from the right table. Syntax: SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name; Example SELECT Customers.CustomerName, Orders.OrderID FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID ORDER BY Customers.CustomerName;
  • 44. SQL Programming Prof. K. Adisesha 44 SQL Joins: JOINS are used to combine rows from two or more tables, based on a related column between those tables. ❖ RIGHT JOIN: This join returns records from the right table, and also those records which satisfy the condition from the left table. Syntax: SELECT ColumnName(s) FROM Table1 RIGHT JOIN Table2 ON Table1.ColumnName = Table2.ColumnName; Example SELECT Orders.OrderID, Employees.LastName, Employees.FirstName FROM Orders RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID ORDER BY Orders.OrderID;
  • 45. SQL Programming Prof. K. Adisesha 45 SQL UNION Operator: The UNION operator is used to combine the result-set of two or more SELECT statements. ➢ Every SELECT statement within UNION must have the same number of columns ➢ The columns must also have similar data types ➢ The columns in every SELECT statement must also be in the same order. Syntax: SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2; Example SELECT City FROM Customers UNION SELECT City FROM Suppliers ORDER BY City;
  • 46. SQL Programming Prof. K. Adisesha 46 SQL GROUP BY Statement: The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country". ➢ The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more columns. Syntax: SELECT column_name(s) FROM table_name WHERE condition GROUP BY column_name(s) ORDER BY column_name(s); Example SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country ORDER BY COUNT(CustomerID) DESC;
  • 47. SQL Programming Prof. K. Adisesha 47 SQL HAVING Clause: The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country". ➢ The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate functions. Syntax: SELECT column_name(s) FROM table_name GROUP BY column_name(s) HAVING condition ORDER BY column_name(s)); Example SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country HAVING COUNT(CustomerID) > 5;
  • 48. PL/SQL Prof. K. Adisesha 48 PL/SQL Programming: The PL/SQL programming language was developed by Oracle Corporation in the late 1980s as procedural extension language for SQL and the Oracle relational database. . ➢ Following are certain notable facts about PL/SQL − ❖ 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. ❖ Direct call can also be made from external programming language calls to database. ❖ PL/SQL's general syntax is based on that of ADA and Pascal programming language.
  • 49. PL/SQL Prof. K. Adisesha 49 Features of PL/SQL: PL/SQL has the following features − ➢ PL/SQL is tightly integrated with SQL. ➢ It offers extensive error checking. ➢ It offers numerous data types. ➢ It offers a variety of programming structures. ➢ It supports structured programming through functions and procedures. ➢ It supports object-oriented programming. ➢ It supports the development of web applications and server pages.
  • 50. PL/SQL Prof. K. Adisesha 50 Advantages of PL/SQL: ➢ SQL is the standard database language and PL/SQL is strongly integrated with SQL. PL/SQL supports both static and dynamic SQL. Static SQL supports DML operations and transaction control from PL/SQL block. In Dynamic SQL, SQL allows embedding DDL statements in PL/SQL blocks. ➢ PL/SQL allows sending an entire block of statements to the database at one time. This reduces network traffic and provides high performance for the applications. ➢ PL/SQL gives high productivity to programmers as it can query, transform, and update data in a database. ➢ PL/SQL saves time on design and debugging by strong features, such as exception handling, encapsulation, data hiding, and object-oriented data types.
  • 51. PL/SQL Procedure Prof. K. Adisesha 51 PL/SQL Procedure: The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or more specific tasks. It is just like procedures in other programming languages. ➢ The procedure contains a header and a body. ❖ Header: The header contains the name of the procedure and the parameters or variables passed to the procedure. ❖ Body: The body contains a declaration section, execution section and exception section similar to a general PL/SQL block. CREATE [OR REPLACE] PROCEDURE procedure_name [ (parameter [,parameter]) ] IS [declaration_section] BEGIN executable_section [EXCEPTION exception_section] END [procedure_name];
  • 52. Introduction Prof. K. Adisesha 52 PL/SQL - Basic Syntax: PL/SQL which is a block-structured language in which PL/SQL programs are divided and written in logical blocks of code. ➢ Each block consists of three sub-parts ❖ Declarations: This section starts with the keyword DECLARE. It is an optional section and defines all variables, cursors, subprograms, and other elements to be used in the program. ❖ Executable Commands: This section is enclosed between the keywords BEGIN and END and it is a mandatory section. It consists of the executable PL/SQL statements of the program. ❖ Exception Handling: This section starts with the keyword EXCEPTION. This optional section contains exception(s) that handle errors in the program.
  • 53. Introduction Prof. K. Adisesha 53 PL/SQL Comments: Program comments are explanatory statements that can be included in the PL/SQL code that you write and helps anyone reading its source code. ➢ All characters available inside any comment are ignored by the PL/SQL compiler. ➢ The PL/SQL supports single-line and multi-line comments. ❖ The PL/SQL single-line comments start with the delimiter -- (double hyphen) ❖ multi-line comments are enclosed by /* and */.
  • 54. Discussion Prof. K. Adisesha (Ph. D) 54 Queries ? Prof. K. Adisesha 9449081542