Unit Iv
Unit Iv
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 −
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.
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)
GRANT
1
Gives a privilege to user.
REVOKE
2
Takes back privileges granted from user.
DATA INTEGRITY
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 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 −
tinyint 0 255
3 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)
bit 0 1
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
Assume 'variable a' holds 10 and 'variable b' holds 20, then −
Assume 'variable a' holds 10 and 'variable b' holds 20, then −
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.
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).
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 −
Example
If you want to create a new database <testDB>, then the CREATE DATABASE statement would
be as shown below −
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 −
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 −
Example
If you want to delete an existing database <testDB>, then the DROP DATABASE statement would
be as shown below −
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 −
| 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.
Creating a basic table involves naming the table and defining its columns and each column's data
type.
Syntax
The basic syntax of the CREATE TABLE statement is as follows −
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 −
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 −
Example
Let us first verify the CUSTOMERS table and then we will delete it from the database as shown
below −
+---------+---------------+------+-----+---------+-------+
+---------+---------------+------+-----+---------+-------+
| ID | int(11) | NO | PRI | | |
| NAME | varchar(20) | NO | | | |
| AGE | int(11) | NO | | | |
+---------+---------------+------+-----+---------+-------+
This means that the CUSTOMERS table is available in the database, so let us now drop it as shown
below.
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.
Example
The following statements would create six records in the CUSTOMERS table.
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 −
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.
Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following code is an example, which would fetch the ID, Name and Salary fields of the
customers available in CUSTOMERS table.
+----+----------+----------+
| 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.
+----+----------+-----+-----------+----------+
| 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.
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:
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 −
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.
Example
ALTER TABLE Customers
ADD Email varchar(255);
To change the data type of a column in a table, use the following syntax:
Now we want to change the data type of the column named "DateOfBirth" in the "Persons" table.
Next, we want to delete the column named "DateOfBirth" in the "Persons" table. We use the
following SQL statement:
Syntax:
Example:
Syntax:
Example:
5. RENAME TABLE
Syntax:
Example:
6. ADD/DROP A CONSTRAINT
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.
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.
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.
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
);
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.
The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons" table is
created:
MySQL:
Oracle
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)
The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is
created:
My SQL
Oracle
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.
"Persons" table:
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:
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:
Oracle:
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:
MS Access:
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.
The following SQL sets a DEFAULT value for the "City" column when the "Persons" table is
created:
ADD/DROP A CONSTRAINT
ADD CONSTRAINT
Syntax:
Example
Let's look at an example of how to create a primary key using the ALTER TABLE statement in
Oracle.
DROP CONSTRAINT
Syntax
The syntax to drop a primary key using the ALTER TABLE statement in Oracle/PLSQL is:
Example
Let's look at an example of how to drop a primary key using the ALTER TABLE statement in
Oracle.
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.
Scalar Functions:
Which operators on single value and returns single value, below is the list of some scale functions
used in sql server.
round (9.56785) This will round the give number to 3 places of decimal, 9.567
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’
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.
SQL numeric functions are used primarily for numeric manipulation and/or mathematical
calculations. The following table details the numeric functions −
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.
Output: 116
25 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)
Output: 6
Output: 15
Output: ‘GeeksforGeeks’
6. LCASE(): This function is used to convert the given string into lower case.
7. LEFT(): This function is used to SELECT a sub string from the left of given size or
characters.
Output: geeks
Syntax: LENGTH('GeeksForGeeks');
Output: 13
9. LOWER(): This function is used to convert the upper case string into lower case.
Output: geeksforgeeks.org
10. LTRIM(): This function is used to cut the given sub string from the original string.
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.
Output: for
12. REPLACE(): This function is used to cut the given string by removing the given sub string.
Output: geeks
Output: ‘gro.skeegrofskeeg’
14. RIGHT(): This function is used to SELECT a sub string from the right end of the given size.
Output: ‘.org’
15. RTRIM(): This function is used to cut the given sub string from the original string.
Output: ‘geeks’
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.
Output: -1
17. TRIM(): This function is used to cut the given symbol from the string.
Output: 123
18. UCASE(): This function is used to make the string in upper case.
Output: GEEKSFORGEEKS
27 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)
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
Name BirthDate
Pratik 1996-09-26
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)
Example:
For the below table named ‘Test’
Id Name BirthTime
Name BirthDay
Pratik 26
Name BirthYear
Pratik 1996
Name BirthSecond
Pratik 581
Example:
For the below table named ‘Test’
Id Name BirthTime
Name BirthTimeModified
Name BirthDayModified
Name BirthSecond
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 −
Where,
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 RETURN clause specifies the data type you are going to return from the function.
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 −
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
RETURN number IS
total number(2) := 0;
BEGIN
FROM customers;
RETURN total;
END;
When the above code is executed using the SQL prompt, it will produce the following result −
Function created.
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)
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
The following program calculates the factorial of a given number by calling itself recursively −
DECLARE
num number;
factorial 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);
END;
When the above code is executed at the SQL prompt, it produces the following result −
Factorial 6 is 720
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.
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:
ID NAME
1 Jack
2 Harry
3 Jackson
ID NAME
3 Jackson
4 Stephan
5 David
35 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)
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:
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:
Example: Using the above First and Second table.Intersect query will be:
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:
Example
Using the above First and Second table.Minus query will be:
ID NAME
1 Jack
2 Harry
37 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)
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.
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.
The BETWEEN operator cannot be used with a subquery. However, the BETWEEN
operator can be used within the subquery.
Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows –
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 |
+----+----------+-----+-----------+----------+
SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
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)
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.
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)
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 |
+----+----------+-----+-----------+----------+
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.
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.
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 −
FROM CUSTOMERS
+----+----------+----------+
| 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)
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.
GROUP BY NAME;
+----------+-------------+
| 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 −
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
| 6 | Komal | 22 | MP | 4500.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 −
GROUP BY NAME;
+---------+-------------+
| 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)
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 −
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.
FROM CUSTOMERS
GROUP BY age
+----+--------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+--------+-----+---------+---------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
+----+--------+-----+---------+---------+
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 −
+----+----------+-----+-----------+----------+
| 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.
+----+----------+-----+-----------+----------+
| 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.
+----+----------+-----+-----------+----------+
| 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, let us join these two tables in our SELECT statement as shown below.
+----+----------+-----+--------+
| 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.
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.
Example
Consider the following two tables.
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
51 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)
+-----+---------------------+-------------+--------+
+-----+---------------------+-------------+--------+
+-----+---------------------+-------------+--------+
Now, let us join these two tables using the INNER JOIN as follows −
FROM CUSTOMERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
+----+----------+--------+---------------------+
| 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 |
+----+----------+--------+---------------------+
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.
Here, the given condition could be any given expression based on your requirement.
Example
Consider the following two tables,
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
+-----+---------------------+-------------+--------+
| 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.
FROM CUSTOMERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
+----+----------+--------+---------------------+
| 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 |
+----+----------+--------+---------------------+
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.
Example
Consider the following two tables,
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
+-----+---------------------+-------------+--------+
+-----+---------------------+-------------+--------+
+-----+---------------------+-------------+--------+
Now, let us join these two tables using the RIGHT JOIN as follows.
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
55 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)
+------+----------+--------+---------------------+
| 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 |
+------+----------+--------+---------------------+
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 −
+----+----------+-----+-----------+----------+
| 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)
+-----+---------------------+-------------+--------+
|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.
FROM CUSTOMERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
+------+----------+--------+---------------------+
| 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.
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 −
Here, the WHERE clause could be any given expression based on your requirement.
Example
Consider the following 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 |
+----+----------+-----+-----------+----------+
58 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)
+----+----------+---------+
| 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 |
+----+----------+---------+
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)
Example
Consider the following two tables.
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
+-----+---------------------+-------------+--------+
+-----+---------------------+-------------+--------+
+-----+---------------------+-------------+--------+
Now, let us join these two tables using CARTESIAN JOIN as follows −
+----+----------+--------+---------------------+
| 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 |
+----+----------+--------+---------------------+
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)
Queries
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:
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:
Syntax:
SELECT ALL field_name
FROM table_name
WHERE condition(s);
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:
OrderDetails Table
Queries
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:
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:
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:
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)
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:
For example, if we want to delete the View MarksView, we can do this as:
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:
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:
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)
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;
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,
Output:
72 Yuvakshetra Institute Of Management Studies (YIMS) DBMS NOTES Bsc.CS (2017-Onwards)
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: