Unit 3 DBMS
Unit 3 DBMS
A table is database object that holds user data. The simplest analogy is to think of a table as
a spread sheet. The cells of the spread sheet equate to the columns of a table having a
specific data type associated with them. If the spread sheet cell has a number data type
associated with it, then storing letters (i.e characters) in the same cell is not allowed. The
same logic is applied to a table’s column of the table will have specific data type bound to it.
Oracle ensures that only data, which is identical to the data type or column, will be stored
within the column.
The CREATE TABLE statement is used to create a new table in a database. For
creating table we have to define the structure of table by adding name to
columns, providing data type and size of data to be stored in columns. Each
column definition is a single clause in the create table syntax. Each table
column is separated from the other by a comma.
Syntax:
Example:
Syntax:
1. Specify both the column names and the values to be inserted to insert
data into specified columns. :
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
2. 2. If you are adding values for all the columns of the table, you do not
need to specify the column names in the SQL query. However, make
sure the order of the values is in the same order as the columns in the
table because table columns and value have one to one relation.
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
Example:
Syntax:
Here, column1, column2, ... are the field names of the table you want to
select data from.
All rows and all columns
If you want to select all the fields available in the table, use the following
syntax:
The WHERE clause is used with SELECT statement to return only those rows from the
table, which satisfy the specified condition in the query.
In SQL, the WHERE clause is not only used with SELECT, but it is also used with other SQL
statements such as UPDATE, ALTER, and DELETE statements.
Syntax:
SELECT * FROM Name_of_Table WHERE [condition];
Example:
SELECT * FROM Student WHERE id=101;
Syntax:
SELECT * FROM table_name ORDER BY column_name ASC|DESC
ASC: to sort the data in ascending order.
DESC: to sort the data in descending order.
Example:
SELECT * FROM Student ORDER BY ROLL_NO DESC;
The new table gets the same column definitions. All columns or specific
columns can be selected.
If you create a new table using an existing table, the new table will be filled
with the existing values from the old table.
Syntax:
Example:
To create a target table without the records from the source table, the select statement must
have a WHERE clause. The WHERE clause must specify a condition that cannot be
satisfied.
Syntax
The INSERT INTO SELECT statement copies data from one table and inserts it
into another table.
The INSERT INTO SELECT statement requires that the data types in source
and target tables match.
Syntax:
Example:
SYNTAX :
ALTER TABLE table_name ADD (column_name datatype(size));
Example –
ALTER TABLE Student ADD (marks_obtained Number (3));
Alter table - drop column(To delete a column)
Syntax: ALTER TABLE table_name DROP COLUMN column_name;
Example: ALTER TABLE Customers DROP COLUMN Email;
To change the data type of a column in a table, use the following syntax:
DESCRIBE table_name;
Constraints are used to limit the type of data that can go into a table. This
ensures the accuracy and reliability of the data in the table. If there is any
violation between the constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply
to a column, and table level constraints apply to the whole table.
2.1 Types of Data Constraints
There are two types, one is I/O constraints. It determines the speed at which
data can be inserted or extracted from a table. The other type of constraints
is called a business rule constraints.
SQL FOREIGN KEY constraint is used to link two tables together and it
is also termed as a referencing key.
SQL FOREIGN KEY constraint is a field or collections of fields in one
table that refers to the PRIMARY KEY constraint in another table.
The table that contains PRIMARY KEY is termed as Master table or
referenced table, and a table containing the FOREIGN KEY is termed as
the Detail table.
FOREIGN KEY constraint prevents invalid data being inserted into
the FOREIGN KEY column because it has to be one of the values
contained in the table it points to.
In all databases whenever we are creating constraints database servers internally automatically
creates unique identification number, for identifying constraint uniquely.
Oracle also generates an unique identification number in the format of SYS_Cn for identifying
constraint uniquely. This is called predefined constraint name.
In place of this we can also create our own name by using constraint key word.This is called user
defined constraint name.
A unique key is a set of one or more than one fields/columns of a table that
uniquely identify a record in a database table.
You can say that it is little like primary key but it can accept only one null
value and it cannot have duplicate values.
The unique key and primary key both provide a guarantee for uniqueness for
a column or a set of columns.
There is an automatically defined unique key constraint within a primary key
constraint.
Unique key cannot be LONG or LONG RAW data type
Unique key can combine upto 16 columns in a composite unique key
Unique key at column level
Example:
CREATE TABLE students
(
S_Id int UNIQUE,
LastName varchar (255) ,
FirstName varchar (255),
City varchar (255)
)
Example:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
UNIQUE (ID)
);
If data constraints are defined as an attribute of a column definition when creating or altering a table
structure, they are column level constraints.
Table level constraints
If data constraints are defined after defining all the tables column attributes when creating or
altering a table structure, it is a table level constraints
NULL Value concept
The first statement inserts a record with a supplier_name that is null, while the second
statement inserts a record with an empty string as a supplier_name.
Now, let's retrieve all rows with a supplier_name that is an empty string value as follows:
When you run this statement, you'd expect to retrieve the row that you inserted above. But
instead, this statement will not retrieve any records at all.
Now, try retrieving all records where the supplier_name contains a null value:
When you run this statement, you will retrieve both rows. This is because Oracle has now
changed its rules so that empty strings behave as null values.
With respect to using null values in SQL statements in Oracle, it is also important to note that
the null value is unique in that you can not use the usual operands (=, <, >, etc) on a null
value. Instead, you must use the IS NULL and IS NOT NULL conditions.
By default, a column can hold NULL values. The NOT NULL constraint enforces a
column to NOT accept NULL values. This enforces a field to always contain a
value, which means that you cannot insert a new record, or update a record
without adding a value to this field.
The following SQL ensures that the "ID", "LastName", and "FirstName"
columns will NOT accept NULL values when the "Persons" table is created:
Example
The CHECK constraint is used to limit the value range that can be placed in a
column.
If you define a CHECK constraint on a column it will allow only certain values
for this column.
If you define a CHECK constraint on a table it can limit the values in certain
columns based on values in other columns in the row.
Syntax:
CREATE TABLE TableName(ColumnName1 Datatype(size), ColumnName2 Datatype(size
), ColumnName3 Datatype(size) Constraint ConstraintName CHECK(ColumnName CON
DITION Value),…, ColumnNameN Datatype(size));
Example :
The following SQL creates a CHECK constraint on the "Age" column when the
"Persons" table is created. The CHECK constraint ensures that the age of a
person must be 18, or older:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);
Here gender column accepts only ‘male’ and ‘female’ input. If you tries to enter other than these
The default value will be added to all new records, if no other value is
specified.
The following SQL sets a DEFAULT value for the "India" column when the
"Persons" table is created:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'India'
);
Arithmetic Operators
In Structured Query Language, the arithmetic operators are used to perform mathematical
operations on the numerical values stored in the database tables.
We can use these operators with the SELECT statement in SQL. We can also use the
WHERE clause in the SELECT statement for performing operations on particular rows.
These types of operators are used between two numerical operands for performing
addition, subtraction, multiplication, and division operations.
The arithmetic operators in SQL are categorized into the following five types:
Syntax:
SELECT <Expression>[arithmetic operator]<expression>...
FROM [table_name]
WHERE [expression];
Output:
Example:
SELECT Emp_Salary - Emp_Panelty AS Emp_Total_Salary FROM Employee;
If you want to multiply the values of two numerical columns, then you have to specify
both columns as the first and second operand. You can also multiply the integer
value with the values of an integer column.
The SQL AND operator is used with the where clause in the SQL Query. AND
operator in SQL returns only those records which satisfy both the conditions in the
SQL query.
Example: Write a query to retrieve only those records of employees from the
employees table where the designation is 'Project Manager' and the City to which the
employee belongs to is Mumbai.
Query: SELECT * FROM employees WHERE City = "Mumbai" AND Designation = "P
roject Manager";
2. SQL OR Operator
The SQL OR operator is used with the where clause in an SQL Query. AND operator
in SQL returns only those records that satisfy any of the conditions in the SQL query.
Example:
Write a query to retrieve only those records of employees from the employees table
where the employee's designation is 'System Engineer' or the city to which the
employee belongs is Mumbai.
NOT operator in SQL shows those records from the table where the criteria is not
met. NOT operator is used with where clause in a SELECT query.
Let's understand the below example, which explains how to execute NOT operator in
SQL query.
Example:
Write a query to retrieve only those records of employees from the employees table
where the employee's designation is not Project Manager.
Range searching
This operator displays the records which fall between the given ranges in the SQL
query. The results of the BETWEEN operator include begin and end values of the
given range.
Example:
Write a query to retrieve only those records of an employee from the employees
table where employee salary lies between 50000 to 90000.
Query: SELECT * FROM employees WHERE Salary BETWEEN 50000 AND 90000;
Pattern matching
LIKE Operator in SQL displays only those data from the table which matches the
pattern specified in the query. Percentage (%) and underscore (_) are the two
wildcard operators used with LIKE Operator to perform pattern matching tasks.
Let's understand the below example, which explains how to execute the LIKE
operator in an SQL query.
Example: Write a query to retrieve only those records of employees from the
employees table whose name starts with the letter S.
When we want to check for one or more than one value in a single SQL query, we
use IN operator with the WHERE clause in a SELECT query.
Let's understand the below example, which explains how to execute IN operator in an
SQL query.
Example:
Write a query to retrieve only those records of employees from the employees table
where the city to which the employee belongs to is either Mumbai, Bangalore, or
Pune.
Query:
Oracle DUAL table which is a special table used for evaluating expressions or calling
functions.
In Oracle, the SELECT statement must have a table name in FROM clause. Otherwise
the SELECT fails.
When an arithmetic exercise is to be performed such as 2*2 or 4/2 and so on, there is
no table being referenced, only numeric literals are being used.
To facilitate such calculation via a SELECT , Oracle provides a dummy table called
DUAL.
DUMMY VARCHAR2(1)
Content of DUAL
OUTPUT
2*2
----------
4
Example:
SYSDATE
22-NOV-22
Oracle Functions:
Aggregate function
AVG function
The AVG function is used to calculate the average value of the numeric type. AVG
function returns the average of all non-Null values.
Syntax
Example:
MIN Function
MIN function is used to find the minimum value of a certain column. This function
determines the smallest value of all selected values of a column.
Syntax
Example:
MAX Function
MAX function is used to find the maximum value of a certain column. This function
determines the largest value of all selected values of a column.
Example:
COUNT FUNCTION
o COUNT function is used to Count the number of rows in a database table. It can work
on both numeric and non-numeric data types.
o COUNT function uses the COUNT(*) that returns the count of all the rows in a
specified table. COUNT(*) considers duplicate and Null.
Syntax: COUNT(*)
or
COUNT( [ALL|DISTINCT] expression )
Example:
SUM Function
Sum function is used to calculate the sum of all selected columns. It works on
numeric fields only.
Syntax
SUM()
or
SUM( [ALL|DISTINCT] expression )
Example: SUM()
The SQL GROUP BY clause can be used in a SELECT statement to collect data
across multiple records and group the results by one or more columns.
Syntax
The syntax for the GROUP BY clause in SQL is:
There will be 2 records selected. These are the results that you should see:
dept_id total_salaries
500 119500
501 113000
In this example, we've used the SUM function to add up all of the salaries for
each dept_id and we've aliased the results of the SUM function as total_salaries.
Because the dept_id is not encapsulated in the SUM function, it must be listed in the
GROUP BY clause.
SQL: HAVING Clause
The SQL HAVING clause is used in combination with the GROUP BY clause to
restrict the groups of returned rows to only those whose the condition is TRUE.
Syntax
The syntax for the HAVING clause in SQL is:
SUBQUERIES
A subquery is a form of an SQL statement that appears inside another SQL statement. It also
termed as nested query. The statement containing a subquery is called a parent statement. The
parent statement uses the rows(i.e the result set) returned by subquery.
SQL: JOINS
SQL JOINS are used to retrieve data from multiple tables. A SQL JOIN is performed
whenever two or more tables are listed in a SQL statement.
There are 4 different types of SQL joins:
Syntax
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
Visual Illustration
In this visual diagram, the SQL INNER JOIN returns the shaded area:
The SQL INNER JOIN would return the records where table1 and table2 intersect.
Example
1 7000 2016/04/18
2 5000 2016/04/18
order_id customer_id order_date
3 8000 2016/04/19
4 4000 2016/04/20
5 NULL 2016/05/01
There will be 4 records selected. These are the results that you should see:
4000 4 2016/04/20
5000 2 2016/04/18
7000 1 2016/04/18
8000 3 2016/04/19
This example would return all rows from the customers and orders tables
where there is a matching customer_id value in both
the customers and orders tables.
The rows where customer_id is equal to 6000 and 9000 in
the customers table would be omitted, since they do not exist in both tables.
The row where the order_id is 5 from the orders table would be omitted, since
the customer_id of NULL does not exist in the customers table.
Old Syntax
As a final note, it is worth mentioning that the INNER JOIN example above could
be rewritten using the older implicit syntax as follows (but we still recommend
using the INNER JOIN keyword syntax):
Outer joins
SQL LEFT OUTER JOIN
Another type of join is called a LEFT OUTER JOIN. This type of join returns all rows
from the LEFT-hand table specified in the ON condition and only those rows from
the other table where the joined fields are equal (join condition is met).
Syntax
SELECT columns
FROM table1
LEFT [OUTER] JOIN table2
ON table1.column = table2.column;
In some databases, the OUTER keyword is omitted and written simply as LEFT
JOIN.
Visual Illustration
In this visual diagram, the SQL LEFT OUTER JOIN returns the shaded area:
The SQL LEFT OUTER JOIN would return the all records from table1 and only those
records from table2 that intersect with table1.
Example
Now let's look at an example that shows how to use the LEFT OUTER JOIN in a
SELECT statement.
Using the same customers table as the previous example:
1 7000 2016/04/18
2 5000 2016/04/18
order_id customer_id order_date
3 8000 2016/04/19
4 4000 2016/04/20
5 NULL 2016/05/01
There will be 6 records selected. These are the results that you should see:
4000 4 2016/04/20
5000 2 2016/04/18
7000 1 2016/04/18
8000 3 2016/04/19
This LEFT OUTER JOIN example would return all rows from the customers table
and only those rows from the orders table where the joined fields are equal.
If a customer_id value in the customers table does not exist in the orders table, all
fields in the orders table will display as NULL in the result set. As you can see, the
rows where customer_id is 6000 and 9000 would be included with a LEFT OUTER
JOIN but the order_id and order_date fields display NULL.
Syntax
SELECT columns
FROM table1
RIGHT [OUTER] JOIN table2
ON table1.column = table2.column;
In some databases, the OUTER keyword is omitted and written simply as RIGHT
JOIN.
Visual Illustration
In this visual diagram, the SQL RIGHT OUTER JOIN returns the shaded area:
The SQL RIGHT OUTER JOIN would return the all records from table2 and only
those records from table1 that intersect with table2.
Example
Now let's look at an example that shows how to use the RIGHT OUTER JOIN in a
SELECT statement.
Using the same customers table as the previous example:
customer_id last_name first_name favorite_website
1 7000 2016/04/18
2 5000 2016/04/18
3 8000 2016/04/19
4 4000 2016/04/20
5 NULL 2016/05/01
There will be 5 records selected. These are the results that you should see:
customer_id order_id order_date
NULL 5 2016/05/01
4000 4 2016/04/20
5000 2 2016/04/18
7000 1 2016/04/18
8000 3 2016/04/19
This RIGHT OUTER JOIN example would return all rows from the orders table and
only those rows from the customers table where the joined fields are equal.
If a customer_id value in the orders table does not exist in the customers table, all
fields in the customers table will display as NULL in the result set. As you can see,
the row where order_id is 5 would be included with a RIGHT OUTER JOIN but
the customer_id field displays NULL.
Syntax
SELECT columns
FROM table1
FULL [OUTER] JOIN table2
ON table1.column = table2.column;
In some databases, the OUTER keyword is omitted and written simply as FULL
JOIN.
Visual Illustration
In this visual diagram, the SQL FULL OUTER JOIN returns the shaded area:
The SQL FULL OUTER JOIN would return the all records from
both table1 and table2.
Example
Let's look at an example that shows how to use the FULL OUTER JOIN in a
SELECT statement.
Using the same customers table as the previous example:
1 7000 2016/04/18
2 5000 2016/04/18
3 8000 2016/04/19
order_id customer_id order_date
4 4000 2016/04/20
5 NULL 2016/05/01
There will be 7 records selected. These are the results that you should see:
NULL 5 2016/05/01
4000 4 2016/04/20
5000 2 2016/04/18
7000 1 2016/04/18
8000 3 2016/04/19
This FULL OUTER JOIN example would return all rows from the orders table
and all rows from the customers table. Whenever the joined condition is not
met, a NULL value would be extended to those fields in the result set. This
means that if a customer_id value in the customers table does not exist in
the orders table, all fields in the orders table will display as NULL in the result
set. Also, if a customer_id value in the orders table does not exist in
the customers table, all fields in the customers table will display as NULL in
the result set.
As you can see, the rows where the customer_id is 6000 and 9000 would be
included but the order_id and order_date fields for those records contains a
NULL value. The row where the order_id is 5 would be also included but
the customer_id field for that record has a NULL value.
The SQL CROSS JOIN produces a result set which is the number of rows in
the first table multiplied by the number of rows in the second table if no
WHERE clause is used along with CROSS JOIN.This kind of result is called
as Cartesian Product.
Syntax:
SELECT *
FROM table1
CROSS JOIN table2;
Example
SELECT foods.item_name,foods.item_unit,
company.company_name,company.company_city
FROM foods CROSS JOIN company;
The SQL UNION clause/operator is used to combine the results of two or more
SELECT statements without returning any duplicate rows.
To use this UNION clause, each SELECT statement must have
Syntax
The basic syntax of a UNION clause is as follows −
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
UNION
Output:
INTERSECT Clause
The SQL INTERSECT clause/operator is used to combine two SELECT statements, but
returns rows only from the first SELECT statement that are identical to a row in the second
SELECT statement. This means INTERSECT returns only common rows returned by the two
SELECT statements.
syntax
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
INTERSECT
Example: select subject from master intersect select subject from detail;
MINUS Clause
The SQL MINUS operator is used to return all rows in the first SELECT statement
that are not returned by the second SELECT statement. Each SELECT statement
will define a dataset. The MINUS operator will retrieve all records from the first
dataset and then remove from the results all records from the second dataset.
Minus Query
Syntax:
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
MINUS
Example: