0% found this document useful (0 votes)
54 views72 pages

Unit Iv

SQL is a standard language for storing, manipulating, and retrieving data in relational databases. It includes commands like SELECT, INSERT, UPDATE, DELETE, and more to interact with database tables. SQL also defines data types for different types of data, like numeric, character, and date/time data types. Operators are used in SQL statements to compare or perform operations on data and specify query conditions. Common operators include arithmetic, comparison, and logical operators.

Uploaded by

Jyothika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views72 pages

Unit Iv

SQL is a standard language for storing, manipulating, and retrieving data in relational databases. It includes commands like SELECT, INSERT, UPDATE, DELETE, and more to interact with database tables. SQL also defines data types for different types of data, like numeric, character, and date/time data types. Operators are used in SQL statements to compare or perform operations on data and specify query conditions. Common operators include arithmetic, comparison, and logical operators.

Uploaded by

Jyothika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

1 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.

CS (2017-Onwards)

UNIT IV

SQL CONCEPTS
What is SQL?
 SQL stands for Structured Query Language .SQL is a standard language for storing,
manipulating and retrieving data in databases
 SQL lets you access and manipulate databases
 SQL became a standard of the American National Standards Institute (ANSI) in 1986, and
of the International Organization for Standardization (ISO) in 1987

SQL COMMANDS

The standard SQL commands to interact with relational databases are CREATE, SELECT,
INSERT, UPDATE, DELETE and DROP. These commands can be classified into the following
groups based on their nature −

DDL - Data Definition Language

Sr.No. Command & Description

CREATE
1
Creates a new table, a view of a table, or other object in the database.

ALTER
2
Modifies an existing database object, such as a table.

DROP
3
Deletes an entire table, a view of a table or other objects in the database.

DML - Data Manipulation Language

Sr.No. Command & Description

SELECT
1
Retrieves certain records from one or more tables.

INSERT
2
Creates a record.

UPDATE
3
Modifies records.

DELETE
4
Deletes records.
2 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

DCL - Data Control Language

Sr.No. Command & Description

GRANT
1
Gives a privilege to user.

REVOKE
2
Takes back privileges granted from user.

DATA INTEGRITY

The following categories of data integrity exist with each RDBMS −

 Entity Integrity − There are no duplicate rows in a table.

 Domain Integrity − Enforces valid entries for a given column by restricting the type, the
format, or the range of values.

 Referential integrity − Rows cannot be deleted, which are used by other records.

 User-Defined Integrity − Enforces some specific business rules that do not fall into entity,
domain or referential integrity.

SQL - DATA TYPES

 SQL Data Type is an attribute that specifies the type of data of any object. Each column,
variable and expression has a related data type in SQL. You can use these data types while
creating your tables. You can choose a data type for a table column based on your
requirement.

 SQL Server offers different categories of data types for your use which are listed below −

Exact Numeric Data Types

DATA TYPE FROM TO

bigint -9,223,372,036,854,775,808 9,223,372,036,854,775,807

int -2,147,483,648 2,147,483,647

smallint -32,768 32,767

tinyint 0 255
3 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

bit 0 1

decimal -10^38 +1 10^38 -1

numeric -10^38 +1 10^38 -1

money -922,337,203,685,477.5808 +922,337,203,685,477.5807

smallmoney -214,748.3648 +214,748.3647

Approximate Numeric Data Types

DATA TYPE FROM TO

float -1.79E + 308 1.79E + 308

real -3.40E + 38 3.40E + 38

Date and Time Data Types

DATA TYPE FROM TO

datetime Jan 1, 1753 Dec 31, 9999

smalldatetime Jan 1, 1900 Jun 6, 2079

date Stores a date like June 30, 1991

time Stores a time of day like 12:30 P.M.

Character Strings Data Types

Sr.No. DATA TYPE & Description

char
1
Maximum length of 8,000 characters.( Fixed length non-Unicode characters)

varchar
2
Maximum of 8,000 characters.(Variable-length non-Unicode data).

varchar(max)
3 Maximum length of 2E + 31 characters, Variable-length non-Unicode data (SQL
Server 2005 only).

text
4 Variable-length non-Unicode data with a maximum length of 2,147,483,647
characters.
4 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

SQL – OPERATORS

An operator is a reserved word or a character used primarily in an SQL statement's WHERE clause
to perform operation(s), such as comparisons and arithmetic operations. These Operators are used
to specify conditions in an SQL statement and to serve as conjunctions for multiple conditions in a
statement.

 Arithmetic operators
 Comparison operators
 Logical operators
 Operators used to negate conditions

SQL Arithmetic Operators

Assume 'variable a' holds 10 and 'variable b' holds 20, then −

Operator Description Example

Adds values on either side of the operator. a+b


+ (Addition) will give
30

Subtracts right hand operand from left hand operand. a - b will


- (Subtraction)
give -10

Multiplies values on either side of the operator. a * b will


* (Multiplication)
give 200

Divides left hand operand by right hand operand. b / a will


/ (Division)
give 2

Divides left hand operand by right hand operand and b%a


% (Modulus) returns remainder. will give
0

SQL Comparison Operators

Assume 'variable a' holds 10 and 'variable b' holds 20, then −

Operator Description Example

Checks if the values of two operands are equal or not, if yes then (a = b) is
=
condition becomes true. not true.

Checks if the values of two operands are equal or not, if values are (a != b)
!=
not equal then condition becomes true. is true.
5 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Checks if the values of two operands are equal or not, if values are (a <> b)
<>
not equal then condition becomes true. is true.

Checks if the value of left operand is greater than the value of (a > b) is
>
right operand, if yes then condition becomes true. not true.

Checks if the value of left operand is less than the value of right (a < b) is
<
operand, if yes then condition becomes true. true.

Checks if the value of left operand is greater than or equal to the (a >= b)
>= value of right operand, if yes then condition becomes true. is not
true.

Checks if the value of left operand is less than or equal to the (a <= b)
<=
value of right operand, if yes then condition becomes true. is true.

Checks if the value of left operand is not less than the value of (a !< b)
!<
right operand, if yes then condition becomes true. is false.

Checks if the value of left operand is not greater than the value of (a !> b)
!>
right operand, if yes then condition becomes true. is true.

SQL Logical Operators

Here is a list of all the logical operators available in SQL.

Sr.No. Operator & Description

ALL
1
The ALL operator is used to compare a value to all values in another value set.

AND
2 The AND operator allows the existence of multiple conditions in an SQL
statement's WHERE clause.

ANY
3 The ANY operator is used to compare a value to any applicable value in the list as
per the condition.

BETWEEN
4 The BETWEEN operator is used to search for values that are within a set of values,
given the minimum value and the maximum value.

EXISTS
5 The EXISTS operator is used to search for the presence of a row in a specified
table that meets a certain criterion.

IN
6 The IN operator is used to compare a value to a list of literal values that have been
specified.

7 LIKE
6 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

The LIKE operator is used to compare a value to similar values using wildcard
operators.

NOT
The NOT operator reverses the meaning of the logical operator with which it is
8
used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate
operator.

OR
9 The OR operator is used to combine multiple conditions in an SQL statement's
WHERE clause.

IS NULL
10
The NULL operator is used to compare a value with a NULL value.

UNIQUE
11 The UNIQUE operator searches every row of a specified table for uniqueness (no
duplicates).

SQL - CREATE DATABASE

The SQL CREATE DATABASE statement is used to create a new SQL database.

Syntax
The basic syntax of this CREATE DATABASE statement is as follows −

CREATE DATABASE DatabaseName;


Always the database name should be unique within the RDBMS.

Example
If you want to create a new database <testDB>, then the CREATE DATABASE statement would
be as shown below −

SQL> CREATE DATABASE testDB;

Make sure you have the admin privilege before creating any database. Once a database is created,
you can check it in the list of databases as follows −

SQL> SHOW DATABASES;


+--------------------+
| Database |
+--------------------+
| information_schema |
| AMROOD |
| TUTORIALSPOINT |
| mysql |
| orig |
| test |
7 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

