lec 10
lec 10
• SQL became a standard of the American National Standards Institute (ANSI) in 1986,
and of the International Organization for Standardization (ISO) in 1987.
• SQL uses the terms table, row, and column for the formal relational model terms
relation, tuple and attribute, respectively.
1. Data Definition Language(DDL) – Consists of commands which are used to define the
database.
3. Data Control Language(DCL) – Consists of commands which deal with the user
permissions and controls of the database system.
SQL Commands
• These 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 database.
• Column level constraints are applied only to one column whereas, table level
constraints are applied to the entire table.
– NOT NULL Constraint: Ensures that a column cannot have a NULL value.
– UNIQUE Constraint: Ensures that all the values in a column are different.
SQL Constraints
PRIMARY Key: Uniquely identifies each row/record in a database table.
CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy
certain conditions.
INDEX: Used to create and retrieve data from the database very quickly.
The CREATE TABLE Command in SQL
• The CREATE TABLE command is used to specify a new relation by giving it a name
and specifying its attributes and initial constraints.
– Giving a name,
• The key, entity integrity, and referential integrity constraints can be specified
within the CREATE TABLE statement after the attributes are declared, or they can
be added later using the ALTER TABLE command.
• Example:
CREATE TABLE EMPLOYEE
( Fname VARCHAR(15) ,
Lname VARCHAR(15) ,
Ssn CHAR(9) ,
Bdate DATE,
Address VARCHAR(30)
);
Basic data types in SQL
• Numeric Data Type:
– Numeric data types include integer numbers of various sizes and floating-
point (real) numbers of various precision.
• And j, the scale, is the number of digits after the decimal point.
• For fixed length strings, a shorter string is padded with blank characters to the
right.
• Example, if the value ‘Smith’ is for an attribute of type CHAR(10), it is padded with
five blank characters to become ‘Smith’.
• The standard date format for input and output is DD-MON-YY e.g., 01-JAN-17.
• The following statement returns the current date with the standard date format by
using the SYSDATE function:
– This is always implicitly specified for the attributes that are part of the
primary key of each relation.
– But it can be specified for any other attributes whose values are required not
to be NULL.
• Example:
CREATE TABLE EMPLOYEE
( Name Varchar2(20) NOT NULL ,
Dno Number NOT NULL DEFAULT 1,….
);
Constraints in SQL
2. DEFAULT Constraint
• It is also possible to define a default value for an attribute by appending the clause
DEFAULT <value> to an attribute definition.
• The default value is included in any new tuple if an explicit value is not provided for
that attribute.
• If no default clause is specified, the default default value is NULL for attributes that do
not have the NOT NULL constraint.
• Example:
CREATE TABLE EMPLOYEE
(……,
Dno Number NOT NULL DEFAULT 1,
Mgr_ssn CHAR(9) NOT NULL DEFAULT ‘888665555’,……);
Constraints in SQL
3. CHECK Constraint
• CHECK Constraint can restrict attribute or domain values using the CHECK clause
following an attribute or domain definition.
• For example, suppose that department numbers are restricted to integer numbers
between 1 and 20.
……………
Dnumber Number NOT NULL CHECK (Dnumber > 0 AND Dnumber < 21);
Key Constraints
• PRIMARY KEY Constraint
• The PRIMARY KEY clause specifies one or more attributes that make up the
primary key of a relation.
• If a primary key has a single attribute, the clause can follow the attribute directly
or it can be defined at attribute level.
• Example
Create Primary Key - Using ALTER
TABLE statement
• Syntax
• Example:
Drop Primary Key
• Syntax
• Example
Key Constraints
• UNIQUE Constraint
• The UNIQUE clause specifies alternate (secondary) keys, as illustrated in the
DEPARTMENT and PROJECT table declarations.
• Example:
( …….,
Or
( …….,
UNIQUE (Dname),………..);
Key Constraints
• Referential integrity using FOREIGN KEY
• Referential integrity is specified via the FOREIGN KEY clause at table level, as shown
below:
CREATE TABLE EMPLOYEE
(…..,
Ssn CHAR(9) NOT NULL,
Salary NUMBER(10,2),
Super_ssn CHAR(9),
Dno NUMBER NOT NULL,
PRIMARY KEY (Ssn),
FOREIGN KEY (Super_ssn) REFERENCES EMPLOYEE(Ssn),
FOREIGN KEY (Dno) REFERENCES DEPARTMENT(Dnumber) );
Key Constraints
• A referential integrity constraint can be violated when tuples are inserted or
deleted, or when a foreign key or primary key attribute value is modified.
• The default action that SQL takes for an integrity violation is to reject the update
operation that will cause a violation.
• Example:
• The database designer chooses ON DELETE SET NULL and ON UPDATE CASCADE
for the foreign key Super_ssn of EMPLOYEE.
Key Constraints
• What is a foreign key with Cascade DELETE in Oracle?
• A foreign key with cascade delete means that if a record in the parent table is
deleted, then the corresponding records in the child table will automatically be
deleted.
• A foreign key with a cascade/set null can be defined in either a CREATE TABLE
statement or an ALTER TABLE statement.
(…..,
• On the other hand, if the Ssn value for a supervising employee is updated (say, because
it was entered incorrectly), the new value is cascaded to Super_ssn for all employee
tuples referencing the updated employee tuple.
Example1:
CREATE TABLE EMPLOYEE
(...,
Dno INT NOT NULL DEFAULT 1,
PRIMARY KEY (Ssn),
FOREIGN KEY (Super_ssn) REFERENCES EMPLOYEE(Ssn)
ON DELETE SET NULL ON UPDATE CASCADE,
FOREIGN KEY(Dno) REFERENCES DEPARTMENT(Dnumber)
ON DELETE SET DEFAULT ON UPDATE CASCADE);
Specifying Constraints on Tuples
Using CHECK
• In addition to key and referential integrity constraints, which are specified by
special keywords, other table constraints can be specified through additional
CHECK clauses at the end of a CREATE TABLE statement.
• These can be called tuple-based constraints because they apply to each tuple
individually and are checked whenever a tuple is inserted or modified.
• For example, suppose that the DEPARTMENT table had an additional attribute
Dept_create_date, which stores the date when the department was created.
• Then we could add the following CHECK clause at the end of the CREATE TABLE
statement for the DEPARTMENT table to make sure that a manager’s start date is
later than the department creation date.
Syntax 1
•Specify both the column names and the values to be inserted:
• If we are adding values for all the columns of the table, we do not need to
specify the column names in the SQL query.
Syntax 2
• However, make sure the order of the values is in the same order as the columns
in the table.
OR
• Syntax:
• DESCRIBE tablename;
• Oracle also supports the short form DESC of DESCRIBE to get description of table.
• To retrieve details about the structure of relation STUDENT, we can write DESC or
DESCRIBE followed by table name:
• Projection:
• Selection:
– Various criteria can be used to restrict the rows that are retrieved.
• Joining:
– Bring together data that is stored in different tables by specifying the link
between them.
Capabilities of SQL SELECT Statements
Basic SELECT Statement
• A SELECT clause, specifies the columns to be displayed.
• A FROM clause, identifies the table containing the columns that are listed in the
SELECT clause
• Syntax:
Example
... WHERE hire_date = '01-JAN-95'
... WHERE salary >= 6000
... WHERE last_name = 'Smith'
Range Conditions Using the BETWEEN
Operator
• Values that are specified with the BETWEEN operator are inclusive.
Range Conditions Using the BETWEEN
Operator
• SELECT last_name
• FROM employees
• The SELECT statement mentioned above returns the first name from the
EMPLOYEES table for any employee whose first name begins with the letter “S.”
• Note the uppercase “S.” Consequently, names beginning with a lowercase “s”
are not returned.
Combining Wildcard Characters
• FROM employees
• The NULL conditions include the IS NULL condition and the IS NOT NULL condition.
• Therefore, you cannot test with =, because a null cannot be equal or unequal to any
value.
Using the AND Operator
Using the OR Operator
Using the NOT Operator
Using the NOT Operator
• The NOT operator can also be used with other SQL operators, such as BETWEEN,
LIKE, and NULL.
• Null values are displayed last for ascending sequences and first for descending
sequences.
Using the ORDER BY Clause
• Sorting by using the column’s numeric position:
SELECT sysdate
FROM dual;
Arithmetic with Dates
Date-Manipulation Functions
CASE Expression
• CASE expressions allow you to use the IF-THEN-ELSE logic in SQL statements
without having to invoke procedures.
What Are Group Functions?
• Group functions operate on sets of rows to give one result per group.
Types of Group Functions
Group Functions: Syntax
Using the COUNT Function
• COUNT(*) returns the number of rows in a table:
• COUNT(expr) returns the number of rows with non-null values for expr:
• COUNT(DISTINCT expr) returns the number of unique, non-null values that are in
the column identified by expr.
Creating Groups of Data
GROUP BY Clause Syntax
GROUP BY Clause with Order BY
• You can also use the group function in the ORDER BY clause:
FROM employees
GROUP BY department_id
HAVING max(salary)>10000;
Using the HAVING Clause
SELECT job_id, SUM(salary) PAYROLL
FROM employees
GROUP BY job_id
ORDER BY SUM(salary);
Nesting Group Functions
• Group functions can be nested to a depth of two functions.
• The example the average salary for each department_id and then displays the
maximum average salary.
• In all such cases, we need to change or alter the structure of the table by using the
alter statement.
• Example
• Example
• Example
• Example
• Example
• Rename table
• Syntax
• Example
• Syntax
UPDATE table_name
SET column1 = expression1,
column2 = expression2,
...
column_n = expression_n
WHERE conditions;
• Example:
WHERE supplier_id = 2;
UPDATE Command
• Update multiple columns
• Example
UPDATE suppliers
WHERE supplier_id = 1;
DELETE Command
• In Oracle, DELETE statement is used to remove or delete a single record or
multiple records from a table.
• Syntax
DELETE FROM table_name WHERE conditions;
• Examples:
• We can use the “ROLLBACK” command to restore the tuple because it does not
auto-commit.
DROP Command
• It is a Data Definition Language Command (DDL).
• With the help of the “DROP” command we can drop (delete) the whole structure
in one go i.e. it removes the named elements of the schema.
• SYNTAX –
• We can’t restore the table by using the “ROLLBACK” command because it auto
commits.
TRUNCATE
• It is also a Data Definition Language Command (DDL).
• With the help of the “TRUNCATE” command, we can’t delete the single row as
here WHERE clause is not used.
• By using this command the existence of all the rows of the table is lost.
• It is comparatively faster than the delete command as it deletes all the rows fastly.
• SYNTAX
• Note – Here we can’t restore the tuples of the table by using the “ROLLBACK”
command.
JOIN Operation in SQL
1. CROSS JOIN
2. EQUI JOIN
3. OUTER JOIN
4. SELF JOIN
CROSS JOIN
EMPNAME DEPTNO DEPTNO DEPTNAME
king 10 10 accounting
Example:
blake NULL 10 accounting
SELECT * clark 10 10 accounting
martin 20 10 accounting
FROM employee e, department d
turner 10 10 accounting
jones NULL 10 accounting
Employee
king 10 30 sales
EMPNAME DEPTNO
king 10 blake NULL 30 sales
blake NULL clark 10 30 sales
clark 10 martin 20 30 sales
martin 20
turner 10 30 sales
turner 10
jones NULL jones NULL 30 sales
X king 10 20 operations
blake NULL 20 operations
Department
clark 10 20 operations
DEPTNO DEPTNAME
martin 20 20 operations
10 accounting
turner 10 20 operations
30 sales
jones NULL 20 operations
20 operations
EQUIJOIN/INNER JOIN
• Inner Join is the simplest and most common type of join.
• It returns all rows from multiple tables where the join condition is met.
• Syntax
SELECT columns
FROM table1 t1
INNER JOIN table2 t2
ON t1.column = t2.column;
OR
SELECT columns
FROM table1 t1 , table2 t2
WHERE t1.column = t2.column;
EQUIJOIN/INNER JOIN
EMPNAME DEPTNO
king 10
blake NULL
clark 10 EMPNAME DEPTNO DEPTNAME
martin 20
king 10 accounting
turner 10
jones NULL clark 10 accounting
martin 20 operations
OR
• Syntax
SELECT columns
FROM table t1
INNER JOIN table t2
ON t1.column = t2.column;
OR
SELECT columns
FROM table t1 , table t2
WHERE t1.column = t2.column;
Example: SELF JOIN
• Consider the Employee schema:
• Each employee in the table has a manager ID associated with it.
• We use SELF JOIN for referencing the same table twice in a same query by using
table alias.
• The Join Condition matches the employees with their managers using the
manager_id and employee_id columns.
SELECT columns
FROM table1 t1
LEFT JOIN table2 t2
ON t1.column = t2.column;
OR
SELECT columns
FROM table1 t1 , table2 t2
WHERE t1.column = t2.column(+);
Left Outer Join
EMPNAME DEPTNO
king 10 EMPNAME DEPTNO DEPTNO DEPTNAME
blake NULL
turner 10 10 accounting
clark 10
martin 20 clark 10 10 accounting
turner 10
king 10 10 accounting
jones NULL
martin 20 20 operations
DEPTNO DEPTNAME
jones NULL NULL NULL
10 accounting
30 sales blake NULL NULL NULL
20 operations
SELECT columns
FROM table1 t1
RIGHT JOIN table2 t2
ON t1.column = t2.column;
OR
SELECT columns
FROM table1 t1 , table2 t2
WHERE t1.column(+) = t2.column;
Right Outer Join
EMPNAME DEPTNO
king 10
blake NULL EMPNAME DEPTNO DEPTNO DEPTNAME
clark 10
king 10 10 accounting
martin 20
turner 10 clark 10 10 accounting
jones NULL martin 20 20 operations
SELECT * SELECT *
FROM employee e OR FROM employee e, department d
RIGHT JOIN department d WHERE e.deptno(+) = d.deptno
ON e.deptno=d.deptno
FULL Outer Join
• The Full Outer Join returns all rows from the left hand table and right hand table.
It places NULL where the join condition is not met.
• Syntax:
SELECT columns
FROM table1 t1
FULL JOIN table2 t2
ON t1.column = t2.column;
FULL Outer Join
EMPNAME DEPTNO
EMPNAME DEPTNO DEPTNO DEPTNAME
king 10
blake NULL turner 10 10 accounting
clark 10 clark 10 10 accounting
martin 20
king 10 10 accounting
turner 10
martin 20 20 operations
jones NULL
jones NULL NULL NULL
DEPTNO DEPTNAME blake NULL NULL NULL
10 accounting
NULL NULL 30 sales
30 sales
20 operations
SELECT *
FROM employee e
FULL JOIN department d
ON e.deptno=d.deptno
Introduction to the Oracle View
• A view is a “virtual” table whose data is the result of a stored query, which is
derived each time when we query against the view.
• Every view has columns with data types so we can execute a query against views or
manage their contents (with some restrictions) using the INSERT, UPDATE, DELETE,
statements.
• It’s a virtual table that can be based on one or more base tables or views.
• When we use view in our query, the sub-query gets executed and view data is
fetched dynamically.
– Complex View – Based on one or more base tables and a sub-query that might
contain a join condition or aggregate function
When to use the Oracle view
• We can use views in many cases for different purposes.
– First, we build a complex query, test it carefully, and encapsulate the query in
a view.
– Then, we can access the data of the underlying tables through the view
instead of rewriting the whole query again and again.
View: Simplifying data retrieval
• The following query returns sales amount by the customer by year:
• Typing it over and over again is time-consuming and potentially cause a mistake.
• Whenever the structures of the base tables change, we just need to update the
view.
• The interface between the database and the external applications remains intact.
• The beauty is that we don’t have to change a single line of code to keep the
external applications up and running.
• For example, some reporting systems may need only customer sales data for
composing strategic reports.
• Hence, you can give the application owners the customer_sales view.
Implementing data security
• Views allow us to implement an additional security layer.
• They help us hide certain columns and rows from the underlying tables and expose
only needed data to the appropriate users.
• Oracle provide us the with GRANT and REVOKE commands on views so that we
can specify which actions a user can perform against the view.
• Note that in this case, we don’t grant any privileges on the underlying tables
because we may not want the user to bypass the views and access the base tables
directly.
Oracle CREATE VIEW
• To create a new view in a database, you use the following Oracle CREATE VIEW
statement:
• SYNTAX CREATE [OR REPLACE] VIEW view_name
[(column_aliases)] AS defining-query
[WITH READ ONLY]
[WITH CHECK OPTION]
• The OR REPLACE option replaces the definition of existing view.
• It is handy if we have granted various privileges on the view.
• Because when we use the DROP VIEW and CREATE VIEW to change the view’s
definition, Oracle removes the view privileges, which may not be what we want.
• To avoid this, you can use the CREATE OR REPLACE clause that preserves the view
privileges.
Example: Oracle CREATE VIEW
• The following statement creates a view named employee_yos based on the
employees table.
• The view shows the employee id, name and years of service:
FROM employees;
Example: Oracle CREATE VIEW
• If you don’t want to use column aliases in the query, you must define them in the
CREATE VIEW clause:
FROM employees;
Example: Oracle CREATE VIEW
• The following query returns employees whose years of service are 15:
• A view is updatable if the statement against the view can be translated into the
corresponding statement against the underlying table.
• In database diagram, a car belongs to one brand while a brand has one or many
cars. The relationship between brand and car is a one-to-many.
Oracle Updatable View
• The following statement creates a new view named cars_master:
• It’s possible to delete a row from the cars table via the cars_master view, for
example:
WHERE car_id = 1;
• And you can update any column values exposed to the cars_master view:
WHERE car_id = 2;
Oracle Updatable View
• We cannot update a view if it contains any of the following:
– GROUP BY clause
– DISTINCT clause
– HAVING
– Subquery in SELECT
– Certain Joins