(Structured Query Language) : DBA Lounge
(Structured Query Language) : DBA Lounge
DBA Lounge
Module 1 - Getting started with RDBMS & SQL
Session 1 - Introduction to RDBMS & SQL
Session 4 - SQL Data Modeling and SQL Intro Assignments (Practice Ses-
sion)
Session 2 - Joins
Session 3 - Procedures
2
Module 1 - Getting started
with RDBMS & SQL
3
4
Session 1 - Introduction to
RDBMS & SQL
What is Database
To find out what database is, we have to start from data, which is the basic
building block of any DBMS.
Record Collection of related data items, e.g. in the above example the
three data items had no meaning. But if we organize them in the following
way, then they collectively represent meaningful information.
Table or Relation
5
Database
6
delete data items in the database.
The management system can be either manual or computerized.
Relational model represents data in the form a table. A table is a two dimen-
sional array containing rows and columns. Each row contains data related
to an entity such as a student. Each column contains the data related to a
single attribute of the entity such as student name.
Terminologies
Tuple/Row
A single row in the table is called as tuple. Each row represents the data of
a single entity.
Attribute/Column
Primary Key
If you take STUDETNS table, it contains data related to students. For each
student there will be one row in the table.Each students data in the table
must be uniquely identified. In order to identify each entity uniquely in the
table, we use a column in the table. That column, which is used to uniquely
identify entities (students) in the table, is called as Primary Key.
7
Composite Primary Key
Foreign Key
In relational model, we often store data in different tables and put them
together to get complete information. For example, in PAYMENTS table
we have only ROLLNO of the student. To get remaining information about
the student we have to use STUDETNS table. Roll number in PAYMENTS
table can be used to obtain remaining information about the student.
The relationship between entities student and payment is one-to-many. One
student may make payment for many times. As we already have ROLLNO
column in PAYMENTS table, it is possible to join with STUDENTS table
and get information about parent entity (student). Roll number column of
PAYMENTS table is called as foreign key as it is used to join PAYMENTS
table with STUDENTS table. So, Foreign Key is the key on the many
side of the relationship.
8
DCL (Data Control Language): DCL commands are used to grant and
revoke different privilege to/from user. Example: GRANT, REVOKE
TCL (Transaction Control Language): TCL commands are used to
complete a transaction. Example: COMMIT, ROLLBACK
DQL/DRL (Data Query/Retrieving Language): DQL/DRL com-
mand is used to select retrieve data from database. Example: SELECT
We must evaluate whether there is any gain in using a DBMS over a situa-
tion where we do not use it. Let us summarize the advantages.
9
abstraction:
Physical level: The lowest level of abstraction describes how data are
stored.
Logical level: The next higher level of abstraction, describes what data
are stored in database and what relationship among those data.
View level: The highest level of abstraction describes only part of entire
database.
Constraints
Data Integrity
SQL Constraints are rules used to limit the type of data that can go into a
table, to maintain the accuracy and integrity of the data inside table.
Constraints are of two types:
The NOT NULL constraint enforces a column NOT to accept NULL values.
NOT NULL can’t be applied to table level.
Example:
mysql¿ CREATE TABLE Persons( PID int NOT NULL, LastName var-
char(30) NOT NULL, FirstName varchar(30), Address varchar(60));
UNIQUE Constraint:
Example:
mysql¿CREATE TABLE Persons(PID int ,LastName varchar(30),FirstName
varchar(30),Address varchar(70),UNIQUE (PID)); NOTE: Above constraint
is applied on table level.
10
Defining UNIQUE Constraint on ALTER TABLE:
Example:
mysql¿ ALTER TABLE Persons ADD UNIQUE (PID);
Naming a Constraint:
Example:
mysql¿ ALTER TABLE Persons ADD CONSTRAINT uc PersonID UNIQUE
(PID,LastName);
NOTE:uc PersonID is the Constraint name.
Dropping a Constraint:
Example:
mysql¿ ALTER TABLE Persons DROP INDEX uc PersonID;
A Primary Key uniquely identifies each record. A Primary Key must con-
tain unique values and it must not contain null value.
Example:
mysql¿ CREATE TABLE Persons(PID int ,LastName varchar(30),FirstName
varchar(30),Address varchar(70),PRIMARY KEY (PID));
To create a Primary Key constraint on the “PID” column when the table is
already created.
11
Example:
mysql¿ ALTER TABLE Persons ADD Primary Key (PID);
Naming a Constraint:
Example:
mysql¿ ALTER TABLE Persons ADD CONSTRAINT uc PersonID Pri-
mary Key (PID,LastName);
NOTE:uc PersonID is the Constraint name.
Dropping a Constraint:
Example:
mysql¿ ALTER TABLE Persons DROP Primary Key;
Illustration:
Let’s illustrate the foreign key with an example. Look at the following two
tables:
Person Table
PID Name City
1111 Sachin Mumbai
1112 Ganguly Kolkata
Orders Table
OID OrderNo PID
Note:
1 1234 1111
2 1235 1111
That the “PID” column in the “Orders” table points to the “PID” column
12
in the “Persons” table.
The “PID” column in the “Persons” table is the PRIMARY KEY in the
“Persons” table.
The “PID” column in the “Orders” table is a FOREIGN KEY in the “Or-
ders” table.
The FOREIGN KEY constraint is used to prevent actions that would de-
stroy links between tables.
The FOREIGN KEY constraint also prevents that invalid data from being
inserted into the foreign key column, because it has to be one of the values
contained in the table it points to.
The following SQL creates a FOREIGN KEY on the “PID” column when
the “Orders” table is created:
Example:
mysql> CREATE TABLE Orders( OId int ,OrderNo int ,PId int,PRIMARY
KEY (OId),FOREIGN KEY (PId) REFERENCES Persons(PId));
DEFAULT Constraint:
Example:
mysql> CREATE TABLE Persons(PID int ,LastName varchar(25),FirstName
varchar(25),Address varchar(55),City varchar(55) DEFAULT ’Sandnes’);
To create a DEFAULT constraint on the “City” column when the table is
already created,use the following syntax:
13
14
Session 2 - Working with
DDL - CREATE, ALTER,
DROP
$ mysql u root p
Enter password: root
mysql>SHOW databases;
mysql>SHOW TABLES;
15
Creating a Table
How to create a table by copying the structure only not the data
of an existing Table
mysql>DESC employee;
Alter
16
mysql> ALTER TABLE employee CHANGE empid id VARCHAR (100),
CHANGE newaddress address VARCHAR (100);
Drop
mysql>TRUNCATE employee;
Data Types
17
• DATETIME: A date and time combination. The supported range
is ’1000-01-01 00:00:00’ to ’9999-12-31 23:59:59’. MySQL displays
DATETIME values in ’YYYYMM-DD HH:MM:SS’ format.
• CHAR :The length of a CHAR column is fixed to the length that you
declare when you create the table. The length can be any value from
0 to 255.
18
Session 3 - Working with
DML - INSERT, UPDATE,
DELETE
Data Manipulation Language (DML) statements are used for managing data
within schema objects (e.g. table).
Insert Statement
INSERT statement allows you to insert one or more rows to the table.It is
possible to write INSERT INTO in two forms:
The first form doesn’t specify the column names where the data will be
inserted, only their values. It is used where users need to insert values to all
available columns of a table.
Syntax
INSERT INTO tablename VALUES (value1, value2, value3,...);
Example
mysql> INSERT INTO student VALUES (1,‘Ajay’,‘Hyderabad’);
The second form specifies both the column names and the values to be
inserted. It is used where users need to insert value to specific column(s) of
a given table.
Syntax
INSERT INTO tablename (column1, column2,column3,...) VALUES (value1,
value2, value3,...)
Example
mysql> INSERT INTO student (Rollno, Name)VALUES (2, ‘Rahul’);
19
Update Statement
Delete Statement
20
Session 4 - SQL Data
Modeling and SQL Intro
Assignments (Practice
Session)
21
22
Session 5 - Working with
DRL - SELECT
For example if you need to view only “firstname”, “lastname” and “jobti-
tle” of employee in the “employees” table, you can use the following query:
mysql> SELECT firstname, lastname, jobtitle FROM employees;
Where Clause
Distinct Clause
With DISTINCT clause, you can eliminate the duplicate records while dis-
playing the result. For example, to find how many job titles of all employees
in the employees table, you use DISTINCT keyword in SELECT statement
as follows:
mysql> SELECT DISTINCT jobtitle FROM employees; mysql> SELECT
23
DISTINCT (jobtitle) FROM employees;
The DISTINCT clause can be applied with more than one column. In this
case, the combinations of all columns are used to define the uniqueness of a
record in the return result set.
For example, to get all cities and states of customers in the customers table,
we can use the following query:
mysql< SELECT DISTINCT city, state FROM customers;
ORDER BY Clause
The ORDER BY clause allows you to sort the result set on one or more
columns in ascending or descending order. To sort the result set in ascending
order you use ASC and in descending order you use DESC keywords. By
default, the ORDER BY will sort the result set in ascending order. For
example, to sort the name of employees by firstname, you can execute the
following query:
mysql>SELECT firstname, lastname, jobtitle FROM employees ORDER
BY firstname;
LIMIT Clause
MySQL supports a feature called LIMIT to allow you to constrain the re-
turned records with SELECT statement.
Let’s say you have a database table with 10000 records and you want to get
just first N records, you can use the following query:
Syntax
mysql> SELECT * FROM table LIMIT N;
Example
If you want to get the first five employees in the table employees, you can
use the following query:
The MySQL LIMIT also allows you to get a range of records where you
decide starting record number and how many records you want to retrieve.
Syntax
24
mysql> SELECT columns FROM table LIMIT S, N;
NOTE: In the query above, S is the starting record index. MySQL specifies
that the first record starts with 0. N is the number of records you want to
select.
Example
Now if you want to get five employees from employee number 10 you can
use MySQL LIMIT with offset as follows:
mysql> SELECT firstname, lastname FROM employees LIMIT 10, 5;
IN Operator
SQL IN allows you to select values which match any one of a list of values.
The usage of SQL IN is as follows:
Syntax
SELECT columnlist FROM tablename WHERE column IN (“listitem1”,“listitem2”);
Example
Suppose if you want to find out all offices which are located in US and
France, you can perform the following query:
Example
To get all countries which are not located in USA or France, we can use
NOT IN in the where clause as follows:
LIKE Operator
MySQL provides LIKE operator in SQL standard. The MySQL LIKE op-
erator is commonly used to select data based on patterns matching.
MySQL provides you two wildcard characters for using with LIKE:
The Percentage (%) wildcard allows you to match any string of zero or more
characters.
Underscore ( ) allows you to match any single character.
25
Syntax
SELECT * from table where column LIKE PATTERN;
Example
Suppose you want to search for employee in employees table who has first
name starting with character ‘a’, you can do it as follows:
26
Session 6 - Working with
DRL - Subqueries
In the above statement the inner query will be parsed first and the result
will be passed to the outer query.
Types of SubQueries
• Scalar SubQueries
• SubQueries with ANY,ALL,IN
• SubQueries with EXISTS and NOT EXISTS
27
• Correlated SubQueries
Scalar SubQueries
• If the subquery returns 0 rows then the value of scalar subquery ex-
pression in NULL.
• If the subquery returns more than one row then MySQL returns an
error.
Figure 1: figure
Scalar SubQuery using Max function
NOTE:The above query returns data for all customers and their orders
where the orders were shipped on the most recent recorded day.
28
Price desc;
NOTE:This query returns all products whose unit price is greater than av-
erage unit price of all Products.
The ALL keyword specifies that the search condition is TRUE if the com-
parison is TRUE for every value that the subquery returns.
In the following example, the first condition tests whether each unitprice is
greater than the unitprice of productid=1.
Figure 2: figure
Subquery using ALL
29
Subquery using ANY
The ANY keyword denotes that the search condition is TRUE if the compar-
ison is TRUE for at least one of the values that is returned. If the subquery
returns no value, the search condition is FALSE. The SOME keyword is a
synonym for ANY.
Figure 3: figure
SubQuery using ANY
30
Figure 4: figure
Exists Condition
Figure 5: figure
Not Exists Condition
when there are no records in the order details table for the given customer id.
INSERT into contacts (contact id, contact name) select supplier id,
supplier name from suppliers where EXISTS (select * from orders
where suppliers.supplier id = orders.supplier id);
NOTE:The above example will insert records into contacts table if sup-
plier id of suppliers and orders table matches.
31
Subquery using EXISTS and DELETE
Correlated SubQueries
Figure 6: figure
Correlated SubQuery
32
Session 7 - DRL Assignments
(Practice Session)
33
34
Module 2 - Advanced SQL
Concepts
35
36
Session 1 - Built-In functions
and Grouping result
Functions
Aggregrate Functions
AVG()
Syntax
SELECT AVG(columnname) FROM tablename;
Example
sql>SELECT AVG(SAL) from employees;
COUNT()
The COUNT() function returns the number of rows that matches a specified
criteria.
textbfSyntax
SELECT COUNT(columnname) FROM tablename;
37
The COUNT(columnname) function returns the number of values (NULL
values will not be counted) of the specified column:
textbfExample
mysql> SELECT COUNT(empno) FROM employees;
MAX()
: The MAX() function returns the largest value of the selected column.
Syntax
SELECT MAX(columnname) FROM tablename;
Example
sql>SELECT MAX(sal) FROM employees;
MIN()
: The MIN() function returns the smallest value of the selected column.
Syntax
SELECT MIN(columnname) FROM tablename;
Example
sql>SELECT MIN(sal) FROM employees;
SUM()
Syntax
SELECT SUM(columnname) FROM tablename;
Example
sql>SELECT SUM(sal) FROM employees;
38
ROUND()
Syntax
SELECT ROUND(columnname,number) FROM tablename;
Example
mysql> select ROUND(sal,2) from employees;
TRUNCATE()
Syntax
SELECT TRUNCATE(columnname,number) FROM tablename;
Example
mysql> SELECT TRUNCATE(sal,2) from employees;
SCALAR Functions
UCASE()
Syntax
SELECT UCASE(columnname) FROM tablename;
Example
mysql> SELECT UCASE(ename) from employees;
LCASE()
39
LENGTH()
Syntax
SELECT LENGTH(columnname) FROM tablename;
Example
mysql> SELECT LCASE(ename) FROM employees;
MID()
Syntax
SELECT MID(column,pos) from tablename;
Example
mysql> SELECT MID(ename,3) FROM emp WHERE ename=’SANTOSH’;
Note: Above specified 3 is the starting character and ending character.
REPLACE()
Returns the string with all occurrences of the string from str replaced by
the string to str. Syntax SELECT REPLACE(str,from str,to str) FROM
tablename;
Example mysql> SELECT REPLACE(ename,’a’,’A’) FROM employee;
DATE Functions
NOW()
Example
mysql> SELECT NOW() FROM dual;
40
CURDATE()
Example
mysql> SELECT CURDATE() FROM dual;
CURTIME()
Example
mysql> SELECT CURTIME() FROM dual;
EXTRACT()
Example
mysql> SELECT EXTRACT(year FROM now()) FROM dual;
mysql> SELECT EXTRACT(month FROM now()) FROM dual;
mysql> SELECT EXTRACT(day FROM now()) FROM dual;
mysql> SELECT EXTRACT(hour FROM now()) FROM dual;
mysql> SELECT EXTRACT(minute FROM now()) FROM dual;
mysql> SELECT EXTRACT(second FROM now()) FROM dual;
DATE ADD()
Example
mysql> SELECT DATE ADD(NOW(),INTERVAL 10 DAY) FROM dual;
DATE SUB()
41
Example
mysql> SELECT DATE SUB(NOW(),INTERVAL 10 DAY) FROM dual;
DATEDIFF()
Example
mysql> SELECT DATEDIFF(NOW(),‘20130612’) FROM dual;
mysql> SELECT DATEDIFF(NOW(),‘20000612’) FROM dual;
mysql> SELECT (DATEDIFF(NOW(),‘20000612’))/365 FROM dual;
DATE FORMAT()
GROUP BY Clause
Example
Let’s say if you want to know how many orders in each status group you
can use the COUNT function as follows:
42
mysql> SELECT status, count (*) FROM orders GROUP BY status;
If you want to see the result of the query above in the descending order, you
can do it as follows:
mysql> SELECT status, count (*) FROM orders GROUP BY status DESC;
HAVING Clause
The HAVING clause is an optional part of and used only with the SQL
SELECT statement. The HAVING clause specifies a filter condition for a
group of record or an aggregate.
The HAVING is often used with GROUP BY clause. When using with
GROUP BY clause, you can apply filter condition of the HAVING clause
only to the columns appear in the GROUP BY clause.
NOTE
If the GROUP BY clause is omitted, the HAVING clause will behave like a
WHERE clause.
HAVING clause applies to groups as a whole while the WHERE clause ap-
plies to individual rows.
Example
What order has total value greater than 1000. In this case, you need to use
the MySQL HAVING clause on aggregate to answer that question.
43
44
Session 2 - Joins
Joins are used to query data from two or more tables, based on a relation-
ship between certain columns in these tables. There are different types of
JOINing methods used in MySQL database, which are given below.
INNER JOIN
Probably the most common join operation MySQL supports is an inner join.
It identifies and combines only matching rows which are stored in two or
more related tables.
A join condition, which indicates how the tables are related, is added with
the keywords ON or USING
NOTE:
Syntax
SELECT <column list > FROM tableA a INNER JOIN tableB b ON
a.somecolumn = b.othercolumn;
Example
mysql> SELECT d.deptno, d.dname, e.empno, e.ename FROM dept d IN-
NER JOIN emp e ON d.deptno = e.deptid;
45
INNER JOIN with USING clause syntax
Syntax
SELECT * FROM tableA a INNER JOIN tableB b USING(columnname);
Example
SELECT d.deptno, d.dname, e.empno, e.ename FROM dept d INNER JOIN
emp e USING (deptno);
OUTER JOIN
The difference between inner and outer join is: An outer join can iden-
tify rows without a match in the joined table. When no match was found,
MySQL sets the value of columns from the joined table to NULL.
This type of join will display matching records from both tables and all
unmatched records of the left table. Left table means which table name is
listed on the left side of the JOIN keywords.
Syntax
SELECT <column list> FROM table1 a LEFT OUTER JOIN table2 b ON
a.somecolumn = b.othercolumn;
Example
SELECT d.deptno, d.dname, e.empno, e.ename FROM dept d LEFT OUTER
JOIN employees e ON d.deptno = e.deptnumber;
This type of join will display matching records from both tables and all un-
matched records of the right table. Right table means which table name is
listed on the right side of the JOIN keywords.
Syntax
46
SELECT <column list> FROM table1 a RIGHT OUTER JOIN table2 b
ON a.somecolumn = b.othercolumn;
Example
SELECT d.deptno, d.dname, e.empno, e.ename FROM dept d RIGHT
OUTER JOIN employees e ON d.deptno = e.deptnumber;
SELF JOIN
Example Suppose you’re tasked with writing a SQL query to retrieve a list
of employees and their managers.
CROSS JOIN
The cross join operation retrieves data between two tables as a Cartesian
product of set theory in mathematics. Each row will get multiplied by other
rows. If one table has three rows and the second row has two rows, then the
Cartesian of two table will be six.
Example
47
48
Session 3 - Procedures
0.1 Procedures
A subprogram is a program unit/module that performs a particular task.
These subprograms are combined to form larger programs. This is basi-
cally called the ’Modular design’. A subprogram can be invoked by another
subprogram or program which is called the calling program.
A subprogram can be created:
1. At schema level
2. Inside a package
3. Inside a PL/SQL block
49
S.No Parts & Description
Declarative Part
1 It is an optional part. However, the declarative part for a sub-
program does not start with the DECLARE keyword. It contains
declarations o f types, cursors, constants, variables, exceptions,
and nested subprograms. These items are local to the subprogram
and cease to exist whe n the subprogram completes execution.
Executable Part
2 This is a mandatory part and contains statements that perform
the designated action.
Exception-handling
3 This is again an optional part. It contains the code that handles
run-time errors.
Where,
3. The optional parameter list contains name, mode and types of the
parameters. IN represents that value will be passed from outside and
OUT represents that this parameter will be used to return a value
outside of the procedure.
50
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line(’Hello World!’);
END;
/
When above code is executed using SQL prompt, it will produce the follow-
ing result: Output: Procedure created.
The above procedure named ’greetings’ can be called with the EXECUTE
keyword as:
EXECUTE greetings;
The above call would display:
Hello World PL/SQL procedure successfully completed.
The procedure can also be called from another PL/SQL block:
BEGIN
greetings;
END;
/
BEGIN
DROP PROCEDURE greetings;
END;
/
51
S.N. Parameter Mode & Description
IN
1 An IN parameter lets you pass a value to the subprogram. It is
a read-only parameter. Inside the subprogram, an IN parameter
acts like a constant. It cannot be assigned a value. You can
pass a constant, literal, initialized variable, or expression as an IN
parameter. You can also initialize it to a default value; however, in
that case, it is omitted from the subprogram call. It is the default
mode of parameter passing. Parameters are passed by reference.
OUT
2 An OUT parameter returns a value to the calling program. Inside
the subprogram, an OUT parameter acts like a variable. You can
change its value and reference the value after assigning it. The
actual parameter must be variable and it is passed by value.
IN OUT
3 An IN OUT parameter passes an initial value to a subprogram and
returns an updated value to the caller. It can be assigned a value
and its value can be read. The actual parameter corresponding to
an IN OUT formal parameter must be a variable, not a constant or
an expression. Formal parameter must be assigned a value.Actual
parameter is passed by value.
This program finds the minimum of two values, here procedure takes two
numbers using IN mode and returns their minimum using OUT parameters.
DECLARE
a number;
b number;
c number;
BEGIN
52
a:= 23;
b:= 45;
findMin(a, b, c);
dbms_output.put_line(’ Minimum of (23, 45) : ’ || c);
END;
/
When the above code is executed at SQL prompt, it produces the following
result: Output: Minimum of (23, 45) : 23 PL/SQL procedure successfully
completed.
This procedure computes the square of value of a passed value. This example
shows how we can use same parameter to accept a value and then return
another result.
DECLARE
a number;
PROCEDURE squareNum(x IN OUT number) IS
BEGIN
x := x * x;
END;
BEGIN
a:= 23;
squareNum(a);
dbms_output.put_line(’ Square of (23): ’ || a);
END;
/
When the above code is executed at SQL prompt, it produces the follow-
ing result: Output: Square of (23): 529 PL/SQL procedure successfully
completed.
1. Positional notation
2. Named notation
3. Mixed notation
53
POSITIONAL NOTATION
NAMED NOTATION
In named notation, the actual parameter is associated with the formal pa-
rameter using the arrow symbol ( =>). So the procedure call would look
like:
findMin(x=>a, y=>b, z=>c, m=>d);
MIXED NOTATION
In mixed notation, you can mix both notations in procedure call; however,
the positional notation should precede the named notation.
The following call is legal:
findMin(a, b, c, m=>d);
But this is not legal:
findMin(x=>a, b, c, d);
54
Session 4 - DRL Assignments
(Practice Session)
55