SQL - DROP OR DELETE DATABASE

The SQL DROP DATABASE statement is used to drop an existing database in SQL schema.

Syntax
The basic syntax of DROP DATABASE statement is as follows −

DROP DATABASE DatabaseName;


Always the database name should be unique within the RDBMS.

Example
If you want to delete an existing database <testDB>, then the DROP DATABASE statement would
be as shown below −

SQL> DROP DATABASE testDB;

SQL - SELECT DATABASE, USE STATEMENT

When you have multiple databases in your SQL Schema, then before starting your operation, you
would need to select a database where all the operations would be performed.

The SQL USE statement is used to select any existing database in the SQL schema.

Syntax
The basic syntax of the USE statement is as shown below −

USE DatabaseName;
Always the database name should be unique within the RDBMS.

Example
You can check the available databases as shown below −

SQL> SHOW DATABASES;

| Database

| information_schema |

| AMROOD |

| TUTORIALSPOINT |

| mysql |

| orig |

| test |
8 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Now, if you want to work with the AMROOD database, then you can execute the following SQL
command and start working with the AMROOD database.

SQL> USE AMROOD;

SQL - CREATE TABLE

Creating a basic table involves naming the table and defining its columns and each column's data
type.

The SQL CREATE TABLE statement is used to create a new table.

Syntax
The basic syntax of the CREATE TABLE statement is as follows −

CREATE TABLE table_name(


column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
CREATE TABLE is the keyword telling the database system what you want to do. In this case, you
want to create a new table. The unique name or identifier for the table follows the CREATE TABLE
statement.Then in brackets comes the list defining each column in the table and what sort of data
type it is. The syntax becomes clearer with the following example.A copy of an existing table can
be created using a combination of the CREATE TABLE statement and the SELECT statement.

Example
The following code block is an example, which creates a CUSTOMERS table with an ID as a
primary key and NOT NULL are the constraints showing that these fields cannot be NULL while
creating records in this table −

SQL> CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
9 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

SQL - DROP OR DELETE TABLE

The SQL DROP TABLE statement is used to remove a table definition and all the data, indexes,
triggers, constraints and permission specifications for that table.

NOTE − You should be very careful while using this command because once a table is deleted then
all the information available in that table will also be lost forever.

Syntax
The basic syntax of this DROP TABLE statement is as follows −

DROP TABLE table_name;

Example
Let us first verify the CUSTOMERS table and then we will delete it from the database as shown
below −

SQL> DESC CUSTOMERS;

+---------+---------------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |

+---------+---------------+------+-----+---------+-------+

| ID | int(11) | NO | PRI | | |

| NAME | varchar(20) | NO | | | |

| AGE | int(11) | NO | | | |

| ADDRESS | char(25) | YES | | NULL | |

| SALARY | decimal(18,2) | YES | | NULL | |

+---------+---------------+------+-----+---------+-------+

5 rows in set (0.00 sec)

This means that the CUSTOMERS table is available in the database, so let us now drop it as shown
below.

SQL> DROP TABLE CUSTOMERS;

Query OK, 0 rows affected (0.01 sec)


10 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

SQL - INSERT QUERY

The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.

Syntax
There are two basic syntaxes of the INSERT INTO statement which are shown below.

INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)


VALUES (value1, value2, value3,...valueN);
Here, column1, column2, column3,...columnN are the names of the columns in the table into which
you want to insert the data.

Example
The following statements would create six records in the CUSTOMERS table.

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)

VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)

VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)

VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)

VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)

VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)

VALUES (6, 'Komal', 22, 'MP', 4500.00 );

SQL - SELECT QUERY

The SQL SELECT statement is used to fetch the data from a database table which returns this data
in the form of a result table. These result tables are called result-sets.

Syntax
The basic syntax of the SELECT statement is as follows −

SELECT column1, column2, columnN FROM table_name;


11 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Here, column1, column2... are the fields of a table whose values you want to fetch. If you want to
fetch all the fields available in the field, then you can use the following syntax.

SELECT * FROM table_name;

Example
Consider the CUSTOMERS table having the 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 |

+----+----------+-----+-----------+----------+

The following code is an example, which would fetch the ID, Name and Salary fields of the
customers available in CUSTOMERS table.

SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS;

This would produce the following result −

+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 1 | Ramesh | 2000.00 |
| 2 | Khilan | 1500.00 |
| 3 | kaushik | 2000.00 |
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+
If you want to fetch all the fields of the CUSTOMERS table, then you should use the following
query.

SQL> SELECT * FROM CUSTOMERS;


12 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

This would produce the result as shown below.

+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+

DELETE QUERY

The SQL DELETE command is used to delete rows that are no longer required from the database
tables. It deletes the whole row from the table. Delete command comes in handy to delete temporary
or obsolete data from your database.The DELETE command can delete more than one row from a
table in a single query. This proves to be advantages when removing large numbers of rows from a
database table.

Delete command syntax

The basic syntax of the delete command is as shown below.

DELETE FROM table_name [WHERE condition];

HERE

 DELETE FROM `table_name` tells MySQL server to remove rows from the table ..

 [WHERE condition] is optional and is used to put a filter that restricts the number of rows
affected by the DELETE query.

Example:

DELETE FROM movies WHERE movie_id = 18;

Note: Here table name is movies


13 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

UPDATE QUERY

Here may be a requirement where the existing data in a MySQL table needs to be modified. You
can do so by using the SQL UPDATE command. This will modify any field value of any MySQL
table.

Syntax
The following code block has a generic SQL syntax of the UPDATE command to modify the data
in the MySQL table −

UPDATE table_name SET field1 = new-value1, field2 = new-value2


[WHERE Clause]

 You can update one or more field altogether.


 You can specify any condition using the WHERE clause.
 You can update the values in a single table at a time.
The WHERE clause is very useful when you want to update the selected rows in a table.
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
14 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

ALTER TABLE QUERY

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

The ALTER TABLE statement is also used to add and drop various constraints on an existing
table.

1. ALTER TABLE - ADD Column

To add a column in a table, use the following syntax:

ALTER TABLE table_name


ADD column_name datatype;

The following SQL adds an "Email" column to the "Customers" table:

Example
ALTER TABLE Customers
ADD Email varchar(255);

2. ALTER TABLE - ALTER/MODIFY Column

To change the data type of a column in a table, use the following syntax:

ALTER TABLE table_name


ALTER COLUMN column_name datatype;
Or
ALTER TABLE table_name
MODIFY COLUMN column_name datatype;
Or
ALTER TABLE table_name
MODIFY column_name datatype;

Change Data Type Example

Now we want to change the data type of the column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:

ALTER TABLE Persons


ALTER COLUMN DateOfBirth year;
15 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

3. ALTER TABLE -Drop Column

Next, we want to delete the column named "DateOfBirth" in the "Persons" table. We use the
following SQL statement:

Syntax:

ALTER TABLE table_name


DROP COLUMN COLUMNNAME

Example:

ALTER TABLE Persons


DROP COLUMN DateOfBirth;

4. ALTER TABLE -Rename Column In Table

Syntax:

ALTER TABLE table_name CHANGE COLUMN


old_name new_name column_definition

Example:

In this example, we will change the column name "cus_surname" to "cus_title".

Use the following query to do this:

ALTER TABLE cus_tbl CHANGE COLUMN


cus_surname cus_title varchar(20) NOT NULL;

5. RENAME TABLE

Syntax:

ALTER TABLE table_name


RENAME TO new_table_name;

Example:

In this example, the table name cus_tbl is renamed as cus_table.

ALTER TABLE cus_tbl


RENAME TO cus_table;

6. ADD/DROP A CONSTRAINT

Refer : SQL constraints topic


16 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

SQL CONSTRAINTS (Constraint Clause)

SQL constraints are used to specify rules for the data in a table.

Constraints 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 table. If there is any violation between the constraint and the data
action, the action is aborted.Constraints can be column level or table level. Column level
constraints apply to a column, and table level constraints apply to the whole table.

 Constraints are the rules enforced on data columns on a table. 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.

 Constraints can either be column level or table level. Column level constraints are applied
only to one column whereas, table level constraints are applied to the entire table.

Following are some of the most commonly used constraints available in SQL −

 NOT NULL Constraint − Ensures that a column cannot have a NULL value.

 DEFAULT Constraint − Provides a default value for a column when none is specified.

 UNIQUE Constraint − Ensures that all the values in a column are different.

 PRIMARY Key − Uniquely identifies each row/record in a database table.

 FOREIGN Key − Uniquely identifies a row/record in any another 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.

SQL NOT NULL Constraint

By default, a column can hold NULL values.The NOT NULL constraint enforces a column to
NOT accept NULL values.This enforces a field to always contain a value, which means that you
cannot insert a new record, or update a record without adding a value to this field.

Sql Not Null On Create Table

The following SQL ensures that the "ID", "LastName", and "FirstName" columns will NOT accept
NULL values when the "Persons" table is created:
17 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Example
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);

SQL UNIQUE Constraint

The UNIQUE constraint ensures that all values in a column are different.Both the UNIQUE and
PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns.

A PRIMARY KEY constraint automatically has a UNIQUE constraint.However, you can have
many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.

Sql Unique Constraint On Create Table

The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons" table is
created:

MySQL:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
UNIQUE (ID)
);

Oracle

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT UC_Person UNIQUE (ID,LastName)
);

SQL PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record in a table.Primary keys must
contain UNIQUE values, and cannot contain NULL values.A table can have only one primary key,
which may consist of single or multiple fields.
18 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Sql Primary Key On Create Table

The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is
created:

My SQL

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);

Oracle

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);

SQL FOREIGN KEY Constraint

A FOREIGN KEY is a key used to link two tables together. A FOREIGN KEY is a field (or
collection of fields) in one table that refers to the PRIMARY KEY in another table.

The table containing the foreign key is called the child table, and the table containing the candidate
key is called the referenced or parent table.

Look at the following two tables:

"Persons" table:

PersonID LastName FirstName Age

1 Hansen Ola 30

2 Svendson Tove 23

3 Pettersen Kari 20
19 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

"Orders" table:

OrderID OrderNumber PersonID

1 77895 3

2 44678 3

3 22456 2

4 24562 1
Notice that the "PersonID" column in the "Orders" table points to the "PersonID" column in the
"Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
The FOREIGN KEY constraint also prevents 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.
Sql Foreign Key On Create Table
The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders" table
is created:

MySQL:

CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

Oracle:

CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
CONSTRAINT PK_PersonOrder PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID)
);
SQL 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
20 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

a CHECK constraint on a table it can limit the values in certain columns based on values in other
columns in the row.
Sql Check On Create Table
The following SQL creates a CHECK constraint on the "Age" column when the "Persons" table is
created. The CHECK constraint ensures that you can not have any person below 18 years:

MySQL:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);

MS Access:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
);

SQL DEFAULT Constraint

The DEFAULT constraint is used to provide a default value for a column.The default value will be
added to all new records IF no other value is specified.

Sql Default On Create Table

The following SQL sets a DEFAULT value for the "City" column when the "Persons" table is
created:

My SQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);
21 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

ADD/DROP A CONSTRAINT

ADD CONSTRAINT

Constraint can be added to a column in a table using ALTER command

Syntax:

ALTER TABLE table_name


ADD CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ... column_n);

Example
Let's look at an example of how to create a primary key using the ALTER TABLE statement in
Oracle.

ALTER TABLE supplier


ADD CONSTRAINT supplier_pk PRIMARY KEY (supplier_id);

DROP CONSTRAINT

Syntax
The syntax to drop a primary key using the ALTER TABLE statement in Oracle/PLSQL is:

ALTER TABLE table_name


DROP CONSTRAINT constraint_name;

Example
Let's look at an example of how to drop a primary key using the ALTER TABLE statement in
Oracle.

ALTER TABLE supplier


DROP CONSTRAINT supplier_pk;

In this example, we're dropping a primary key on the supplier table called supplier_pk.
22 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

PL/SQL – FUNCTIONS

A function is same as a procedure except that it returns a value. Therefore, all the discussions of
the previous chapter are true for functions too.

Types of SQL Server Functions:

 System Defined Functions(Built in functions)


 User defined function

And in system defined function we have 2 types of functions.

 System Scalar Function


 System Aggregate Function

Scalar Functions:

Which operators on single value and returns single value, below is the list of some scale functions
used in sql server.

Scalar Function Description

round (9.56785) This will round the give number to 3 places of decimal, 9.567

rand (10) This will generate random numbers of 10 characters

upper (‘sql’) This will return upper case of given string, ‘SQL’

lower (‘SQL’) This will return lower case of given string, ‘sql’

abs (-20.75) This will return absolute number of a given number, 20.25

Convert (int, 20.56) This will convert given float value to integer, 20

ltrim (‘ sql’) This will remove the spaces from left hand side, ‘sql’

rtrim (‘sql ‘) This will remove the spaces from right hand side, ‘sql’

Substr () This will extract characters from a text field

ASCII (char_Exp) This will return ASCII code of the given character expression
23 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Aggregate Functions:

Aggregates the values and return a single value, below is the list of some aggregate values in sql
server.

Aggregate Function Description

Min () This will return Minimum value

Max() This will return Maximum value

Avg () This will return Average value

Count () This will return number of counts

Sum () This will return total sum of numeric value

SQL - Numeric Functions

SQL numeric functions are used primarily for numeric manipulation and/or mathematical
calculations. The following table details the numeric functions −

Sr.No. Function & Description

ABS()
1.
Returns the absolute value of numeric expression.

BIT_AND()
2.
Returns the bitwise AND all the bits in expression.

BIT_COUNT()
3.
Returns the string representation of the binary value passed to it.

BIT_OR()
4.
Returns the bitwise OR of all the bits in the passed expression.

COS()
5. Returns the cosine of passed numeric expression. The numeric expression should
be expressed in radians.

DEGREES()
6.
Returns numeric expression converted from radians to degrees.

EXP()
7. Returns the base of the natural logarithm (e) raised to the power of passed numeric
expression.

GREATEST()
8.
Returns the largest value of the input expressions.
24 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

MOD()
9.
Returns the remainder of one expression by diving by another expression.

OCT()
10. Returns the string representation of the octal value of the passed numeric
expression. Returns NULL if passed value is NULL.

PI()
11.
Returns the value of pi

POW()
12.
Returns the value of one expression raised to the power of another expression

POWER()
13.
Returns the value of one expression raised to the power of another expression

RADIANS()
14.
Returns the value of passed expression converted from degrees to radians.

ROUND()
15. Returns numeric expression rounded to an integer. Can be used to round an
expression to a number of decimal points

SIN()
16.
Returns the sine of numeric expression given in radians.

SQRT()
17.
Returns the non-negative square root of numeric expression.

STD()
18.
Returns the standard deviation of the numeric expression.

STDDEV()
19.
Returns the standard deviation of the numeric expression.

TAN()
20.
Returns the tangent of numeric expression expressed in radians.

TRUNCATE()
21. Returns numeric exp1 truncated to exp2 decimal places. If exp2 is 0, then the result
will have no decimal point.

SQL String functions


String functions are used to perform an operation on input string and return an output string.
Following are the string functions defined in SQL:

1. ASCII(): This function is used to find the ASCII value of a character.

Syntax: SELECT ascii('t');

Output: 116
25 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

2. CHAR_LENGTH(): This function is used to find the length of a word.

Syntax: SELECT char_length('Hello!');

Output: 6

3. CHARACTER_LENGTH(): This function is used to find the length of a line.

Syntax: SELECT CHARACTER_LENGTH('geeks for geeks');

Output: 15

4. CONCAT(): This function is used to add two words or strings.

Syntax: SELECT 'Geeks' || ' ' || 'forGeeks' FROM dual;

Output: ‘GeeksforGeeks’

5. INSERT(): This function is used to insert the data into a database.

Syntax: INSERT INTO database (geek_id, geek_name) VALUES (5000, 'abc');

Output: successfully updated

6. LCASE(): This function is used to convert the given string into lower case.

Syntax: LCASE ("GeeksFor Geeks To Learn");

Output: geeksforgeeks to learn

7. LEFT(): This function is used to SELECT a sub string from the left of given size or
characters.

Syntax: SELECT LEFT('geeksforgeeks.org', 5);

Output: geeks

8. LENGTH(): This function is used to find the length of a word.

Syntax: LENGTH('GeeksForGeeks');

Output: 13

9. LOWER(): This function is used to convert the upper case string into lower case.

Syntax: SELECT LOWER('GEEKSFORGEEKS.ORG');

Output: geeksforgeeks.org

10. LTRIM(): This function is used to cut the given sub string from the original string.

Syntax: LTRIM('123123geeks', '123');

Output: geeks
26 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

11. MID(): This function is to find a word from the given position and of the given size.

Syntax: Mid ("geeksforgeeks", 6, 2);

Output: for

12. REPLACE(): This function is used to cut the given string by removing the given sub string.

Syntax: REPLACE('123geeks123', '123');

Output: geeks

13. REVERSE(): This function is used to reverse a string.

Syntax: SELECT REVERSE('geeksforgeeks.org');

Output: ‘gro.skeegrofskeeg’

14. RIGHT(): This function is used to SELECT a sub string from the right end of the given size.

Syntax: SELECT RIGHT('geeksforgeeks.org', 4);

Output: ‘.org’

15. RTRIM(): This function is used to cut the given sub string from the original string.

Syntax: RTRIM('geeksxyxzyyy', 'xyz');

Output: ‘geeks’

16. STRCMP(): This function is used to compare 2 strings.

 If string1 and string2 are the same, the STRCMP function will return 0.

 If string1 is smaller than string2, the STRCMP function will return -1.

 If string1 is larger than string2, the STRCMP function will return 1.

Syntax: SELECT STRCMP('google.com', 'geeksforgeeks.com');

Output: -1

17. TRIM(): This function is used to cut the given symbol from the string.

Syntax: TRIM(LEADING '0' FROM '000123');

Output: 123

18. UCASE(): This function is used to make the string in upper case.

Syntax: UCASE ("GeeksForGeeks");

Output: GEEKSFORGEEKS
27 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

SQL Date functions


In SQL, dates are complicated for newbies, since while working with database, the format of the
date in table must be matched with the input date in order to insert. In various scenarios instead of
date, datetime (time is also involved with date) is used.
In MySql the default date functions are:

 NOW(): Returns the current date and time. Example:

SELECT NOW();
Output:
2017-01-13 08:03:52
 CURDATE(): Returns the current date. Example:

SELECT CURDATE();
Output:
2017-01-13
 CURTIME(): Returns the current time. Example:

SELECT CURTIME();
Output:
08:05:15
 DATE(): Extracts the date part of a date or date/time expression. Example:
For the below table named ‘Test’

Id Name BirthTime

4120 Pratik 1996-09-26 16:44:15.581

SELECT Name, DATE(BirthTime) AS BirthDate FROM Test;


Output:

Name BirthDate

Pratik 1996-09-26

 EXTRACT (): Returns a single part of a date/time. Syntax:


EXTRACT (unit FORM date);

There are several units that can be considered but only some are used such as:
MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER,
YEAR, etc.
28 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

And ‘date’ is a valid date expression.

Example:
For the below table named ‘Test’

Id Name BirthTime

4120 Pratik 1996-09-26 16:44:15.581


Queries
SELECT Name, Extract(DAY FROM BirthTime) AS BirthDay FROM Test;
Output:

Name BirthDay

Pratik 26

SELECT Name, Extract(YEAR FROM BirthTime) AS BirthYear FROM Test;


Output:

Name BirthYear

Pratik 1996

SELECT Name, Extract(SECOND FROM BirthTime) AS BirthSecond FROM Test;


Output:

Name BirthSecond

Pratik 581

 DATE_ADD() : Adds a specified time interval to a date


Syntax:
DATE_ADD(date, INTERVAL expr type);
Where, date – valid date expression and expr is the number of interval we want to add.
and type can be one of the following:
MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER,
YEAR, etc.
29 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Example:
For the below table named ‘Test’

Id Name BirthTime

4120 Pratik 1996-09-26 16:44:15.581


Queries

SELECT Name, DATE_ADD(BirthTime, INTERVAL 1 YEAR) AS BirthTimeModified


FROM Test;
Output:

Name BirthTimeModified

Pratik 1997-09-26 16:44:15.581

SELECT Name, DATE_ADD(BirthTime, INTERVAL 30 DAY) AS


BirthDayModified FROM Test;
Output:

Name BirthDayModified

Pratik 1996-10-26 16:44:15.581

SELECT Name, DATE_ADD(BirthTime, INTERVAL 4 HOUR) AS


BirthHourModified FROM Test;
Output:

Name BirthSecond

Pratik 1996-10-26 20:44:15.581

 DATE_SUB(): Subtracts a specified time interval from a date. Syntax for DATE_SUB is
same as DATE_ADD just the difference is that DATE_SUB is used to subtract a given
interval of date.
30 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

CREATING A FUNCTION

A standalone function is created using the CREATE FUNCTION statement. The simplified
syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −

CREATE [OR REPLACE] FUNCTION function_name


[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];

Where,

 function-name specifies the name of the function.

 [OR REPLACE] option allows the modification of an existing function.

 The optional parameter list contains name, mode and types of the parameters. IN represents
the value that will be passed from outside and OUT represents the parameter that will be
used to return a value outside of the procedure.

 The function must contain a return statement.

 The RETURN clause specifies the data type you are going to return from the function.

 function-body contains the executable part.

 The AS keyword is used instead of the IS keyword for creating a standalone function.

Example
The following example illustrates how to create and call a standalone function. This function returns
the total number of CUSTOMERS in the customers table.We will use the CUSTOMERS table,
which we had created in the PL/SQL Variables chapter −

Select * from customers;


+----+----------+-----+-----------+----------+
| 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 |
31 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+

CREATE OR REPLACE FUNCTION totalCustomers

RETURN number IS

total number(2) := 0;

BEGIN

SELECT count(*) into total

FROM customers;

RETURN total;

END;

When the above code is executed using the SQL prompt, it will produce the following result −

Function created.

CALLING A FUNCTION (Function Call)


While creating a function, you give a definition of what the function has to do. To use a function,
you will have to call that function to perform the defined task. When a program calls a function,
the program control is transferred to the called function.A called function performs the defined task
and when its return statement is executed or when the last end statement is reached, it returns the
program control back to the main program.To call a function, you simply need to pass the required
parameters along with the function name and if the function returns a value, then you can store the
returned value. Following program calls the function totalCustomers from an anonymous block −

DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
/

When the above code is executed at the SQL prompt, it produces the following result −
32 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Total no. of Customers: 6

PL/SQL procedure successfully completed.

Example
The following example demonstrates Declaring, Defining, and Invoking a Simple PL/SQL
Function that computes and returns the maximum of two values.

DECLARE
a number;
b number;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
BEGIN
a:= 23;
b:= 45;
c := findMax(a, b);
dbms_output.put_line(' Maximum of (23,45): ' || c);
END;
/

When the above code is executed at the SQL prompt, it produces the following result −

Maximum of (23,45): 45

PL/SQL procedure successfully completed.


33 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

PL/SQL RECURSIVE FUNCTIONS


We have seen that a program or subprogram may call another subprogram. When a subprogram
calls itself, it is referred to as a recursive call and the process is known as recursion.

The following program calculates the factorial of a given number by calling itself recursively −

DECLARE

num number;

factorial number;

FUNCTION fact(x number)

RETURN number IS

f number;

BEGIN

IF x=0 THEN

f := 1;

ELSE

f := x * fact(x-1);

END IF;

RETURN f;

END;

BEGIN

num:= 6;

factorial := fact(num);

dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);

END;

When the above code is executed at the SQL prompt, it produces the following result −

Factorial 6 is 720

PL/SQL procedure successfully completed.


34 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

SQL SET OPERATION

Set operators are used to join the results of two (or more) SELECT statements.The SET operators
available in Oracle 11g are UNION,UNION ALL,INTERSECT,and MINUS.

Types of Set Operation


1. Union
2. UnionAll
3. Intersect
4. Minus

1. Union
 The SQL Union operation is used to combine the result of two or more SQL SELECT
queries.
 In the union operation, all the number of datatype and columns must be same in both the
tables on which UNION operation is being applied.
 The union operation eliminates the duplicate rows from its resultset.

Syntax
SELECT column_name FROM table1
UNION
SELECT column_name FROM table2;

Example:

The First table

ID NAME

1 Jack

2 Harry

3 Jackson

The Second table

ID NAME

3 Jackson

4 Stephan

5 David
35 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Union SQL query will be:

SELECT * FROM First UNION SELECT * FROM Second;

The result set table will look like:

ID NAME

1 Jack

2 Harry

3 Jackson

4 Stephan

5 David

2. Union All
Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.

Syntax:
SELECT column_name FROM table1 UNION ALL SELECT column_name FROM table2;

Example:

Using the above First and Second table. Union All query will be like:

SELECT * FROM First UNION ALL SELECT * FROM Second;

The resultset table will look like:

ID NAME

1 Jack

2 Harry

3 Jackson

3 Jackson

4 Stephan

5 David
36 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

3. Intersect
 It is used to combine two SELECT statements. The Intersect operation returns the common
rows from both the SELECT statements.
 In the Intersect operation, the number of datatype and columns must be the same.
 It has no duplicates and it arranges the data in ascending order by default.

Syntax:

SELECT column_name FROM table1 INTERSECT SELECT column_name FROM table2;

Example: Using the above First and Second table.Intersect query will be:

SELECT * FROM First INTERSECT SELECT * FROM Second;

The resultset table will look like:

ID NAME

3 Jackson

4. Minus
 It combines the result of two SELECT statements. Minus operator is used to display the

rows which are present in the first query but absent in the second query.
 It has no duplicates and data arranged in ascending order by default.

Syntax:

SELECT column_name FROM table1 MINUS SELECT column_name FROM table2;

Example

Using the above First and Second table.Minus query will be:

SELECT * FROM First MINUS SELECT * FROM Second;

The resultset table will look like:

ID NAME

1 Jack

2 Harry
37 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

SQL - SUBQUERY OR INNER QUERY OR A NESTED QUERY

A Subquery or Inner query or a Nested query is a query within another SQL query and embedded
within the WHERE clause.

A subquery is used to return data that will be used in the main query as a condition to further restrict
the data to be retrieved.Subqueries can be used with the SELECT, INSERT, UPDATE, and
DELETE statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.

There are a few rules that subqueries must follow −

 Subqueries must be enclosed within parentheses.

 A subquery can have only one column in the SELECT clause, unless multiple columns are
in the main query for the subquery to compare its selected columns.

 An ORDER BY command cannot be used in a subquery, although the main query can use
an ORDER BY. The GROUP BY command can be used to perform the same function as
the ORDER BY in a subquery.

 Subqueries that return more than one row can only be used with multiple value operators
such as the IN operator.

 The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY,
CLOB, or NCLOB.

 A subquery cannot be immediately enclosed in a set function.

 The BETWEEN operator cannot be used with a subquery. However, the BETWEEN
operator can be used within the subquery.

Subqueries with the SELECT Statement

Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows –

SELECT column_name [, column_name ]


FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])
38 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Example
Consider the CUSTOMERS table having the following records −

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | 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, let us check the following subquery with a SELECT statement.

SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;

This would produce the following result.

+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+

Subqueries with the INSERT Statement

Subqueries also can be used with INSERT statements. The INSERT statement uses the data
returned from the subquery to insert into another table. The selected data in the subquery can be
modified with any of the character, date or number functions.
39 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

The basic syntax is as follows.

INSERT INTO table_name [ (column1 [, column2 ]) ]

SELECT [ *|column1 [, column2 ]

FROM table1 [, table2 ]

[ WHERE VALUE OPERATOR ]

Example
Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Now to copy
the complete CUSTOMERS table into the CUSTOMERS_BKP table, you can use the following
syntax.

SQL> INSERT INTO CUSTOMERS_BKP


SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS) ;

Subqueries with the UPDATE Statement


The subquery can be used in conjunction with the UPDATE statement. Either single or multiple
columns in a table can be updated when using a subquery with the UPDATE statement.

The basic syntax is as follows.

UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]

Example
Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table.
The following example updates SALARY by 0.25 times in the CUSTOMERS table for all the
customers whose AGE is greater than or equal to 27.
40 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

SQL> UPDATE CUSTOMERS

SET SALARY = SALARY * 0.25

WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP

WHERE AGE >= 27 );

This would impact two rows and finally CUSTOMERS table would have the following records.

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 125.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 2125.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Subqueries with the DELETE Statement


The subquery can be used in conjunction with the DELETE statement like with any other statements
mentioned above.

The basic syntax is as follows.

DELETE FROM TABLE_NAME


[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]

Example
Assuming, we have a CUSTOMERS_BKP table available which is a backup of the CUSTOMERS
table. The following example deletes the records from the CUSTOMERS table for all the customers
whose AGE is greater than or equal to 27.

SQL> DELETE FROM CUSTOMERS

WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP

WHERE AGE >= 27 );

This would impact two rows and finally the CUSTOMERS table would have the following records.
41 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+

CLAUSES IN SQL

SQL Server provides with the following clauses that can be used in the SELECT statements:
1. WHERE
2. GROUP BY
3. HAVING
4. ORDER BY
5. WHERE
SQL - WHERE Clause
The SQL WHERE clause is used to specify a condition while fetching the data from a single table
or by joining with multiple tables. If the given condition is satisfied, then only it returns a specific
value from the table. You should use the WHERE clause to filter the records and fetching only the
necessary records.

The WHERE clause is not only used in the SELECT statement, but it is also used in the UPDATE,
DELETE statement, etc., which we would examine in the subsequent chapters.

Syntax
The basic syntax of the SELECT statement with the WHERE clause is as shown below.

SELECT column1, column2, columnN


FROM table_name
WHERE [condition]

You can specify a condition using the comparison or logical operators like >, <, =, LIKE, NOT,
etc. The following examples would make this concept clear.
42 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Example
Consider the CUSTOMERS table having the 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 |
+----+----------+-----+-----------+----------+

The following code is an example which would fetch the ID, Name and Salary fields from the
CUSTOMERS table, where the salary is greater than 2000 −

SQL> SELECT ID, NAME, SALARY

FROM CUSTOMERS

WHERE SALARY > 2000;

This would produce the following result −

+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+

SQL - Group By

The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange
identical data into groups. This GROUP BY clause follows the WHERE clause in a SELECT
statement and precedes the ORDER BY clause.

Syntax
The basic syntax of a GROUP BY clause is shown in the following code block. The GROUP BY
clause must follow the conditions in the WHERE clause and must precede the ORDER BY clause
if one is used.
43 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

SELECT column1, column2


FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2

Example
Consider the CUSTOMERS table is having the 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 |
+----+----------+-----+-----------+----------+

If you want to know the total amount of the salary on each customer, then the GROUP BY query
would be as follows.

SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS

GROUP BY NAME;

This would produce the following result −

+----------+-------------+
| NAME | SUM(SALARY) |
+----------+-------------+
| Chaitali | 6500.00 |
| Hardik | 8500.00 |
| kaushik | 2000.00 |
| Khilan | 1500.00 |
| Komal | 4500.00 |
| Muffy | 10000.00 |
| Ramesh | 2000.00 |
+----------+-------------+
44 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Now, let us look at a table where the CUSTOMERS table has the following records with duplicate
names −

+----+----------+-----+-----------+----------+

| ID | NAME | AGE | ADDRESS | SALARY |

+----+----------+-----+-----------+----------+

| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |

| 2 | Ramesh | 25 | Delhi | 1500.00 |

| 3 | kaushik | 23 | Kota | 2000.00 |

| 4 | kaushik | 25 | Mumbai | 6500.00 |

| 5 | Hardik | 27 | Bhopal | 8500.00 |

| 6 | Komal | 22 | MP | 4500.00 |

| 7 | Muffy | 24 | Indore | 10000.00 |

+----+----------+-----+-----------+----------+

Now again, if you want to know the total amount of salary on each customer, then the GROUP BY
query would be as follows −

SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS

GROUP BY NAME;

This would produce the following result −

+---------+-------------+
| NAME | SUM(SALARY) |
+---------+-------------+
| Hardik | 8500.00 |
| kaushik | 8500.00 |
| Komal | 4500.00 |
| Muffy | 10000.00 |
| Ramesh | 3500.00 |
+---------+-------------+
45 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

SQL - Having Clause


The HAVING Clause enables you to specify conditions that filter which group results appear in
the results.

The WHERE clause places conditions on the selected columns, whereas the HAVING clause places
conditions on groups created by the GROUP BY clause.

Syntax
The HAVING clause must follow the GROUP BY clause in a query and must also precede the
ORDER BY clause if used. The following code block has the syntax of the SELECT statement
including the HAVING clause −

SELECT column1, column2


FROM table1, table2
WHERE [ conditions ]
GROUP BY column1, column2
HAVING [ conditions ]
ORDER BY column1, column2

Example
Consider the CUSTOMERS table having the 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 an example, which would display a record for a similar age count that would be more
than or equal to 2.

SQL > SELECT ID, NAME, AGE, ADDRESS, SALARY

FROM CUSTOMERS

GROUP BY age

HAVING COUNT(age) >= 2;


46 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

This would produce the following result −

+----+--------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+--------+-----+---------+---------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
+----+--------+-----+---------+---------+

SQL - ORDER BY Clause

The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on
one or more columns. Some databases sort the query results in an ascending order by default.

Syntax
The basic syntax of the ORDER BY clause is as follows −

SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];

You can use more than one column in the ORDER BY clause. Make sure whatever column you are
using to sort that column should be in the column-list.

Example
Consider the CUSTOMERS table having the 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 |
+----+----------+-----+-----------+----------+
47 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

The following code block has an example, which would sort the result in an ascending order by the
NAME and the SALARY −

SQL> SELECT * FROM CUSTOMERS

ORDER BY NAME, SALARY;

This would produce the following result −

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

The following code block has an example, which would sort the result in the descending order by
NAME.

SQL> SELECT * FROM CUSTOMERS ORDER BY NAME DESC;

This would produce the following result −

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
+----+----------+-----+-----------+----------+
48 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

SQL – JOINS

The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN
is a means for combining fields from two tables by using values common to each.

Consider the following two tables −

Table 1 − CUSTOMERS Table

+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+

Table 2 − ORDERS Table

+-----+---------------------+-------------+--------+

|OID | DATE | CUSTOMER_ID | AMOUNT |

+-----+---------------------+-------------+--------+

| 102 | 2009-10-08 00:00:00 | 3 | 3000 |

| 100 | 2009-10-08 00:00:00 | 3 | 1500 |

| 101 | 2009-11-20 00:00:00 | 2 | 1560 |

| 103 | 2008-05-20 00:00:00 | 4 | 2060 |

+-----+---------------------+-------------+--------+

Now, let us join these two tables in our SELECT statement as shown below.

SQL> SELECT ID, NAME, AGE, AMOUNT

FROM CUSTOMERS, ORDERS

WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID;


49 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

This would produce the following result.

+----+----------+-----+--------+
| ID | NAME | AGE | AMOUNT |
+----+----------+-----+--------+
| 3 | kaushik | 23 | 3000 |
| 3 | kaushik | 23 | 1500 |
| 2 | Khilan | 25 | 1560 |
| 4 | Chaitali | 25 | 2060 |
+----+----------+-----+--------+
Here, it is noticeable that the join is performed in the WHERE clause. Several operators can be used
to join tables, such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can all be used to
join tables. However, the most common operator is the equal to symbol.
There are different types of joins available in SQL −
 INNER JOIN − returns rows when there is a match in both tables.
 LEFT JOIN − returns all rows from the left table, even if there are no matches in the right
table.
 RIGHT JOIN − returns all rows from the right table, even if there are no matches in the left
table.
 FULL JOIN − returns rows when there is a match in one of the tables.
 SELF JOIN − is used to join a table to itself as if the table were two tables, temporarily
renaming at least one table in the SQL statement.
 CARTESIAN JOIN − returns the Cartesian product of the sets of records from the two or
more joined tables.

Let us now discuss each of these joins in detail.


50 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

SQL - INNER JOINS

The most important and frequently used of the joins is the INNER JOIN. They are also referred to
as an EQUIJOIN.

The INNER JOIN creates a new result table by combining column values of two tables (table1 and
table2) based upon the join-predicate. The query compares each row of table1 with each row of
table2 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.

Syntax
The basic syntax of the INNER JOIN is as follows.

SELECT table1.column1, table2.column2...


FROM table1
INNER JOIN table2
ON table1.common_field = table2.common_field;

Example
Consider the following two tables.

Table 1 − CUSTOMERS Table is as follows.

+----+----------+-----+-----------+----------+

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

+----+----------+-----+-----------+----------+
51 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Table 2 − ORDERS Table is as follows.

+-----+---------------------+-------------+--------+

| OID | DATE | CUSTOMER_ID | AMOUNT |

+-----+---------------------+-------------+--------+

| 102 | 2009-10-08 00:00:00 | 3 | 3000 |

| 100 | 2009-10-08 00:00:00 | 3 | 1500 |

| 101 | 2009-11-20 00:00:00 | 2 | 1560 |

| 103 | 2008-05-20 00:00:00 | 4 | 2060 |

+-----+---------------------+-------------+--------+

Now, let us join these two tables using the INNER JOIN as follows −

SQL> SELECT ID, NAME, AMOUNT, DATE

FROM CUSTOMERS

INNER JOIN ORDERS

ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

This would produce the following result.

+----+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+----+----------+--------+---------------------+
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
+----+----------+--------+---------------------+

SQL - LEFT JOINS

The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right
table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still
return a row in the result, but with NULL in each column from the right table.

This means that a left join returns all the values from the left table, plus matched values from the
right table or NULL in case of no matching join predicate.
52 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Syntax
The basic syntax of a LEFT JOIN is as follows.

SELECT table1.column1, table2.column2...


FROM table1
LEFT JOIN table2
ON table1.common_field = table2.common_field;

Here, the given condition could be any given expression based on your requirement.

Example
Consider the following two tables,

Table 1 − CUSTOMERS Table is as follows.

+----+----------+-----+-----------+----------+

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

+----+----------+-----+-----------+----------+

Table 2 − Orders Table is as follows.

+-----+---------------------+-------------+--------+
| OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
53 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Now, let us join these two tables using the LEFT JOIN as follows.

SQL> SELECT ID, NAME, AMOUNT, DATE

FROM CUSTOMERS

LEFT JOIN ORDERS

ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

This would produce the following result −

+----+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+----+----------+--------+---------------------+
| 1 | Ramesh | NULL | NULL |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | NULL | NULL |
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
+----+----------+--------+---------------------+

SQL - RIGHT JOINS

The SQL RIGHT JOIN returns all rows from the right table, even if there are no matches in the
left table. This means that if the ON clause matches 0 (zero) records in the left table; the join will
still return a row in the result, but with NULL in each column from the left table.
This means that a right join returns all the values from the right table, plus matched values from the
left table or NULL in case of no matching join predicate.
Syntax
The basic syntax of a RIGHT JOIN is as follow.

SELECT table1.column1, table2.column2...


FROM table1
RIGHT JOIN table2
ON table1.common_field = table2.common_field;
54 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Example
Consider the following two tables,

Table 1 − CUSTOMERS Table is as follows.

+----+----------+-----+-----------+----------+

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

+----+----------+-----+-----------+----------+

Table 2 − ORDERS Table is as follows.

+-----+---------------------+-------------+--------+

|OID | DATE | CUSTOMER_ID | AMOUNT |

+-----+---------------------+-------------+--------+

| 102 | 2009-10-08 00:00:00 | 3 | 3000 |

| 100 | 2009-10-08 00:00:00 | 3 | 1500 |

| 101 | 2009-11-20 00:00:00 | 2 | 1560 |

| 103 | 2008-05-20 00:00:00 | 4 | 2060 |

+-----+---------------------+-------------+--------+

Now, let us join these two tables using the RIGHT JOIN as follows.

SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS

RIGHT JOIN ORDERS

ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
55 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

This would produce the following result −

+------+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+------+----------+--------+---------------------+
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
+------+----------+--------+---------------------+

SQL - FULL JOINS

The SQL FULL JOIN combines the results of both left and right outer joins.
The joined table will contain all records from both the tables and fill in NULLs for missing matches
on either side.
Syntax
The basic syntax of a FULL JOIN is as follows −

SELECT table1.column1, table2.column2...


FROM table1
FULL JOIN table2
ON table1.common_field = table2.common_field;
Here, the given condition could be any given expression based on your requirement.
Example
Consider the following two tables.
Table 1 − CUSTOMERS Table is as follows.

+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
56 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Table 2 − ORDERS Table is as follows.

+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+

Now, let us join these two tables using FULL JOIN as follows.

SQL> SELECT ID, NAME, AMOUNT, DATE

FROM CUSTOMERS

FULL JOIN ORDERS

ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

This would produce the following result −

+------+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+------+----------+--------+---------------------+
| 1 | Ramesh | NULL | NULL |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | NULL | NULL |
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
+------+----------+--------+---------------------+
57 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

If your Database does not support FULL JOIN (MySQL does not support FULL JOIN), then you
can use UNION ALL clause to combine these two JOINS as shown below.

SQL> SELECT ID, NAME, AMOUNT, DATE


FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
UNION ALL
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID

SQL - SELF JOINS

The SQL SELF JOIN is used to join a table to itself as if the table were two tables; temporarily
renaming at least one table in the SQL statement.

Syntax
The basic syntax of SELF JOIN is as follows −

SELECT a.column_name, b.column_name... FROM table1 a, table1 b


WHERE a.common_field = b.common_field;

Here, the WHERE clause could be any given expression based on your requirement.

Example
Consider the following table.

CUSTOMERS Table is as follows.

+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
58 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Now, let us join this table using SELF JOIN as follows −

SQL> SELECT a.ID, b.NAME, a.SALARY

FROM CUSTOMERS a, CUSTOMERS b

WHERE a.SALARY < b.SALARY;

This would produce the following result −

+----+----------+---------+
| ID | NAME | SALARY |
+----+----------+---------+
| 2 | Ramesh | 1500.00 |
| 2 | kaushik | 1500.00 |
| 1 | Chaitali | 2000.00 |
| 2 | Chaitali | 1500.00 |
| 3 | Chaitali | 2000.00 |
| 6 | Chaitali | 4500.00 |
| 1 | Hardik | 2000.00 |
| 2 | Hardik | 1500.00 |
| 3 | Hardik | 2000.00 |
| 4 | Hardik | 6500.00 |
| 6 | Hardik | 4500.00 |
| 1 | Komal | 2000.00 |
| 2 | Komal | 1500.00 |
| 3 | Komal | 2000.00 |
| 1 | Muffy | 2000.00 |
| 2 | Muffy | 1500.00 |
| 3 | Muffy | 2000.00 |
| 4 | Muffy | 6500.00 |
| 5 | Muffy | 8500.00 |
| 6 | Muffy | 4500.00 |
+----+----------+---------+

SQL - CARTESIAN or CROSS JOINS

The CARTESIAN JOIN or CROSS JOIN returns the Cartesian product of the sets of records from
two or more joined tables. Thus, it equates to an inner join where the join-condition always
evaluates to either True or where the join-condition is absent from the statement.

Syntax
The basic syntax of the CARTESIAN JOIN or the CROSS JOIN is as follows −
59 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

SELECT table1.column1, table2.column2...


FROM table1, table2 [, table3 ]

Example
Consider the following two tables.

Table 1 − CUSTOMERS table is as follows.

+----+----------+-----+-----------+----------+

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

+----+----------+-----+-----------+----------+

Table 2: ORDERS Table is as follows −

+-----+---------------------+-------------+--------+

|OID | DATE | CUSTOMER_ID | AMOUNT |

+-----+---------------------+-------------+--------+

| 102 | 2009-10-08 00:00:00 | 3 | 3000 |

| 100 | 2009-10-08 00:00:00 | 3 | 1500 |

| 101 | 2009-11-20 00:00:00 | 2 | 1560 |

| 103 | 2008-05-20 00:00:00 | 4 | 2060 |

+-----+---------------------+-------------+--------+

Now, let us join these two tables using CARTESIAN JOIN as follows −

SQL> SELECT ID, NAME, AMOUNT, DATE

FROM CUSTOMERS, ORDERS;


60 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

This would produce the following result −

+----+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+----+----------+--------+---------------------+
| 1 | Ramesh | 3000 | 2009-10-08 00:00:00 |
| 1 | Ramesh | 1500 | 2009-10-08 00:00:00 |
| 1 | Ramesh | 1560 | 2009-11-20 00:00:00 |
| 1 | Ramesh | 2060 | 2008-05-20 00:00:00 |
| 2 | Khilan | 3000 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 2 | Khilan | 2060 | 2008-05-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 2060 | 2008-05-20 00:00:00 |
| 4 | Chaitali | 3000 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | 3000 | 2009-10-08 00:00:00 |
| 5 | Hardik | 1500 | 2009-10-08 00:00:00 |
| 5 | Hardik | 1560 | 2009-11-20 00:00:00 |
| 5 | Hardik | 2060 | 2008-05-20 00:00:00 |
| 6 | Komal | 3000 | 2009-10-08 00:00:00 |
| 6 | Komal | 1500 | 2009-10-08 00:00:00 |
| 6 | Komal | 1560 | 2009-11-20 00:00:00 |
| 6 | Komal | 2060 | 2008-05-20 00:00:00 |
| 7 | Muffy | 3000 | 2009-10-08 00:00:00 |
| 7 | Muffy | 1500 | 2009-10-08 00:00:00 |
| 7 | Muffy | 1560 | 2009-11-20 00:00:00 |
| 7 | Muffy | 2060 | 2008-05-20 00:00:00 |
+----+----------+--------+---------------------+

SQL | EXISTS ANY AND ALL OPERATORS

The EXISTS condition in SQL is used to check whether the result of a correlated nested query is
empty (contains no tuples) or not. The result of EXISTS is a boolean value True or False. It can be
used in a SELECT, UPDATE, INSERT or DELETE statement.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name(s)
FROM table_name
WHERE condition);
Examples:
61 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Consider the following two relation “Customers” and “Orders”.

Queries

Using EXISTS condition with SELECT statement


To fetch the first and last name of the customers who placed atleast one order.

SELECT fname, lname


FROM Customers
WHERE EXISTS (SELECT *
FROM Orders
WHERE Customers.customer_id = Orders.c_id);
Output:
62 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Using NOT with EXISTS


Fetch last and first name of the customers who has not placed any order.
SELECT lname, fname
FROM Customer
WHERE NOT EXISTS (SELECT *
FROM Orders
WHERE Customers.customer_id = Orders.c_id);
Output:

Using EXISTS condition with DELETE statement

Delete the record of all the customer from Order Table whose last name is ‘Mehra’.
DELETE
FROM Orders
WHERE EXISTS (SELECT *
FROM customers
WHERE Customers.customer_id = Orders.cid
AND Customers.lname = 'Mehra');
SELECT * FROM Orders;

Output:

Using EXISTS condition with UPDATE statement

Update the lname as ‘Kumari’ of customer in Customer Table whose customer_id is 401.
UPDATE Customers
SET lname = 'Kumari'
WHERE EXISTS (SELECT *
FROM Customers
WHERE customer_id = 401);
SELECT * FROM Customers;
63 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Output:

SQL ALL AND ANY


ALL & ANY are logical operators in SQL. They return boolean value as a result.
ALL operator is used to select all tuples of SELECT STATEMENT. It is also used to compare a
value to every value in another value set or result from a subquery.
 The ALL operator returns TRUE iff all of the subqueries values meet the condition. The ALL
must be preceded by comparison operators and evaluates true if all of the subqueries values
meet the condition.
 ALL is used with SELECT, WHERE, HAVING statement.

ALL with SELECT Statement:

Syntax:
SELECT ALL field_name
FROM table_name
WHERE condition(s);

ALL with WHERE or HAVING Statement:

Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name comparison_operator ALL
(SELECT column_name
FROM table_name
WHERE condition(s));
64 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Example:

Consider the following Products Table and OrderDetails Table,


Products Table

OrderDetails Table

Queries

Find the name of the all the product.

SELECT ALL ProductName


FROM Products
WHERE TRUE;
Output:
65 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Find the name of the product if all the records in the OrderDetails has Quantity either
equal to 6 or 2.

SELECT ProductName
FROM Products
WHERE ProductID = ALL (SELECT ProductId
FROM OrderDetails
WHERE Quantity = 6 OR Quantity = 2);
Output:

Find the OrderID whose maximum Quantity among all product of that OrderID is greater
than average quantity of all OrderID.

SELECT OrderID
FROM OrderDetails
GROUP BY OrderID
HAVING max(Quantity) > ALL (SELECT avg(Quantity)
FROM OrderDetails
GROUP BY OrderID);
Output:

ANY

ANY compares a value to each value in a list or results from a query and evaluates to true if the
result of an inner query contains at least one row.
 ANY return true if any of the subqueries values meet the condition.
 ANY must be preceded by comparison operators.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name comparison_operator ANY
(SELECT column_name
FROM table_name
WHERE condition(s));
66 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Queries
Find the Distinct CategoryID of the products which have any record in OrderDetails Table.
SELECT DISTINCT CategoryID
FROM Products
WHERE ProductID = ANY (SELECT ProductID
FROM OrderDetails);
Output:

Finds any records in the OrderDetails table that Quantity = 9.


SELECT ProductName
FROM Products
WHERE ProductID = ANY (SELECT ProductID
FROM OrderDetails
WHERE Quantity = 9);
67 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

SQL VIEWS

Views in SQL are kind of virtual tables. A view also has rows and columns as they are in a real
table in the database. We can create a view by selecting fields from one or more tables present in
the database. A View can either have all the rows of a table or specific rows based on certain
condition.

In this article we will learn about creating , deleting and updating Views.
Sample Tables:
StudentDetails

StudentMarks

CREATING VIEWS

We can create View using CREATE VIEW statement. A View can be created from a single table
or multiple tables.
Syntax:

CREATE VIEW view_name AS


SELECT column1, column2.....
FROM table_name
WHERE condition;

view_name: Name for the View


table_name: Name of the table
condition: Condition to select rows
68 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

Examples:
 Creating View from a single table:
In this example we will create a View named DetailsView from the table StudentDetails.
Query:
CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM StudentDetails
WHERE S_ID < 5;
To see the data in the View, we can query the view in the same manner as we query a table.
SELECT * FROM DetailsView;
Output:

In this example, we will create a view named StudentNames from the table StudentDetails.
Query:
CREATE VIEW StudentNames AS
SELECT S_ID, NAME
FROM StudentDetails
ORDER BY NAME;
If we now query the view as,
SELECT * FROM StudentNames;
Output:

 Creating View from multiple tables:

In this example we will create a View named MarksView from two tables StudentDetails and
StudentMarks. To create a View from multiple tables we can simply include multiple tables in the
SELECT statement. Query:
69 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

CREATE VIEW MarksView AS


SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
To display data of View MarksView:
SELECT * FROM MarksView;
Output:

DELETING VIEWS

We have learned about creating a View, but what if a created View is not needed any more?
Obviously we will want to delete it. SQL allows us to delete an existing View. We can delete or
drop a View using the DROP statement.

Syntax:

DROP VIEW view_name;

view_name: Name of the View which we want to delete.

For example, if we want to delete the View MarksView, we can do this as:

DROP VIEW MarksView;

UPDATING VIEWS

There are certain conditions needed to be satisfied to update a view. If any one of these conditions
is not met, then we will not be allowed to update the view.
1. The SELECT statement which is used to create the view should not include GROUP BY
clause or ORDER BY clause.
2. The SELECT statement should not have the DISTINCT keyword.
3. The View should have all NOT NULL values.
4. The view should not be created using nested queries or complex queries.
5. The view should be created from a single table. If the view is created using multiple tables
then we will not be allowed to update the view.
70 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

We can use the CREATE OR REPLACE VIEW statement to add or remove fields from a
view.
Syntax:

CREATE OR REPLACE VIEW view_name AS


SELECT column1,coulmn2,..
FROM table_name
WHERE condition;
For example, if we want to update the view MarksView and add the field AGE to this View
from StudentMarks Table, we can do this as:
CREATE OR REPLACE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS,
StudentMarks.AGE
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
If we fetch all the data from MarksView now as:
SELECT * FROM MarksView;
Output:

 Inserting a row in a view:

We can insert a row in a View in a same way as we do in a table. We can use the INSERT
INTO statement of SQL to insert a row in a View.Syntax:

INSERT view_name(column1, column2 , column3,..)


VALUES(value1, value2, value3..);

view_name: Name of the View

Example:

In the below example we will insert a new row in the View DetailsView which we have
created above in the example of “creating views from a single table”.
71 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

INSERT INTO DetailsView(NAME, ADDRESS) VALUES("Suresh","Gurgaon");


If we fetch all the data from DetailsView now as,
SELECT * FROM DetailsView;
Output:

 Deleting a row from a View:

Deleting rows from a view is also as simple as deleting rows from a table. We can use the
DELETE statement of SQL to delete rows from a view. Also deleting a row from a view first
delete the row from the actual table and the change is then reflected in the view.Syntax:
DELETE FROM view_name
WHERE condition;

view_name:Name of view from where we want to delete rows


condition: Condition to select rows

Example:
In this example we will delete the last row from the view DetailsView which we just added
in the above example of inserting rows.
DELETE FROM DetailsView WHERE NAME="Suresh";
If we fetch all the data from DetailsView now as,

SELECT * FROM DetailsView;

Output:
72 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)

USING VIEW WITH CHECK OPTION

The WITH CHECK OPTION clause in SQL is a very useful clause for views. It is applicable to a
updatable view. If the view is not updatable, then there is no meaning of including this clause in
the CREATE VIEW statement.

 The WITH CHECK OPTION clause is used to prevent the insertion of rows in the view
where the condition in the WHERE clause in CREATE VIEW statement is not satisfied.
 If we have used the WITH CHECK OPTION clause in the CREATE VIEW statement, and if
the UPDATE or INSERT clause does not satisfy the conditions then they will return an error.
Example:
In the below example we are creating a View SampleView from StudentDetails Table with WITH
CHECK OPTION clause.
CREATE VIEW SampleView AS
SELECT S_ID, NAME
FROM StudentDetails WHERE NAME IS NOT NULL
WITH CHECK OPTION;
In this View if we now try to insert a new row with null value in the NAME column then it will
give an error because the view is created with the condition for NAME column as NOT NULL.
For example,though the View is updatable but then also the below query for this View is not valid:

INSERT INTO SampleView(S_ID) VALUES(6);

Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards

You might also like