Computer SQL Project
Computer SQL Project
A self-join is a query in which a table is joined (compared) to itself. Self-joins are used to
compare values in a column with other values in the same column in the same table.
One practical use for self-joins: obtaining running counts and running totals in an SQL
query.
To write the query, select from the same table listed twice with different aliases, set up
the comparison, and eliminate cases where a particular value would be equal to itself.
Example
Which customers are located in the same state (column name is Region)? Type this
statement in the SQL window:
An inner join is the most common join operation used in applications and can be regarded as the default join-type. Inner join
creates a new result table by combining column values of two tables (A and B) based upon the join-predicate. The query
compares each row of A with each row of B to find all pairs of rows which satisfy the join-predicate. When the join-predicate is
satisfied, column values for each matched pair of rows of A and B are combined into a result row. The result of the join can be
defined as the outcome of first taking the Cartesian product (or Cross join) of all records in the tables (combining every record in
table A with every record in table B)—then return all records which satisfy the join predicate. Actual SQL implementations
normally use other approaches like a hash join or a sort-merge join where possible, since computing the Cartesian product is very
inefficient.
SQL specifies two different syntactical ways to express joins: "explicit join notation" and "implicit join notation".
The "explicit join notation" uses the JOIN keyword to specify the table to join, and the ON keyword to specify the predicates for
SELECT *
FROM employee INNER JOIN department
ON employee.DepartmentID = department.DepartmentID;
The "implicit join notation" simply lists the tables for joining (in the FROM clause of the SELECT statement), using commas to
separate them. Thus, it specifies a cross join, and theWHERE clause may apply additional filter-predicates (which function
The following example shows a query which is equivalent to the one from the previous examples, but this time written using the
SELECT *
FROM employee, department
WHERE employee.DepartmentID = department.DepartmentID;
The queries given in the examples above will join the Employee and Department tables using the DepartmentID column of both
tables. Where the DepartmentID of these tables match (i.e. the join-predicate is satisfied), the query will combine
the LastName, DepartmentID and DepartmentName columns from the two tables into a result row. Where the DepartmentID does
Thus the result of the execution of either of the two queries above will be:
Robinson 34 Clerical 34
Jones 33 Engineering 33
Smith 34 Clerical 34
Steinberg 33 Engineering 33
Rafferty 31 Sales 31
Note: Programmers should take special care when joining tables on columns that can contain NULL values, since NULL will
never match any other value (or even NULL itself), unless the join condition explicitly uses the IS NULL or IS NOT
NULL predicates.
Notice that the employee "John" and the department "Marketing" do not appear in the query execution results. Neither of these
has any matching records in the respective other table: "John" has no associated department, and no employee has the
department ID 35. Thus, no information on John or on Marketing appears in the joined table. Depending on the desired results,
this behavior may be a subtle bug. Outer joins may be used to avoid it.
One can further classify inner joins as equi-joins, as natural joins, or as cross-joins.
[edit]Equi-join
An equi-join, also known as an equijoin, is a specific type of comparator-based join, or theta join, that uses
only equality comparisons in the join-predicate. Using other comparison operators (such as <) disqualifies a join as an equi-join.
SELECT *
FROM employee
JOIN department
ON employee.DepartmentID = department.DepartmentID;
If columns in an equijoin have the same name, SQL/92 provides an optional shorthand notation for expressing equi-joins, by way
SELECT *
FROM employee
INNER JOIN department
USING (DepartmentID);
The USING construct is more than mere syntactic sugar, however, since the result set differs from the result set of the version
with the explicit predicate. Specifically, any columns mentioned in the USING list will appear only once, with an unqualified
name, rather than once for each table in the join. In the above case, there will be a single DepartmentID column and
no employee.DepartmentID or department.DepartmentID.
2) What is a subquery?
A subquery is a query within a query. In Oracle, you can create subqueries within your SQL statements. These subqueries can reside in the
WHERE clause, the FROM clause, or the SELECT clause.
Subqueries
A subquery is a query expression enclosed in parentheses. Subqueries can be nested inside INSERT, DELETE, UPDATE,
and SELECT statements, or other query expressions, to an arbitrary depth. The statement or expression that contains the
subquery is called the subquery's parent. Typically, subqueries are used to derive a set of results that can be evaluated in
conjunction with the result set of the parent query.
Several detailed examples of subqueries used in the select list, the FROM clause, and the WHERE clause are presented in
the SQL Self-Study Guide.
According to the ANSI standard, subqueries fall into three categories: scalar, row, and table. IBM Red Brick Warehouse supports
scalar subqueries and table subqueries:
• A scalar subquery returns a single scalar value (one column, one row) and can occur either in a select list or in
a condition as an argument of a comparison operator.
• A table subquery returns a result table of zero or more rows and can occur either in a FROM clause or in a condition as
an argument of anEXISTS, IN, SOME, ANY, or ALL predicate.
FROM clause subqueries and subqueries used as arguments to EXISTS predicates might consist of multiple columns
as well as multiple rows. However, the select lists of subqueries used as arguments to IN, SOME, ANY,
or ALL predicates are restricted to one column.
WHERE clause
Most often, the subquery will be found in the WHERE clause. These subqueries are also called nested subqueries.
For example:
Limitations:
3)
Structured Query Language, is a database computer language designed for managing data in relational database management
systems (RDBMS), and originally based upon relational algebra and calculus.[4] Its scope includes data insert, query, update and
delete, schema creation and modification, and data access control. SQL was one of the first commercial languages for Edgar F.
Codd's relational model, as described in his influential 1970 paper, "A Relational Model of Data for Large Shared Data Banks".
[5]
Despite not adhering to the relational model as described by Codd, it became the most widely used database language.[6][7]
Categories in SQL commands
There are 3 broad categories in SQL commands. They are namely
DROP TABLE: This command is used to remove an existing table permanently from database.
SYNTAX: DROP TABLE tablename;
If we want to select all column values from a table then SQL command use is
SELECT * from tablename ;
Based on the condition specified the rows gets fetched from the table and gets deleted in table. Here the WHERE
clause is optional.
UPDATE: This SQL command is used to modify the values in an existing table.
SYNTAX: UPDATE tablename SET columnname = value, columnname = value,….. WHERE condition;
The rows which satisfies the WHERE condition are fetched and for these rows the column values we placed in
command above in SET statement gets updated.
Commands under Transaction Control Statements
ROLLBACK – This SQL command is used to undo the current transaction
SYNTAX: ROLLBACK;
SAVEPOINT: This is used to identify a point in a transaction to which we can later rollback.
COMMIT: This command is used to make all changes permanent in database and also marks the end of
transaction.
SYNTAX: COMMIT;
Always it is better to commit changes to database at regular intervals since it will help loss of data or loss of work
done when computer shuts due to unavoidable reasons.
Having known about the broad categories of SQL commands let us see some more SQL important terminologies.
6) Referential integrity
Many applications do not use foreign key referential integrity and, instead, rely
upon application code to enforce business rules. This method is not foolproof
because the application tables can be accessed via other means such as
SQL*PLUS.
A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the
database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from
one single table.
If you have the Northwind database you can see that it has several views installed by default.
The view "Current Product List" lists all active products (products that are not discontinued) from the "Products" table.
The view is created with the following SQL:
Now we want to add the "Category" column to the "Current Product List" view. We will update the view with the following
SQL:
Sequences
A sequence is a database object that generates numbers in sequential order. Applications most
often use these numbers when they require a unique value in a table such as primary key
values. Some database management systems use an "auto number" concept or "auto
increment" setting on numeric column types. Both the auto numbering columns and sequences
provide a unique number in sequence used for a unique identifier. The following list describes
the characteristics of sequences:
• Sequences are available to all users of the database
• Sequences are created using SQL statements (see below)
• Sequences have a minimum and maximum value (the defaults are minimum=0 and
maximum=263-1); they can be dropped, but not reset
• Once a sequence returns a value, the sequence can never return that same value
• While sequence values are not tied to any particular table, a sequence is usually used
to generate values for only one table
• Sequences increment by an amount specified when created (the default is 1)
Creating a Sequence
To create sequences, execute a CREATE SEQUENCE statement in the same way as an
UPDATE or INSERT statement. The sequence information is stored in a data dictionary file in
the same location as the rest of the data dictionary files for the database. If the data dictionary
file does not exist, the SQL engine creates the file when it creates the first sequence. In legacy
dictionaries, the new file name is SEQUENCE.DD. The format of this file remains proprietary
and subject to change, so do not depend on the record layout or format of the data. In Journaled
Filesystem databases, this information is also proprietary and subject to change.
The format for a CREATE SEQUENCE statement is as follows:
CREATE SEQUENCE sequence_name
[INCREMENT BY #]
[START WITH #]
[MAXVALUE # | NOMAXVALUE]
[MINVALUE # | NOMINVALUE]
[CYCLE | NOCYCLE]
Variable Description
INCREMENT BY The increment value. This can be a positive or negative number.
START WITH The start value for the sequence.
MAXVALUE The maximum value that the sequence can generate. If specifying NOMAXVALUE,
the maximum value is 263-1.
MINVALUE The minimum value that the sequence can generate. If specifying NOMINVALUE,
the minimum value is -263.
CYCLE Specify CYCLE to indicate that when the maximum value is reached the sequence
starts over again at the start value. Specify NOCYCLE to generate an error upon
reaching the maximum value.
Dropping a Sequence
To drop a sequence, execute a DROP SEQUENCE statement. Use this function when a
sequence is no longer useful, or to reset a sequence to an older number. To reset a sequence,
first drop the sequence and then recreate it.
Drop a sequence following this format:
DROP SEQUENCE my_sequence
To drop a column from a table you can use one of these syntax examples, depending on
whether you wish to drop a single column (with drop column) or multiple columns. You
can use the Oracle “alter table” syntax to drop any column from a table, as shown in this
example:
alter table
table_name
drop column
col_name1; -- drop one column
alter table
table_name
drop
(col_name1, col_name2); -- drop many columns
You can also drop a table column by marking it unused and then dropping the column,
thusly:
alter table
table_name
set unused column
column_name;
alter table
table_name
drop unused columns;
For example:
D, DROP TABLE
PURPOSE:
SYNTAX:
SQL>
SQL> select table_name,constraint_name,search_condition from
user_constraints where table_name = 'NN
_TEST';
TABLE_NAME CONSTRAINT_NAME
------------------------------ ------------------------------
SEARCH_CONDITION
-----------------------------------------------------------------------
---------
NN_TEST NN_TEST_COL_1_NN
"COL_1" IS NOT NULL
SQL>
SQL> alter table nn_test drop constraint NN_TEST_COL_1_NN;
Table altered.
SQL>
SQL> select * from user_constraints where table_name = 'NN_TEST';
no rows selected
Keys
(VII) Secondary Key – The attributes that are not even the
Super Key but can be still used for identification of records (not
unique) are known as Secondary Key.
E.g. of Secondary Key can be Name, Address, Salary,
Department_ID etc. as they can identify the records but they might
not be unique.