You are on page 1of 22

INSTITUTE OF INNOVATION IN TECHNOLOGY AND MANAGEMENT

Handouts for Subject: DATABASE MANAGEMENT SYSTEMS (DBMS)


Prepared for: BCA Paper Code: BCA-110

UNIT-2:

INTRODUCTION TO SQL:
SQL (Structured Query Language) is a database sublanguage for querying and modifying relational databases. It
was developed by IBM Research in the mid 70's and standardized by ANSI in 1986.The Structured Query
Language (SQL) is the language of databases. All modern relational databases, including Access, FileMaker
Pro, Microsoft SQL Server and Oracle use SQL as their basic building block. All of the graphical user interfaces
that provide data entry and manipulation functionality are nothing more than SQL translators. They take the
actions you perform graphically and convert them to SQL commands understood by the database.

CHARACTERISTICS OF SQL:
1.SQL can execute queries against a database 2. SQL can retrieve data from a database
3.SQL can insert records in a database 4. SQL can update records in a database
5.SQL can delete records from a database 6. SQL can create new databases
7.SQL can create new tables in a database 8. SQL can create stored procedures in a database
9.SQL can create views in a database 10. SQL can set permissions on tables, views etc.

DATA TYPES IN SQL:

1) Char:
CHAR is a fixed length string data type, so any remaining space in the field is padded with blanks.
CHAR takes up 1 byte per character. So, a CHAR (100) field (or variable) takes up 100 bytes on disk,
regardless of the string it holds.

2) Varchar:
VARCHAR is a variable length string data type, so it holds only the characters you assign to it.
VARCHAR takes up 1 byte per character, + 2 bytes to hold length information. For example, if you
set a VARCHAR (100) data type = 'Jen', then it would take up 3 bytes (for J, E, and N) plus 2 bytes, or
5 bytes in all.

3) Number:
Numbers have the most available data types and the greatest constraints on implementation. Numbers
also pose the most serious risk of degraded data during ports between differing database
implementations. Design variances between implementations—say the same type has different default
size limits in Oracle and SQL Server—can cause the porting process to truncate your numbers, altering
their value.

4) Date
The date is displayed in YYYY-MM-DD format. The documentation in my build indicates that this is
the default for the DATE data type. The DATE data type can store values from 0001-01-01 through
9999-12-31. The DATE data type seems to accept most of the formats that the DATETIME accepted.
The DATE data type only takes three bytes to store its values as compared to eight bytes for a
DATETIME. The DATE data type will accept DATETIME values and implicitly convert it to a DATE
by removing the time portion.
TYPES OF SQL STATEMENTS:
There are four basic types of SQL statements:

 Data definition language (DDL) statements


 Data manipulation language (DML) statements
 Data control language(DCL) statements
 Transaction control language(TCL) statements

1) DDL: - The Data Definition Language (DDL) is used to create and destroy databases and
database objects. These SQL statements define the structure of a database, including rows,
columns; tables, indexes, and database specifics such as file locations. DDL SQL statements
are more part of the DBMS and have large differences between the SQL variations. These
commands will primarily be used by database administrators.

 CREATE - to create objects in the database


 ALTER - alters the structure of the database
 DROP - delete objects from the database

 CREATE TABLE, ALTER TABLE, DROP TABLE


 CREATE VIEW, DROP VIEW

2) DML: - The Data Manipulation Language (DML) is used to retrieve, insert and modify
database information. These SQL statements are used to retrieve and manipulate data. This
category encompasses the most fundamental commands including DELETE, INSERT,
SELECT, and UPDATE. These commands will be used by all database users during the
routine operation of the database. Even though select is not exactly a DML language
command oracle still recommends you to consider SELECT as a DML command. Examples:
SELECT, INSERT, UPDATE, and DELETE.
 SELECT - retrieve data from the database.
 INSERT - insert data into a table.
 UPDATE - updates existing data within a table.
 DELETE - deletes all records from a table, the space for the records remain.

