Documente Academic
Documente Profesional
Documente Cultură
A primary key is a column which uniquely identifies the records in a table. In a broad sense, a primary key is the
mixture of a unique key and an index: A column with a primary key is indexed to deliver a faster query, and doesn't allow
duplicate values to ensure specific data.
A foreign key is a column (the child column) in a table which has a corresponding relationship and a dependency
on another column (the parent column) that is usually in a different table. Parent columns can have multiple child columns,
but a child column can only have one parent column.
Primary key does't allow null value while foreign key allow null value
Foreign Key
1. A foreign key can refer
to its own relation.
2. One or more Foreign
key can be treated in Parent table.
3. Foreign key constraints
can be defined at the column or
table constraint level.
Primary Key
1. The Primary key clause speci-files one or more attributes that make up
primary key of a relation.
2. One Primary key can be
treated for each table.
3. Primary key constraint is a
column or set of columns that uniquely
identifies each row in a table.
table can access the information in the first table by including a column to hold just the primary key value as a foreign key.
When pulling information processes can take information from an orders table and use the foreign key on the order to
reference all of the information for the customer that foreign key relates.
Primary Key: A column in a table whose values uniquely identify the rows in the table. A primary key value cannot be
NULL.
Unique Key: Unique Keys are used to uniquely identify each row in an Oracle table. There can be one and only one row
for each unique key value.
Surrogate Key: A system generated key with no business value. Usually implemented with database generated sequences.
The Difference Between UNION and UNION ALL
UNION performs a DISTINCT on the result set, eliminating any duplicate rows.
UNION ALL does not remove duplicates, and is therefore faster than UNION.
The basic difference between UNION and UNION ALL is union operation eliminates the duplicated rows from the result
set but union all returns all rows after joining.
union is used to select distinct values from two tables where as union all is used to select all values including duplicates
from the tables
UNION
The UNION command is used to select related information from two tables, much like the JOIN command. However,
when using the UNION command all selected columns need to be of the same data type. With UNION, only distinct
values are selected.
UNION ALL
The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values.
The difference between Union and Union all is that Union all will not eliminate duplicate rows, instead it just pulls all rows
from all tables fitting your query specifics and combines them into a table.
A UNION statement effectively does a SELECT DISTINCT on the results set. If you know that all the records returned
are unique from your union, use UNION ALL instead, it gives faster results.
Example :Table X contain values(a,b,c) and Table Y contain values(c,d,e)
In Case Of Union we will get Result-a,b,c,d,e
and other hand (Union All ) we will get-a,b,c,c,d,e.
Note: The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL.
SQL UNION ALL Syntax
SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2
PS: The column names in the result-set of a UNION are always equal to the column names in the first SELECT statement
in the UNION.
SQL UNION Example
Look at the following tables:
"Employees_Norway":
E_ID
01
02
03
04
E_Name
Hansen, Ola
Svendson, Tove
Svendson, Stephen
Pettersen, Kari
"Employees_USA":
E_ID
01
02
03
04
E_Name
Turner, Sally
Kent, Clark
Svendson, Stephen
Scott, Stephen
Now we want to list all the different employees in Norway and USA.
We use the following SELECT statement:
SELECT E_Name FROM Employees_Norway
UNION
SELECT E_Name FROM Employees_USA
The result-set will look like this:
E_Name
Hansen, Ola
Svendson, Tove
Svendson, Stephen
Pettersen, Kari
Turner, Sally
Kent, Clark
Scott, Stephen
Note: This command cannot be used to list all employees in Norway and USA. In the example above we have two
employees with equal names, and only one of them will be listed. The UNION command selects only distinct values.
o
o
o
o
o
o
DML
Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples:
o SELECT - retrieve data from the a database
o INSERT - insert data into a table
o UPDATE - updates existing data within a table
o DELETE - deletes all records from a table, the space for the records remain
o MERGE - UPSERT operation (insert or update)
o CALL - call a PL/SQL or Java subprogram
o EXPLAIN PLAN - explain access path to data
o LOCK TABLE - control concurrency
DCL
Data Control Language (DCL) statements. Some examples:
o GRANT - gives user's access privileges to database
o REVOKE - withdraw access privileges given with the GRANT command
TCL
Transaction Control (TCL) statements are used to manage the changes made by DML statements. It allows statements to
be grouped together into logical transactions.
o COMMIT - save work done
o SAVEPOINT - identify a point in a transaction to which you can later roll back
o ROLLBACK - restore database to original since the last COMMIT
o SET TRANSACTION - Change transaction options like isolation level and what rollback segment to use
DDL COMMANDS:
CREATE,ALTER,DROP AND TRUNCATE ARE CALLED DDL COMMANDS. They are called Data Definition since
they are used for defining the data. That is the structure of the data is known through these DDL commands.
DML COMMANDS:
DML commands are used for data manipulation. Some of the DML commands
insert,select,update,delete etc. Even though select is not exactly a DML language command oracle still recommends you to
consider SELECT as an DML command.
TCL:
For revoking the transactions and to make the data commit to the database we use TCL. Some of the TCL commands are:
1. ROLLBACK
2. COMMIT
ROLLBACK is used for revoking the transactions until last commit.
COMMIT is used for commiting the transactions to the database.
Once we commit we cannot rollback. Once we rollback we cannot commit.
Commit and Rollback are generally used to commit or revoke the transactions that are with regard to DML commands.
DCL:
Data Control Language is used for the control of data. That is a user can access any data based on the priveleges given to
him. This is done through DATA CONTROL LANGUAGE. Some of the DCL Commands are:
1. GRANT
2. REVOKE
TRUNCATE
DROP
Command Type
DML
DDL
DDL
Yes
No
No
Selective deletion
possible?
Triggers fired?
No triggers fired
No triggers fired
Purpose
Commit required?
Undo possible?
Exception: Truncate is
possible if the FK is selfreferential.
Efficiency
Privileges required to
issue the command
TRUNCATE is most
efficient for deleting all
rows, even more than
dropping and recreating
the table using DROP
DELETE privilege.
DELETE privilege on a
specific table can be
granted to another user or
role.
TRUNCATE privilege on a
specific table cannot be
granted to another user or
role.
Yes
Yes
The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If
no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to
COMMIT or ROLLBACK the transaction to make the change permanent or to undo it.
TRUNCATE removes all rows from a table. The operation cannot be rolled back. As such, TRUCATE is faster and doesn't
use as much undo space as a DELETE.
The DROP command removes a table from the database. All the tables' rows,
indexes and privileges will also be removed. The operation cannot be rolled back.
DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command. Therefore DELETE operations can
be rolled back (undone), while DROP and TRUNCATE operations cannot be rolled back.
The delete statement will result in the table spaces or memories would remain as the current size and table structure remain
in the database. Delete is not effective when you use it to remove all data from a table because it takes up storeage spaces
due to unclear memories. The truncate statement will result in clearing table spaces or memories and the table structure
remain in the database. Therefore it free table storage spaces and only use it when you need to remove all data from a table.
The drop statement will result in completely removing the table from the database. Note: Statements above are made with
the assumption that a commit is has been executed. Once a commit statement is executed (commit is final). Therefore
rollback a transaction will not work if commit statement is executed.
DELETE
The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If
no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT
or ROLLBACK the transaction to make the change permanent or to undo it. Note that this operation will cause all
DELETE triggers on the table to fire.
SQL> SELECT COUNT(*) FROM emp;
COUNT(*)
---------14
SQL> DELETE FROM emp WHERE job = 'CLERK';
4 rows deleted.
SQL> COMMIT;
Commit complete.
SQL> SELECT COUNT(*) FROM emp;
COUNT(*)
---------10
TRUNCATE
TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such,
TRUCATE is faster and doesn't use as much undo space as a DELETE.
SQL> TRUNCATE TABLE emp;
Table truncated.
SQL> SELECT COUNT(*) FROM emp;
COUNT(*)
---------0
DROP
The DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed.
No DML triggers will be fired. The operation cannot be rolled back.
SQL> DROP TABLE emp;
Table dropped.
SQL> SELECT * FROM emp;
SELECT * FROM emp
*
ERROR at line 1:
ORA-00942: table or view does not exist
DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command. Therefore DELETE operations can
be rolled back (undone), while DROP and TRUNCATE operations cannot be rolled back.
DELETE
Delete is the command that only remove the data from the table. It is DML statement. Deleted data can be rollback. By
using this we can delete whole data from the table(if use without where clause).If ew want to remove only selected data
then we should specify condition in the where clause
SQL>delete from employee;(this command will remove all the data from table)
SQL>delete from employee where employee_name='JOHN';(This command will remove only that row from employee
table where employee_name is JOHN');
DROP:
Drop command remove the table from data dictionary. This is the DDL statement. We can not recover the table before
Oracle 10g. But Oracle 10g provide the command to recover it by using the command (FLASHBACK)
TRUNCATE:
This is the DML command. This command delete the data from table. But there is one difference from ordinary delete
command. Truncate command drop the storage held by this table. Drop storage can be use by this table again or some other
table. This is the faster command because it directly drop the storage
NOTE:The WHERE clause in the sql delete command is optional and it identifies the rows in the column that gets
deleted. If you do not include the WHERE clause all the rows in the table is deleted, so be careful while writing a
DELETE query without WHERE clause.
For Example: To delete an employee with id 100 from the employee table, the sql delete query would be like,
DELETE FROM employee WHERE id = 100;
To delete all the rows from the employee table, the query would be like,
DELETE FROM employee;
SQL TRUNCATE Statement
The SQL TRUNCATE command is used to delete all the rows from the table and free the space containing the table.
Syntax to TRUNCATE a table:
TRUNCATE TABLE table_name;
For Example: To delete all the rows from employee table, the query would be like,
TRUNCATE TABLE employee;
Difference between DELETE and TRUNCATE Statements:
DELETE Statement: This command deletes only the rows from the table based on the condition given in the where clause
or deletes all the rows from the table if no condition is specified. But it does not free the space containing the table.
TRUNCATE statement: This command is used to delete all the rows from the table and free the space containing the
table.
An inner join of A and B gives the result of A intersect B, i.e. the inner part of a venn diagram intersection.
An outer join of A and B gives the results of A union B, i.e. the outer parts of a venn diagram union.
Examples
Suppose you have two Tables, with a single column each, and data as follows:
A
1
2
3
4
B
3
4
5
6
Note that (1,2) are unique to A, (3,4) are common, and (5,6) are unique to B.
inner join
An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in
common.
select * from a INNER JOIN b on a.a = b.b;
select a.*,b.* from a,b where a.a = b.b;
a|b
--+-3|3
4|4
left outer join
A left outer join will give all rows in A, plus any common rows in B.
select * from a LEFT OUTER JOIN b on a.a = b.b;
select a.*,b.* from a,b where a.a = b.b(+);
a| b
--+----1 | null
2 | null
3|
4|
3
4
Joins
A join is a query that combines rows from two or more tables, views, or materialized views. Oracle Database performs a
join whenever multiple tables appear in the FROM clause of the query. The select list of the query can select any columns
from any of these tables. If any two of these tables have a column name in common, then you must qualify all references to
these columns throughout the query with table names to avoid ambiguity.
Join Conditions
Most join queries contain at least one join condition, either in the FROM clause or in the WHERE clause. The join
condition compares two columns, each from a different table. To execute a join, Oracle Database combines pairs of rows,
each containing one row from each table, for which the join condition evaluates to TRUE. The columns in the join
conditions need not also appear in the select list.
To execute a join of three or more tables, Oracle first joins two of the tables based on the join conditions comparing their
columns and then joins the result to another table based on join conditions containing columns of the joined tables and the
new table. Oracle continues this process until all tables are joined into the result. The optimizer determines the order in
which Oracle joins tables based on the join conditions, indexes on the tables, and, any available statistics for the tables.
IA WHERE clause that contains a join condition can also contain other conditions that refer to columns of only one table.
These conditions can further restrict the rows returned by the join query.
Note:
You cannot specify LOB columns in the WHERE clause if the WHERE clause contains the join condition. The use of
LOBs in WHERE clauses is also subject to other restrictions. See Oracle Database SecureFiles and Large Objects
Developer's Guide for more information.
Equijoins
An equijoin is a join with a join condition containing an equality operator. An equijoin combines rows that have equivalent
values for the specified columns. Depending on the internal algorithm the optimizer chooses to execute the join, the total
size of the columns in the equijoin condition in a single table may be limited to the size of a data block minus some
overhead. The size of a data block is specified by the initialization parameter DB_BLOCK_SIZE.
See Also:
"Using Join Queries: Examples"
Self Joins
A self join is a join of a table to itself. This table appears twice in the FROM clause and is followed by table aliases that
qualify column names in the join condition. To perform a self join, Oracle Database combines and returns rows of the table
that satisfy the join condition.
See Also:
"Using Self Joins: Example"
Cartesian Products
If two tables in a join query have no join condition, then Oracle Database returns their Cartesian product. Oracle
combines each row of one table with each row of the other. A Cartesian product always generates many rows and is rarely
useful. For example, the Cartesian product of two tables, each with 100 rows, has 10,000 rows. Always include a join
condition unless you specifically need a Cartesian product. If a query joins three or more tables and you do not specify a
join condition for a specific pair, then the optimizer may choose a join order that avoids producing an intermediate
Cartesian product.
Inner Joins
An inner join (sometimes called a simple join) is a join of two or more tables that returns only those rows that satisfy the
join condition.
Outer Joins
An outer join extends the result of a simple join. An outer join returns all rows that satisfy the join condition and also
returns some or all of those rows from one table for which no rows from the other satisfy the join condition.
To write a query that performs an outer join of tables A and B and returns all rows from A (a left outer join), use
the LEFT [OUTER] JOIN syntax in the FROM clause, or apply the outer join operator (+) to all columns of B in
the join condition in the WHERE clause. For all rows in A that have no matching rows in B, Oracle Database
returns null for any select list expressions containing columns of B.
To write a query that performs an outer join of tables A and B and returns all rows from B (a right outer join), use
the RIGHT [OUTER] JOIN syntax in the FROM clause, or apply the outer join operator (+) to all columns of A in
the join condition in the WHERE clause. For all rows in B that have no matching rows in A, Oracle returns null
for any select list expressions containing columns of A.
To write a query that performs an outer join and returns all rows from A and B, extended with nulls if they do not
satisfy the join condition (a full outer join), use the FULL [OUTER] JOIN syntax in the FROM clause.
You cannot compare a column with a subquery in the WHERE clause of any outer join, regardless which form you specify.
You can use outer joins to fill gaps in sparse data. Such a join is called a partitioned outer join and is formed using the
query_partition_clause of the join_clause syntax. Sparse data is data that does not have rows for all possible values of a
dimension such as time or department. For example, tables of sales data typically do not have rows for products that had no
sales on a given date. Filling data gaps is useful in situations where data sparsity complicates analytic computation or
where some data might be missed if the sparse data is queried directly.
See Also:
join_clause for more information about using outer joins to fill gaps in sparse data
Oracle Database Data Warehousing Guide for a complete discussion of group outer joins and filling gaps in
sparse data
Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join
queries that use the Oracle join operator (+) are subject to the following rules and restrictions, which do not apply to the
FROM clause OUTER JOIN syntax:
You cannot specify the (+) operator in a query block that also contains FROM clause join syntax.
The (+) operator can appear only in the WHERE clause or, in the context of left-correlation (when specifying the
TABLE clause) in the FROM clause, and can be applied only to a column of a table or view.
If A and B are joined by multiple join conditions, then you must use the (+) operator in all of these conditions. If
you do not, then Oracle Database will return only the rows resulting from a simple join, but without a warning or
error to advise you that you do not have the results of an outer join.
The (+) operator does not produce an outer join if you specify one table in the outer query and the other table in an
inner query.
You cannot use the (+) operator to outer-join a table to itself, although self joins are valid. For example, the
following statement is not valid:
The (+) operator can be applied only to a column, not to an arbitrary expression. However, an arbitrary expression
can contain one or more columns marked with the (+) operator.
A WHERE condition containing the (+) operator cannot be combined with another condition using the OR logical
operator.
A WHERE condition cannot use the IN comparison condition to compare a column marked with the (+) operator
with an expression.
If the WHERE clause contains a condition that compares a column from table B with a constant, then the (+) operator must
be applied to the column so that Oracle returns the rows from table A for which it has generated nulls for this column.
Otherwise Oracle returns only the results of a simple join.
In a query that performs outer joins of more than two pairs of tables, a single table can be the null-generated table for only
one other table. For this reason, you cannot apply the (+) operator to columns of B in the join condition for A and B and the
join condition for B and C. Refer to SELECT for the syntax for an outer join.
Antijoins
An antijoin returns rows from the left side of the predicate for which there are no corresponding rows on the right side of
the predicate. It returns rows that fail to match (NOT IN) the subquery on the right side.
See Also:
"Using Antijoins: Example"
Semijoins
A semijoin returns rows that match an EXISTS subquery without duplicating rows from the left side of the predicate when
multiple rows on the right side satisfy the criteria of the subquery.
Semijoin and antijoin transformation cannot be done if the subquery is on an OR branch of the WHERE clause.
column_name1, column_name2 are the names of the columns which define the primary Key.
For Example: To create an employee table with Primary Key constraint, the query would be like.
For Example:
For Example: To create a employee table with Null value, the query would be like
CREATE TABLE employee
( id number(5),
name char(20) CONSTRAINT nm_nn NOT NULL,
dept char(10),
age number(2),
salary number(10),
location char(10)
);
4) SQL Unique Key:
This constraint ensures that a column or a group of columns in each row have a distinct value. A column(s) can have a null
value but the values cannot be duplicated.
Syntax to define a Unique key at column level:
[CONSTRAINT constraint_name] UNIQUE
Syntax to define a Unique key at table level:
[CONSTRAINT constraint_name] UNIQUE(column_name)
For Example: To create an employee table with Unique key, the query would be like,
Unique Key at column level:
CREATE TABLE employee
( id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10) UNIQUE
); or
CREATE TABLE employee
( id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10) CONSTRAINT loc_un UNIQUE
);
Unique Key at table level:
CREATE TABLE employee
( id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10),
CONSTRAINT loc_un UNIQUE(location)
);
5) SQL Check Constraint :
This constraint defines a business rule on a column. All the rows must satisfy this rule. The constraint can be applied for a
single column or a group of columns.
Syntax to define a Check constraint: