You are on page 1of 11

1)

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:

SELECT DISTINCT c1.ContactName, c1.Address, c1.City, c1.Region


FROM Customers AS c1, Customers AS c2
WHERE c1.Region = c2.Region
AND c1.ContactName <> c2.ContactName
ORDER BY c1.Region, c1.ContactName;
Inner join

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

the join, as in the following example:

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

comparably to the join-predicates in the explicit notation).

The following example shows a query which is equivalent to the one from the previous examples, but this time written using the

implicit join notation:

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

not match, no result row is generated.

Thus the result of the execution of either of the two queries above will be:

Employee.LastName Employee.DepartmentID Department.DepartmentName Department.DepartmentID

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.

The query shown above has already provided an example of 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

of the USING construct[2]:

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.

Scalar subqueries and table subqueries

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:

select * from all_tables tabs


where tabs.table_name in (select cols.table_name
from all_tab_columns cols
where cols.column_name = 'SUPPLIER_ID');

Limitations:

Oracle allows up to 255 levels of subqueries in the WHERE clause.

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

 Data Definition language (DDL)

 Data Manipulation Language (DML)

 Transaction Control Commands


Under each category there are many SQL commands. Let us see each in brief.

Commands under Data Definition language (DDL)


This category include creating, dropping and altering table commands

CREATE TABLE is used in creation of table(s).


SYNTAX: CREATE TABLE tablename (colname col definition, colname col definition…);
ALTER TABLE: If you want to modify a table definition we can use this command. This command is used to alter
column definition in table.
SYNTAX: ALTER TABLE tablename MODIFY (Column definition);

DROP TABLE: This command is used to remove an existing table permanently from database.
SYNTAX: DROP TABLE tablename;

Commands under Data Manipulation Language (DML)


INSERT: This command is used to insert rows into the table.
SYNTAX: INSERT INTO tablename VALUES (value,value,….);

SELECT: This is used to select values or data from table


SYNTAX: SELECT column name1, column name2, …. FROM tablename;

If we want to select all column values from a table then SQL command use is
SELECT * from tablename ;

DELETE: In order to delete rows from a table we use this command


SYNTAX: DELETE FROM tablename WHERE condition;

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.

SYNTAX: SAVEPOINT savepoint_identifier;

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

A database system needs to be able to enforce business rules. Referential


integrity (foreign key constraint) is one way Oracle provides for maintaining
business rules. Relational systems allow control of business rules with
constraints, and referential integrity rules form the backbone of relational
tables.

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.

I/O not there

7) SQL CREATE VIEW Statement


In SQL, a view is a virtual table based on the result-set of an SQL statement.

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.

SQL CREATE VIEW Syntax

CREATE VIEW view_name AS


SELECT column_name(s)
FROM table_name
WHERE condition
SQL CREATE VIEW Examples

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:

CREATE VIEW [Current Product List] AS


SELECT ProductID,ProductName
FROM Products
WHERE Discontinued=No

SQL Updating a View

You can update a view by using the following syntax:

SQL CREATE OR REPLACE VIEW Syntax

CREATE OR REPLACE VIEW view_name AS


SELECT column_name(s)
FROM table_name
WHERE condition

Now we want to add the "Category" column to the "Current Product List" view. We will update the view with the following
SQL:

CREATE VIEW [Current Product List] AS


SELECT ProductID,ProductName,Category
FROM Products
WHERE Discontinued=No

SQL Dropping a View

You can delete a view with the DROP VIEW command.

SQL DROP VIEW Syntax

DROP VIEW view_name

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

8)a, Oracle alter table drop column

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;

b, Drop a Primary Key


The syntax for dropping a primary key is:

ALTER TABLE table_name


drop CONSTRAINT constraint_name;

For example:

ALTER TABLE supplier


drop CONSTRAINT supplier_pk;

D, DROP TABLE
PURPOSE:

To remove a table and all its data from the database.

SYNTAX:

DROP TABLE [schema.]table


[CASCADE CONSTRAINTS]
C,
I)Not null constraint
SQL> create table nn_test (col_1 date constraint nn_test_col_1_nn not
null);
Table created.

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

II)To DROP a CHECK Constraint

To drop a CHECK constraint, use the following SQL:

SQL Server / Oracle / MS Access:

ALTER TABLE Persons


DROP CONSTRAINT chk_Person

III) Drop a Primary Key


The syntax for dropping a primary key is:

ALTER TABLE table_name


drop CONSTRAINT constraint_name;

Keys

(I) Super Key – An attribute or a combination of attribute that is


used to identify the records uniquely is known as Super Key. A table
can have many Super Keys.
E.g. of Super Key
1 ID
2 ID, Name
3 ID, Address
4 ID, Department_ID
5 ID, Salary
6 Name, Address
7 Name, Address, Department_ID ………… So on as any combination
which can identify the records uniquely will be a Super Key.

(II) Candidate Key – It can be defined as minimal Super Key or


irreducible Super Key. In other words an attribute or a combination of
attribute that identifies the record uniquely but none of its proper
subsets can identify the records uniquely.
E.g. of Candidate Key
1 Code
2 Name, Address
For above table we have only two Candidate Keys (i.e. Irreducible
Super Key) used to identify the records from the table uniquely. Code
Key can identify the record uniquely and similarly combination of
Name and Address can identify the record uniquely, but neither Name
nor Address can be used to identify the records uniquely as it might be
possible that we have two employees with similar name or two
employees from the same house.

(III) Primary Key – A Candidate Key that is used by the database


designer for unique identification of each row in a table is known as
Primary Key. A Primary Key can consist of one or more attributes of a
table.
E.g. of Primary Key - Database designer can use one of the
Candidate Key as a Primary Key. In this case we have “Code” and
“Name, Address” as Candidate Key, we will consider “Code” Key as a
Primary Key as the other key is the combination of more than one
attribute.

(IV) Foreign Key – A foreign key is an attribute or combination of


attribute in one base table that points to the candidate key (generally
it is the primary key) of another table. The purpose of the foreign key
is to ensure referential integrity of the data i.e. only values that are
supposed to appear in the database are permitted.
E.g. of Foreign Key – Let consider we have another table i.e.
Department Table with Attributes “Department_ID”,
“Department_Name”, “Manager_ID”, ”Location_ID” with
Department_ID as an Primary Key. Now the Department_ID attribute
of Employee Table (dependent or child table) can be defined as the
Foreign Key as it can reference to the Department_ID attribute of the
Departments table (the referenced or parent table), a Foreign Key
value must match an existing value in the parent table or be NULL.

(V) Composite Key – If we use multiple attributes to create a


Primary Key then that Primary Key is called Composite Key (also called
a Compound Key or Concatenated Key).
E.g. of Composite Key, if we have used “Name, Address” as a
Primary Key then it will be our Composite Key.

(VI) Alternate Key – Alternate Key can be any of the Candidate


Keys except for the Primary Key.
E.g. of Alternate Key is “Name, Address” as it is the only other
Candidate Key which is not a Primary Key.

(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.

You might also like