3) DCL: - Data control commands in SQL allow you to control access to data within the
database. These SQL statements control the security and permissions of the objects or parts of
the database(s). These DCL commands are normally used to create objects related to user
access and also control the distribution of privileges among users. Some data control
commands are as follows:
 GRANT - gives user's access privileges to database
 REVOKE - withdraw access privileges given with the GRANT command

4) TCL: - Transaction control commands allow the user to manage database 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.

DDL:

I. CREATE TABLE STATEMENT:


The CREATE TABLE Statement creates a new base table. It adds the table description to the catalog.
A base table is a logical entity with persistence. The logical description of a base table consists of:
 Schema -- the logical database design of the table.
 Table Name -- a name unique among tables and views in the Schema.
 Column List -- an ordered list of column declarations (name, data type).
 Constraints -- a list of constraints on the contents of the table.

The CREATE TABLE Statement has the following general format:

Syntax:
CREATE TABLE table-name (column-- name data-type (Size) [column-constraints])

Table-name is the name of the table. Column- name is the name of the column and must be unique
among the columns of the table. Data- type declares the type of the column. Constraint is a table
constraint.
The column declaration can include optional column constraints. The declaration has the following
general format:

Examples for CREATE TABLE statement:


 CREATE TABLE employee (eid VARCHAR(5) NOT NULL PRIMARY KEY, name
VARCHAR(16), city VARCHAR(16))

 CREATE TABLE product (pno VARCHAR(5) NOT NULL PRIMARY KEY, pname
VARCHAR(16), pcolor VARCHAR(8))
Constraints:
Constraints are used to limit the type of data that can go into a table. Constraints can be specified
when a table is created (with the CREATE TABLE statement) or after the table is created (with the
ALTER TABLE statement).
Constraints can be defined in two ways:
1) The constraints can be specified immediately after the column definition. This is called column-
level definition.
2) The constraints can be specified after all the columns are defined. This is called table-level
definition.
We will focus on the following constraints:
(I) NOT NULL Constraint:
The NOT NULL constraint enforces a column to NOT accept NULL values. The NOT
NULL constraint enforces a field to always contain a value. This means that you cannot
update a record without adding a value to this field.
CREATE TABLE Persons ( P_Id number (3) NOT NULL, LastName varchar (255)
NOT NULL, FirstName varchar (255), Address varchar (255), City varchar (255))
(II) UNIQUE Constraint:
The UNIQUE constraint uniquely identifies each record in a database table. The
UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a
column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE
constraint defined on it. Note that you can have many UNIQUE constraints per table, but
only one PRIMARY KEY constraint per table.
CREATE TABLE Persons( P_Id number (3) NOT NULL UNIQUE, LastName
varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City
varchar(255)).

(III) PRIMARY KEY Constraint:


The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain unique values. A primary key column cannot contain NULL
values. Each table should have a primary key, and each table can have only ONE primary
key.
CREATE TABLE Persons ( P_Id number (3) PRIMARY KEY, LastName
varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City
varchar(255))

To allow defining a PRIMARY KEY constraint on multiple columns:


CREATE TABLE Persons ( P_Id number (3), LastName varchar(255) NOT NULL,
FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT
PRIMARY KEY (P_Id,LastName))

(IV) FOREIGN KEY Constraint:


A FOREIGN KEY in one table points to a PRIMARY KEY in another table. The
FOREIGN KEY constraint is used to prevent actions that would destroy links between
tables. The FOREIGN KEY constraint also prevents that invalid data from being inserted
into the foreign key column, because it has to be one of the values contained in the table it
points to.
CREATE TABLE Orders ( O_Id number (3)PRIMARY KEY, OrderAmt number
(3) NOT NULL, P_Id int, CONSTRAINT name FOREIGN KEY( P_Id)
REFERENCES Persons(P_Id))

(V) CHECK Constraint:


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 single column it allows 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.

The following SQL creates a CHECK constraint on the "P_Id" column when the
"Persons" table is created. The CHECK constraint specifies that the column "P_Id" must
only include integers greater than 0.

CREATE TABLE Persons ( P_Id int CONSTAINT name CHECK (P_Id>0),


LastName varchar(255) NOT NULL, FirstName varchar(255), Address
varchar(255), City varchar(255))

For defining a CHECK constraint on multiple columns, use the following SQL syntax:
CREATE TABLE Persons ( P_Id number NOT NULL, LastName varchar(255)
NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255),
CONSTRAINT name CHECK (P_Id>0 AND City='Sydney'))
(VI) DEFAULT Constraint:
The DEFAULT constraint is used to insert a default value into a column. The default
value will be added to all new records, if no other value is specified.The following SQL
creates a DEFAULT constraint on the "City" column when the "Persons" table is created:
CREATE TABLE Persons( P_Id int NOT NULL, LastName varchar(255) NOT
NULL, FirstName varchar(255), Address varchar(255), City varchar(255)
DEFAULT 'not defined')

II. ALTER TABLE STATEMENT:


The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.

Syntax:
To add a column in a table, use the following syntax:
ALTER TABLE table_name
ADD column_name datatype

To delete a column in a table, use the following syntax (notice that some database systems don't allow
deleting a column):
ALTER TABLE table_name
DROP COLUMN column_name

To change the data type of a column in a table, use the following syntax:
ALTER TABLE table _name
ALTER COLUMN column _name datatype

III. DROP TABLE STATEMENT:


The DROP TABLE statement is used to delete a table..

Syntax:
DROP TABLE table _name

DML:
1. INSERT STATEMENT:
The INSERT INTO statement is used to insert new records in a table.

Syntax:
It is possible to write the INSERT INTO statement in two forms:

(i) The first form doesn't specify the column names where the data will be inserted, only their
values:
INSERT INTO table _ name VALUES (value1, value2, value3,...)

(ii) The second form specifies both the column names and the values to be inserted:
INSERT INTO table _ name (column1, column2, column3,...) VALUES (value1, value2,
value3,...)

Example:
(i) INSERT INTO Persons VALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger')
(ii) Insert Data Only in Specified Columns:
It is also possible to only add data in specific columns.
INSERT INTO Persons (P_Id, LastName, FirstName) VALUES (5, 'Tjessem', 'Jakob')
2. UPDATE STATEMENT:
The UPDATE statement is used to update records in a table.
Syntax:
UPDATE table _name SET column1=value1, column2=value2 WHERE column1=value
Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record
or records that should be updated. If you omit the WHERE clause, all records will be updated!

Example:
We want to update the person "Tjessem, Jakob" in the "Persons" table.
We use the following SQL statement:
UPDATE Persons SET Address='Nissestien 67', City='Sandnes' WHERE LastName='Tjessem' AND
FirstName='Jakob'

3. DELETE STATEMENT:
The DELETE statement is used to delete records in a table.
Syntax:
DELETE FROM table_name WHERE column = value.
Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record
or records that should be deleted. If you omit the WHERE clause, all records will be deleted!
Example:
We want to delete the person "Tjessem, Jakob" in the "Persons" table. We use the following SQL
statement:
DELETE FROM Persons WHERE LastName='Tjessem' AND FirstName='Jakob'

Delete All Rows:


It is possible to delete all rows in a table without deleting the table. This means that the table structure,
attributes, and indexes will be intact:
DELETE FROM table_name
or
DELETE * FROM table_name

4. SELECT STATEMENT:
The SELECT statement is used to select data from a database. The result is stored in a result table,
called the result-set.
Syntax:
SELECT column_ name(s) FROM table_ name
We want to select the content of the columns named "LastName" and "FirstName", then we will
write:
SELECT LastName,FirstName FROM Persons
Example:
We want to select all the columns from the "Persons" table, then we use the following SELECT
statement:
SELECT * FROM Persons
DCL:

1. GRANT STATEMENT:
GRANT is a command used to provide access or privileges on the database objects to the users.
Syntax:

GRANT privilege_name ON object_name TO {user_name |PUBLIC} [WITH GRANT OPTION];

 Privilege_name: is the access right or privilege granted to the user.


 Object_name: is the name of an database object like TABLE, VIEW etc.
 User_name: is the name of the user to whom an access right is being granted.
 Public: is used to grant access rights to all users.
 With grant option: allows a user to grant access rights to other users.
For Example: GRANT SELECT ON employee TO user1;This command grants a SELECT
permission on employee table to user1.You should use the WITH GRANT option carefully because
for example if you GRANT SELECT privilege on employee table to user1 using the WITH GRANT
option, then user1 can GRANT SELECT privilege on employee table to another user, such as user2
etc. Later, if you REVOKE the SELECT privilege on employee from user1, still user2 will have
SELECT privilege on employee table.

2. REVOKE STATEMENT:
The REVOKE command removes user access rights or privileges to the database objects.

Syntax:
REVOKE privilege_name ON object_name FROM {user_name |PUBLIC}

For Example: REVOKE SELECT ON employee FROM user1;This command will REVOKE a
SELECT privilege on employee table from user1.When you REVOKE SELECT privilege on a table
from a user, the user will not be able to SELECT data from that table anymore. However, if the user
has received SELECT privileges on that table from more than one users, he/she can SELECT from
that table until everyone who granted the permission revokes it. You cannot REVOKE privileges if
they were not initially granted by you.

TCL:

1. COMMIT STATEMENT:
The COMMIT command is the transactional command used to save changes performed by a
transaction to the database. The COMMIT command saves all transactions to the database.

Syntax:
COMMIT;
Example:
Consider CUSTOMERS table is having following records:
| ID |NAME | AGE | ADDRESS | SALARY |
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |

Following is the example which would delete records from the table having age = 25, and then
COMMIT the changes in the database.
DELETE FROM CUSTOMERS WHERE AGE = 25;
COMMIT;

2. ROLLBACK STATEMENT:
The ROLLBACK command is the transactional command used to undo transactions that have not
already been saved to the database. The ROLLBACK command can only be used to undo transactions
since the last COMMIT or ROLLBACK command was issued.

Syntax:
ROLLBACK;

Example:
Consider CUSTOMERS table is having following records:
| ID | NAME | AGE | ADDRESS | SALARY
| 1 | Ramesh | 32 | Ahmedabad |2000.00 |
| 2 | Khilan | 25 | Delhi |1500.00 |
| 3 | kaushik | 23 | Kota |2000.00 |
| 4 | Chaitali | 25 | Mumbai |6500.00 |
| 5 | Hardik | 27 | Bhopal |8500.00 |
| 6 | Komal | 22 | MP |4500.00 |
| 7 | Muffy | 24 | Indore |10000.00

Following is the example which would delete records from the table having age = 25, and then
ROLLBACK the changes in the database.

DELETE FROM CUSTOMERS WHERE AGE = 25;


ROLLBACK;

3. SAVEPOINT STATEMENT:
A SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain point
without rolling back the entire transaction.

Syntax: (FOR CREATING SAVEPOINTS)

SAVEPOINT SAVEPOINT_NAME;
This command serves only in the creation of a SAVEPOINT among transactional statements. The
ROLLBACK command is used to undo a group of transactions.

The syntax for rolling back to a SAVEPOINT is as follows:

ROLLBACK TO SAVEPOINT_NAME;

Following is an example where you plan to delete the three different records from the CUSTOMERS
table. You want to create a SAVEPOINT before each delete, so that you can ROLLBACK to any
SAVEPOINT at any time to return the appropriate data to its original state:

Example:
Consider CUSTOMERS table is having following records:

| ID | NAME | AGE | ADDRESS | SALARY


| 1 | Ramesh | 32 | Ahmedabad | 2000.00
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |

Now here is the series of operations:

SAVEPOINT SP1;
Savepoint created.

DELETE FROM CUSTOMERS WHERE ID=1;


1 row deleted.

SAVEPOINT SP2;
Savepoint created.

DELETE FROM CUSTOMERS WHERE ID=2;


1 row deleted.

SAVEPOINT SP3;
Savepoint created.

DELETE FROM CUSTOMERS WHERE ID=3;


1 row deleted.

Now that the three deletions have taken place, say you have changed your mind and decided to
ROLLBACK to the SAVEPOINT that you identified as SP2. Because SP2 was created after the first
deletion, the last two deletions are undone:

ROLLBACK TO SP2;
Rollback complete.

CLAUSES:

They are the conditional statements using which certain conditions can be imposed along with the
manipulation statements.

i. SQL WHERE CLAUSE:

The WHERE clause is used to filter records. The WHERE clause is used to extract only those records
that fulfill a specified criterion.

Syntax:
SELECT column_name(s) FROM table_name WHERE column_name operator value

Example:
We want to select only the persons living in the city "Sydney"

SELECT * FROM Persons WHERE City='Sydney'.


Operators Allowed in the WHERE Clause:
Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN To specify multiple possible values for a column

 SQL AND & OR Operators:

The AND & OR Operators:


The AND operator displays a record if both the first condition and the second condition is true.
The OR operator displays a record if either the first condition or the second condition is true.

AND Operator Example:


We want to select only the persons with the first name equal to "Tove" AND the last name equal to
"Svendson". We use the following SELECT statement:
SELECT * FROM Persons WHERE FirstName = 'Tove' AND LastName = 'Svendson'.
OR Operator Example:
Now we want to select only the persons with the first name equal to "Tove" OR the first name equal
to "Ola". We use the following SELECT statement:
SELECT * FROM Persons WHERE FirstName = 'Tove' OR FirstName = 'Ola'

ii. SQL ORDER BY CLAUSE:

The ORDER BY keyword is used to sort the result-set by a specified column. The ORDER BY
keyword sorts the records in ascending order by default.
If you want to sort the records in a descending order, you can use the DESC keyword.
Syntax:
SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC.

Example:
We want to select all the persons from the table above; however, we want to sort the persons by their
last name. We use the following SELECT statement:
SELECT * FROM Persons ORDER BY LastName

ORDER BY DESC Example:


Now we want to select all the persons from the table above, however, we want to sort the persons
descending by their last name. We use the following SELECT statement:
SELECT * FROM Persons ORDER BY LastName DESC

iii. SQL GROUP BY CLAUSE:


Aggregate functions often need an added GROUP BY statement. The GROUP BY statement is used
in conjunction with the aggregate functions to group the result-set by one or more columns.
Syntax:
SELECT column_name, aggregate_function (column_name) FROM table_name WHERE
column_name operator value GROUP BY column_name.
Example:
We have the following "Orders" table:
O_ Id Order Date Order Price Customer
1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen

We want to find the total sum (total order) of each customer. We will have to use the GROUP BY
statement to group the customers. We use the following SQL statement:

SELECT SUM (Order Price) FROM Orders GROUP BY Customer.

iv. SQL HAVING:

The HAVING was added to SQL because the WHERE could not be used with aggregate function
output.

Syntax:
SELECT column_name, aggregate_function(column_name) FROM table_name WHERE
column_name operator value GROUP BY column_name HAVING
aggregate_function(column_name) operator value

Example:
We want to find if any of the customers have a total order of less than 2000. We use the following
SQL statement:

SELECT Customer, SUM (Order Price) FROM Orders GROUP BY Customer HAVING SUM (Order
Price) <2000

Now we want to find if the customers "Hansen" or "Jensen" have a total order of more than 1500. We
add an ordinary WHERE clause to the SQL statement:
SELECT Customer, SUM (Order Price) FROM Orders WHERE Customer='Hansen' OR
Customer='Jensen' GROUP BY Customer HAVING SUM (Order Price) >1500.

AGGREGATE FUNCTIONS:
SQL aggregate functions return a single value, calculated from values in a column. Useful
aggregate functions:
 AVG() - Returns the average value
 COUNT() - Returns the number of rows
 FIRST() - Returns the first value
 LAST() - Returns the last value
 MAX() - Returns the largest value
 MIN() - Returns the smallest value
 SUM() - Returns the sum

Suppose we have the following "Orders" table:


Now keeping this table in mind, we will discuss the following aggregate functions:

1. SQL AVG( ) Function:


The AVG ( ) function returns the average value of a numeric column.
Syntax:
SELECT AVG (column_ name) FROM table_ name

