Unit 3 notes DBMS final
Unit 3 notes DBMS final
Unit 3 notes DBMS final
These are used for creation, deletion, and modification of definitions for database tables
and views.
In order to make/perform changes on the physical structure of any table residing inside a
database, DDL is used. These commands when executed are auto commit in nature and
all the changes in the table are reflected and saved immediately. DDL commands
includes :
Once the tables are created and database is generated using DDL commands,
manipulation inside those tables and databases is done using DML commands. The
advantage of using DML commands is, if in case any wrong changes or values are made,
they can be changes and rolled back easily. DML commands includes :
Delete from tablename where condition;
DCL commands as the name suggests manages the matters and issues related to the data
control in any database. TCL commands mainly provides special privilege access to users
and is also used to specify the roles of users accordingly. There are two commonly used
DCL commands, these are:
Transaction Control Language as the name suggests manages the issues and matters
related to the transactions in any database. They are used to rollback or commit the
changes in the database.
Roll back means “Undo” the changes and Commit means “Applying” the changes. There
are three major TCL commands.
Savepoint <save point name>;
Savepoint A;
Rollback to savepoint A;
The form of a Basic SQL query:
From-list : From-list in the FROM clause is a list of table name( relation names). A table name
can be followed by a range variable; a range variable particularly useful when the same table
name appears more than once in the from-list.
select-list A list of column names of tables named in the table-list. Column names can be
prefixed by range variable name.
qualification in the WHERE clause is Boolean expression using relational
operators(<,>,<=,>=, <>, =) and logical operators AND, OR and NOT. The qualification
starts with WHERE clause that is used to specify selection conditions on the tables mentioned in
the FROM clause.
DISTINCT is optional keyword indicating that answer should not contain duplicates.
Examples:
create table dept(
deptno number(2,0),
dname varchar2(14),
loc varchar2(13),
constraint pk_dept primary key (deptno)
);
Aggregate Functions
The following are the most commonly used SQL aggregate functions:
SQL | ORDER BY
The ORDER BY statement in sql is used to sort the fetched data in either ascending or
descending according to one or more columns.
By default ORDER BY sorts the data in ascending order.
We can use the keyword DESC to sort the data in descending order and the keyword
ASC to sort in ascending order.
Syntax of all ways of using ORDER BY is shown below:
Sort according to one column: To sort in ascending or descending order we can use the
keywords ASC or DESC respectively.
Syntax:
SELECT * FROM table_name ORDER BY column_name ASC|DESC
Sort according to multiple columns: To sort in ascending or descending order we can use the
keywords ASC or DESC respectively. To sort according to multiple columns, separate the names
of columns by (,) operator.
Syntax:
SELECT * FROM table_name ORDER BY column1 ASC|DESC , column2 ASC|DESC
SQL | GROUP BY
The GROUP BY Statement in SQL is used to arrange identical data into groups with the help of
some functions. i.e if a particular column has same values in different rows then it will arrange
these rows in a group.
Important Points:
GROUP BY clause is used with the SELECT statement.
In the query, GROUP BY clause is placed after the WHERE clause.
In the query, GROUP BY clause is placed before ORDER BY clause if used any.
Syntax:
SELECT column1, function_name(column2)
FROM table_name
WHERE condition
GROUP BY column1, column2
ORDER BY column1, column2;
Sample Table:
Employee
Student
Example:
Group By single column: Group By single column means, to place all the rows with
same value of only that particular column in one group. Consider the query as shown below:
SELECT NAME, SUM(SALARY) FROM Employee
GROUP BY NAME;
The above query will produce the below output:
As you can see in the above output, the rows with duplicate NAMEs are grouped under
same NAME and their corresponding SALARY is the sum of the SALARY of duplicate
rows. The SUM() function of SQL is used here to calculate the sum.
Group By multiple columns: Group by multiple column is say for example, GROUP
BY column1, column2. This means to place all the rows with same values of both the
columns column1 and column2 in one group. Consider the below query:
SELECT SUBJECT, YEAR, Count(*)
FROM Student
GROUP BY SUBJECT, YEAR;
Output:
As you can see in the above output the students with both same SUBJECT and YEAR are
placed in same group. And those whose only SUBJECT is same but not YEAR belongs to
different groups. So here we have grouped the table according to two columns or more than
one column.
HAVING Clause
We know that WHERE clause is used to place conditions on columns but what if we want to
place conditions on groups?
This is where HAVING clause comes into use. We can use HAVING clause to place conditions
to decide which group will be the part of final result-set. Also we can not use the aggregate
functions like SUM(), COUNT() etc. with WHERE clause. So we have to use HAVING clause if
we want to use any of these functions in the conditions.
Syntax:
SELECT column1, function_name(column2)
FROM table_name
WHERE condition
GROUP BY column1, column2
HAVING condition
ORDER BY column1, column2;
Nested Queries
Nested query is a query within another SQL query and embedded within the WHERE clause.
Embedded query is called Subquery.
A subquery is used to return data that will be used in the main query as a condition to further
restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along
with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
There are a few rules that subqueries must follow −
Subqueries must be enclosed within parentheses.
A subquery can have only one column in the SELECT clause, unless multiple columns
are in the main query for the subquery to compare its selected columns.
An ORDER BY command cannot be used in a subquery, although the main query can
use an ORDER BY. The GROUP BY command can be used to perform the same
function as the ORDER BY in a subquery.
Subqueries that return more than one row can only be used with multiple value operators
such as the IN operator.
The SELECT list cannot include any references to values that evaluate to a BLOB,
ARRAY, CLOB, or NCLOB.
A subquery cannot be immediately enclosed in a set function.
The BETWEEN operator cannot be used with a subquery. However, the BETWEEN
operator can be used within the subquery.
Q1) Find names, salaries whose salary greater than the salary of employ ‘SMITH’;
SQL>select Ename,sal from emp where sal > ( select sal from emp where ename like 'smith');
Q2) Display the Ename, Job, Sal from EMP working in the LOC 'CHICAGO' and salary is less
than the salary of whose empno=7876.
SQL> SELECT ENAME, JOB, SAL FROM EMP WHERE DEPINO = (SELECT DEPTNO FR
OM DEPT WHERE LOC='CHICAGO') AND SAL < (SELECT SAL FROM EMP WHERE EM
PNO=7876);
Q3) To retrieve the details of the employee holding the minimum salary.
Q4) finds the employees whose salary is the same as the minimum salary of the employees in
some department.
SQL> SELECT ENAME,SAL FROM EMP WHERE SAL IN (SELECT MIN (SAL) FROM EMP
GROUP BY DEPTNO);
Q5) List all the employees Name and Sal working at the location 'DALLAS'.
SQL> SELECT ENAME, SAL, JOB FROM EMP WHERE DEPTNO IN (SELECT DEPTNO
FROM DEPT WHERE LOC ='DAllAS');
Correlated Subqueries
Correlated subqueries are used for row-by-row processing. Each subquery is executed once for
every row of the outer query.
A correlated subquery is evaluated once for each row processed by the parent statement. The
parent statement can be a SELECT, UPDATE, or DELETE statement.
A correlated subquery is one way of reading every row in a table and comparing values in each
row against related data. It is used whenever a subquery must return a different result or set of
results for each candidate row considered by the main query. In other words, you can use a
correlated subquery to answer a multipart question whose answer depends on the value in each
row processed by the parent statement.
Nested Sub queries Versus Correlated Sub queries :
With a normal nested subquery, the inner SELECT query runs first and executes once, returning
values to be used by the main query. A correlated subquery, however, executes once for each
candidate row considered by the outer query. In other words, the inner query is driven by the
outer query.
NOTE : You can also use the ANY and ALL operator in a correlated subquery.
EXAMPLE of Correlated Subqueries : Find all the employees who earn more than the average
salary in their department.
SQL> SELECT Ename, sal, deptno FROM emp out WHERE sal > (SELECT AVG(sal)
FROM emp inn WHERE inn.deptno = out.deptno);
UNION Operator
The Union operator returns rows from both tables. If used by itself, UNION returns a distinct
list of rows. Using UNION ALL, returns all rows from both tables. A UNION is useful when
you want to sort results from two separate queries as one combined result. For instance, if you
have two tables, Vendor, and Customer, and you want a combined list of names, you can easily
do so using:
SELECT ‘Vendor’, V.Name
FROM Vendor V
UNION
SELECT ‘Customer’, C.Name
FROM Customer C
ORDER BY Name;
INTERSECT Operator
Use an intersect operator to returns rows that are in common between two tables; it returns
unique rows from both the left and right query. This query is useful when you want to find
results that are in common between two queries. Continuing with Vendors, and Customers,
suppose you want to find vendors that are also customers. You can do so easily using:
SELECT V.Name
FROM Vendor V
INTERSECT
SELECT C.Name
FROM Customer C
ORDER BY Name
EXCEPT Operator
Use the EXCEPT Operator to return only rows found in the left query. It returns unique rows
from the left query that aren’t in the right query’s results. This is similar to MINUS command in
other sql softwares. This query is useful when you’re looking to find rows that are in one set but
not another. For example, to create a list of all vendors that are not customers you could write:
SELECT V.Name
FROM Vendor V
EXCEPT
SELECT C.Name
FROM Customer C
ORDER BY Name
IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.
IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
NULL values
The SQL NULL is the term used to represent a missing value. A NULL value in a table is a
value in a field that appears to be blank.
A field with a NULL value is a field with no value. It is very important to understand that a
NULL value is different than a zero value or a field that contains spaces.
How to Test for NULL Values?
It is not possible to test for NULL values with comparison operators, such as =, <, or <>.
We will have to use the IS NULL and IS NOT NULL operators instead.
IS NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
IS NOT NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
The IS NULL Operator
The IS NULL operator is used to test for empty values (NULL values).
The following SQL lists all customers with a NULL value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;
Always use IS NULL to look for NULL values.
The IS NOT NULL Operator
The IS NOT NULL operator is used to test for non-empty values (NOT NULL values).
The following SQL lists all customers with a value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
INTEGRITY CONSTRAINTS
The Integrity constraints are useful to prevent the invalid data entry into a table. We can add
these constraints to the particular column at the time of creating table also by using ALTER
TABLE command Constraints are mainly three types:
1. Domain constraints
a. NOT NULL constraints
b. CHECK constraints
2. Entity constraints
Unique constraints
3. Referential constraints
a. Primary key constraints
b. Foreign key constrains
DOMAIN CONSTRAINTS
NOT NULL constraints:
This constraint is useful to check the column values for the NULL values. It
displays an error message when we enter no value to a specific column.
CHECK constraints:
This constraint is useful to enter the specified value into a specific column. We can add a
condition along with these constraints. This constraint allows values when the condition is true.
It displays an error message when the condition is false.
ENTITY CONSTRAINTS
UNIQUE constraints:
These constraints are useful to prevent duplicate values in specific columns. It displays an error
message when we enter any one of the previous values in a column.
How to add constraints at the time of creating table:
create table emp1
(ENO number (3) constraints SA Unique,
Ename varchar 2 (20) constraints RA not null,
Esal number (6,2) constraints LA check (esal <= 10000),
deptno number (4));
To see the user constraints list:
select * from user_ constraints;
We can also add constraints
to the exiting table by using ‘ALTER’ table command,
Ex:
Alter table emp 1 add constraints a unique (eno);
Alter table emp 1 modify ename constraints b not null;
Alter table emp 1 add constraints c check (esal <=10000);
we can also drop the constraints from a table by using ‘ALTER’ table command.
EX:
Alter table emp 1 drop constraints c;
Alter table emp 1 disable constraints A;;
The above example disable the constraints A. If you enable after sometime we can use
same command with enable.
Ex:
Alter table Emp 1 enable constraints A;
FOREIGN KEY:
A column included in the definition of referential integrity, which would refer to a referenced
key [ primary key].
Child table:
This table depends up on the value present in the referenced of the parent table.
Parent table:
It determines whether insertion or updating of data can be done in the child table. It would be
preferred by child foreign key.
Example:
Create table emp
(eno number (4),
ename varchar 2 (20),
esal number (10,2),
deptno number (4) constraints f references dept (deptno ));
The referential integrity constraints does not use foreignkey keyword to identify the column that
makeup the foreign key.
create trigger T
before insert on emp
begin
dbms_output.put_line(‘One new row inserted’);
end;
SQL triggers only can provide an extended validation and they cannot replace all the
validations. Some simple validations have to be done in the application layer.