Example:
We want to find the average value of the "Order Price" fields. We use the following
SQL statement:
SELECT AVG (Order Price) FROM Orders.

2. SQL COUNT( ) Function:


The COUNT ( ) function returns the number of rows that matches a specified criteria.
Syntax:
SELECT COUNT (column_ name) FROM table _ name

The COUNT (column_ name) function returns the number of values (NULL values
will not be counted) of the specified column. Also, the COUNT (*) function returns
the number of records in a table.
SELECT COUNT (*) FROM table_ name

3. SQL MAX( ) Function:


The MAX ( ) function returns the largest value of the selected column.
Syntax:
SELECT MAX (column_ name) FROM table_ name

Example:
We want to find the largest value of the "Order Price" column. We use the following
SQL statement:
SELECT MAX (Order Price) FROM Orders.

4. SQL MIN( ) Function:


The MIN ( ) function returns the smallest value of the selected column.
Syntax:
SELECT MIN (column_ name) FROM table_ name
Example:
We want to find the smallest value of the "Order Price" column. We use the following
SQL statement:
SELECT MIN (Order Price) FROM Orders.

5. SQL SUM( ) Function:


The SUM ( ) function returns the total sum of a numeric column.
Syntax:
SELECT SUM (column_ name) FROM table_ name

Example:
We want to find the sum of all "Order Price" field. We use the following SQL
statement:
SELECT SUM (Order Price) FROM Orders.

6. SQL FIRST ( ) Function:


The FIRST ( ) function returns the first value of the selected column.
Syntax:
SELECT FIRST (column_ name) FROM table_ name

Example:
We want to find the first value in "Order Price" fields. We use the following SQL
statement:
SELECT FIRST (Order Price) FROM Orders.

7. SQL LAST ( ) Function:


The LAST ( ) function returns the last value of the selected column.
Syntax:
SELECT LAST (column_ name) FROM table_ name

Example:
We want to find the last value in "Order Price" fields. We use the following SQL
statement:
SELECT LAST (Order Price) FROM Orders.

UNION, INTERSECT AND EXCEPT OPERATORS (SET-COMPARISON OPERATORS):

1. UNION OPERATOR:
The SQL UNION operator combines two or more SELECT statements. The UNION operator
is used to combine the result-set of two or more SELECT statements.

Notice that each SELECT statement within the UNION must have the same number of
columns. The columns must also have similar data types.

Syntax:
SELECT column_ name(s) FROM table_name1 UNION SELECT column_ name(s) FROM
table_name2
2. INTERSECT OPERATOR:
The SQL INTERSECT query allows you to return the results of 2 or more "select"
queries. However, it only returns the rows selected by all queries.

If a record exists in one query and not in the other, it will be omitted from the
INTERSECT results.

Each SQL statement within the SQL INTERSECT query must have the same number
of fields in the result sets with similar data types.

Syntax:
SELECT field1, field2, ……field n FROM table name INTERSECT SELECT field1,
field2, field n FROM table name;

Example:
The following is an example of an SQL INTERSECT query that has one field with
the same data type:
SELECT supplier_id FROM suppliers INTERSECT SELECT supplier_id FROM
orders;

In this SQL INTERSECT query example, if a supplier_id appeared in both the


suppliers and orders table, it would appear in your result set.

3. EXCEPT OPERATOR:
The SQL EXCEPT clause/operator is used to combine two SELECT statements and
returns rows from the first SELECT statement that are not returned by the second
SELECT statement. This means EXCEPT returns only rows which are not available
in second SELECT statement.

Syntax:
SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition]
EXCEPT SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE
condition].
SQL WILDCARDS:
SQL wildcards can be used when searching for data in a database. SQL wildcards can
substitute for one or more characters when searching for data in a database. SQL wildcards
must be used with the SQL LIKE operator. With SQL, the following wildcards can be used:
SQL-JOINS:

An SQL join clause combines records from two or more tables in a database. It creates a set
that can be saved as a table or used as it is. A JOIN is a means for combining fields from two
tables by using values common to each.

ANSI-standard SQL specifies five types of JOIN: INNER, LEFT OUTER, RIGHT OUTER,
FULL OUTER and CROSS.

For example, a Department may be associated with many different Employees. Joining two
tables effectively creates another table which combines information from both tables. In the
following tables the DepartmentID column of the Department table (which can be designated
as Department. DepartmentID) is the primary key, while Employee. DepartmentID is a
foreign key.

There are 5 types of JOIN:-

INNER LEFT OUTER RIGHT OUTER FULL OUTER CROSS


1. CROSS JOIN:
CROSS JOIN returns the Cartesian product of rows from tables in the join. In other
words, it will produce rows which combine each row from the first table with each
row from the second table.

SELECT * FROM employee CROSS JOIN department;

2. INNER JOIN:
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) and then
returning all records which satisfy the join predicate.

SELECT *FROM employee INNER JOIN department ON employee.DepartmentID =


department.DepartmentID;
Rafferty 31 sales 31
Jones 33 Engineering 33
Heisenberg 33 Engineering 33
Robinson 34 Clerical 34
Smith 34 Clerical 34
EQUI-JOIN:
An equi-join is a specific type of comparator-based 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;

3. NATURAL-JOIN:
A natural join is a type of equi-join where the join predicate arises implicitly by
comparing all columns in both tables that have the same column-names in the joined
tables. The resulting joined table contains only one column for each pair of equally
named columns.

SELECT *FROM employee NATURAL JOIN department;

4. OUTER-JOIN:
An outer join does not require each record in the two tables to have a matching
record.

a) LEFT-outer join:
Here, the result of left outer join for table T1 and T2 always contains all records of
the ‘left’ table T1, even if the join conditions does not find any matching record in
right table T2.

SELECT *FROM employee LEFT OUTER JOIN department ON


employee.DepartmentID = department.DepartmentID;
b) RIGHT-outer join:
Here, the result of right outer join for T1 and T2 always contains all records of the
right table T2, even if the join condition does not find anything matching in T1.

SELECT *FROM employee RIGHT OUTER JOIN department ON


employee.DepartmentID = department.DepartmentID;

5. FULL OUTER JOIN:

A full outer join combines the effect of applying both left and right outer joins. Where
records in the FULL OUTER JOIN tables do not match, the result set will have NULL values
for every column of the table that lacks a matching row.

SELECT *FROM employee FULL OUTER JOIN department ON employee.DepartmentID =


department.DepartmentID;
NULL VALUES:

The SQL NULL is the term used to represent a missing value. A NULL value in a table is a
value in a field that appears to be blank. A field with a NULL value is a field with no value. It
is very important to understand that a NULL value is different than a zero value.

If many attributes do not have values for the some tuples in the relation or in database, we
end up with a number of NULL values in those tuples. For example if a database defines with
five telephone numbers but most of the tuples have only one or two telephone entries then
there exist a number null values .Null values have multiple interpretations:
1. The attribute does not apply to this tuple.
2. The attribute value for this tuple is unknown.
3. The value is known but absent.
So, Relations should be designed such that their tuples will have as few NULL values as
possible and attributes that are NULL frequently could be placed in separate Relation (with
the primary key).

SQL INDEXES:

An index is defined as a table or a data structure that is maintained to determine the location
of rows or records in a file that satisfy some condition. Such a table is known as index table.

Index table: it consists of a key field and a pointer to the location where the record is stored.

Firstly, this index table is searched for the address of the record and then the reading of
record from this address. Example: index of a book.

Indexing is of two types:

1. Ordered indexing: Based on sorted orderings.


2. Hashed indexing: Based on orderings using a mathematical function called as hashed
function.
There are two types of indexes:

1. Primary or clustering index:


It is based on sequential searching. This consists of two things:
a)Primary Key
b)Physical address of record
So, when a user requests a record, the O.S. firstly loads the primary index into main
memory and reaches the index sequentially for primary key. When it finds the entry
for the primary key, it then reads the addresses in which record is stored.

2. Secondary or Non-clustering index:


The indexes whose search key is not sequentially ordered are called as secondary
indexes. It consists of two things:
a) An indexing field
b) A record pointer

You might also like