UNIT4
UNIT4
SQL
SYLLABUS o SQL (pronounced as “ess-cue-ell”), commonly
SQL Concepts: expanded as Structured Query Language, is a
o Basics of SQL, DDL, DML, DCL, computer language designed for the retrieval
o Tables and management of data in relational database
Create management system, database schema creation
Modify and modification.
Delete table structures, o The most popular relational database
Rename and Drop tables management systems today are Oracle,
o Defining constraints – MySQL, Microsoft SQL server, Postgre SQL
Primary key and IBM DB2.
foreign key o The SQL commands can be divided into three
unique main sublanguages:
not null Data Definition Language
check Data Manipulation Language
o IN operator Data Control Language
Select Command
Logical Operators o Data Definition Language:
Functions The SQL DDL provides commands for
o aggregate functions defining relation schemas, deleting relations,
o Built-in functions and modifying relations schemas.
Numeric DDL or Data Definition Language actually
Date consists of the SQL commands that can be
string functions used to define the database schema.
set operations These commands will primarily be used by
sub-queries database administrators during the setup and
o correlated sub-queries removal phases of a database project.
Use of group by, having, order by, Examples of DDL commands:
join and its types
CREATE – is used to create the database
Exist, Any, All.
or its objects (like table, index, function,
View - Creation, Renaming the column of a
views, store procedure and triggers).
view, destroys view.
DROP – is used to delete objects from
the database.
ALTER-is used to alter the structure of
the database.
TRUNCATE–is used to remove all
records from a table, including all spaces
allocated for the records are removed
GEMS: [email protected]
The CREATE statement
o Data Manipulation language(DML): o The CREATE statement in SQL creates an
The Data manipulation Language is used to objects inside of a RDBMS.
retrieve, insert and modify database o CREATE statement can be used to make a new
information. database, table, or stored query.
These commands will be used by all o There are two CREATE statements available in
database users during the routine operation SQL:
of the database CREATE DATABASE
o Examples of DML commands CREATE TABLE
SELECT – is used to retrieve data from the
o CREATE DATABASE
database.
The CREATE DATABASE statement is
INSERT – is used to add rows to an
used to create a new database in SQL.
existing table.
Syntax
UPDATE – is used to modify the values of
a set of existing table rows.
DELETE – is used to delete records from a
database table.
o Data Control Language
DCL handles the authorization aspects of
Example
data and permits the user to control who has
access to see or manipulate data within the
database.
o CREATE TABLE
Its two main keywords are:
The CREATE TABLE statement is used to
GRANT authorizes one or more users to
create a table in SQL. We know that a table
perform an operation or a set of comprises of rows and columns. So while
operations on an object. creating tables we have to provide all the
REVOKE removes or restricts the information to SQL about the names of the
capability of a user to perform an columns, type of data to be stored in columns,
operation or a set of operations. size of the data etc.
Syntax:
Example:
GEMS: [email protected]
INSERT INTO
DROP o The SQL INSERT INTO Statement is used
o The DROP DATABASE statement is used to add new rows of data to a table in the
to drop an existing SQL database. database.
Syntax o It is possible to write the INSERT INTO
statement in two ways
Syntax:
Example
Example
TRUNCATE TABLE s4bca;
OR
GEMS: [email protected]
o To drop a column from the table.
ALTER ALTER command can also be used to drop or
o ALTER command is used for altering the table remove columns.
structure, such as, Syntax:
to add a column to existing table
to rename any existing column ALTER TABLE table_name
to change datatype of any column or to DROP COLUMN col_name;
modify its size.
to drop a column from the table. Example
o To add to add a column to existing table
ALTER TABLE s4bca
Using ALTER command we can add a DROP COLUMN mark;
column to any existing table.
Syntax:
UPDATE
o The UPDATE statement is used to modify
Example: the existing records in a table.
o Syntax
Example
DELETE
ALTER TABLE s4bca o The DELETE statement is used to delete
RENAME COLUMN no TO id; existing records in a table.
o Syntax
Example
GEMS: [email protected]
SQL CONSTRAINTS
o Constraints are the rules enforced on the data
columns of a table. These are used to limit the PRIMARY KEY: A primary key is a field
which can uniquely identify each row in a
type of data that can go into a table.
table. And this constraint is used to specify a
o Following are some of the most commonly field in a table as primary key.
used constraints available in SQL.
o Syntax: Example
Example:
Example
GEMS: [email protected]
SELECT COMMAND LOGICAL OPERATORS
o There are three Logical Operators namely,
o The SELECT statement is used to retrieve data AND
from a database. OR
o Syntax NOT.
o These operators compare two conditions at a
time to determine whether a row can be
selected for the output.
o When retrieving data using a SELECT
statement, you can use logical operators in the
The select clause is used to list the WHERE clause, which allows you to combine
attributes desired in the result of a query. more than one condition.
The from clause is a list of the relations o OR
(tables) to be accessed in the evaluation of It is used to select rows that satisfy at least
the query. one of the given conditions.
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.
<attribute list> is a list of attribute names
whose values are to be retrieved by the
query.
<table list> is a list of the relation names
required to process the query.
<condition> is a conditional (Boolean)
expression that identifies the tuples to be
retrieved by the query.
o The WHERE clause can use the comparison
operators such as =, !=, <, >, <=,and >=, as o AND
well as the BETWEEN and LIKE operators. It is used to select rows that must satisfy all
o Example: the given conditions.
Example
o NOT
It is used to find rows that do not satisfy a
condition.
NOT results in the reverse of a condition.
That is, if a condition is satisfied, then the
row is not returned.
GEMS: [email protected]
IN OPERATOR AGGREGATE FUNCTIONS
o IN operator allows us to easily test if the
expression matches any value in the list of o An aggregate function allows you to perform a
values. calculation on a set of values to return a single
o It is used to remove the need of multiple OR scalar value.
condition in SELECT, INSERT, UPDATE or
o DELETE. o The following are the most commonly used
o You can also use NOT IN to exclude the rows SQL aggregate functions:
in your list. AVG –
o Syntax calculates the average of a set of values.
Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
o Example
COUNT
counts rows in a specified table or view.
Syntax
SELECT COUNT(column_name)
FROM table_name
or WHERE condition;
MIN
gets the minimum value in a set of
values.
Syntax
o SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX
gets the maximum value in a set of
values.
Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
SUM
calculates the sum of values.
Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
GEMS: [email protected]
NUMERIC FUNCTONS SET OPERATIONS
o Set operators are used to join the results of two
(or more) SELECT statements.
o the SET operators available in Oracle 11g are
UNION
UNION ALL
INTERSECT
MINUS
o UNION
UNION is used to combine the results of
two or more SELECT statements.
However it will eliminate duplicate rows
from its resultset.
In case of union, number of columns and
datatype must be same in both the tables,
on which UNION operation is being
applied.
EXAMPLE
DATE FUNCTIONS
o UNION ALL
This operation is similar to Union. But it also
shows the duplicate rows.
Example
GEMS: [email protected]
o INTERSECT STRING FUNCTIONS
Intersect operation is used to combine two o SQL string functions are used primarily for
SELECT statements, but it only retuns the string manipulation.
records which are common from both
o The following are the important string
SELECT statements.
In case of Intersect the number of columns functions
and datatype must be same ASCII():
Example This function is used to find the ASCII
value of a character.
Syntax: SELECT ascii('t');
Output: 116
LENGTH():
This function is used to find the length of
a word.
o MINUS Syntax: LENGTH('GeeksForGeeks');
The Minus operation combines results of Output: 13
two SELECT statements and return only
those in the final result, which belongs to STRCMP():
the first set of the result. This function is used to compare 2
Example 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
UCASE():
This function is used to make the string in
upper case.
Syntax:
UCASE ("GeeksForGeeks");
Output:
GEEKSFORGEEKS
LCASE():
This function is used to convert the given
string into lower case.
Syntax:
LCASE ("GeeksFor Geeks To Learn");
Output:
geeksforgeeks to learn
INSTR():
This function is used to find the
occurrence of an alphabet.
Syntax:
INSTR('geeks for geeks', 'e');
Output:
2 (the first occurrence of „e‟)
GEMS: [email protected]
LENGTH(): SUBQUERY
This function is used to find the length of o A MySQL subquery is a query nested within
a word. another query.
Syntax: o Subqueries can be used with the SELECT,
LENGTH('GeeksForGeeks'); INSERT, UPDATE, and DELETE statements
Output: 13 along with the operators like =, <, >, >=, <=,
IN, BETWEEN, etc.
REPEAT(): o There are a few rules that subqueries must
This function is used to write the given follow:
string again and again till the number of Subqueries must be enclosed within
times mentioned. parentheses.
Syntax: A subquery can have only one column in
SELECT REPEAT('geeks', 2); the SELECT clause, unless multiple
Output: columns are in the main query for the
geeksgeeks
subquery to compare its selected columns.
Subqueries that return more than one row
can only be used with multiple value
REVERSE(): operators such as the IN operator.
This function is used to reverse a string.
Syntax:
SELECT REVERSE('geeksforgeeks.org');
Output:
„gro.skeegrofskeeg‟
o Example:
GEMS: [email protected]
Correlated Subquery ORDER BY
o A correlated subquery is a subquery that o The ORDER BY statement in sql is used to sort
contains a reference to a table (in the parent the fetched data in either ascending or
descending according to one or more columns.
query) that also appears in the outer query.
o By default ORDER BY sorts the data in
o Correlated subqueries are used for row-by- ascending order.
row processing. Each subquery is executed o We can use the keyword DESC to sort the data
once for every row of the outer query. in descending order and the keyword ASC to
o A correlated subquery is one way of reading sort in ascending order.
every row in a table and comparing values o Syntax
in each row against related data. It is used
whenever a subquery must return a different
result or set of results for each candidate
row considered by the main query. o Example
o You can also use the ANY and ALL
operator in a correlated subquery.
Difference between nested Subquery and
Correlated Subquery
o With a normal nested subquery, the inner
SELECT query runs first and executes
once, returning values to be used by the
main query. A correlated subquery,
however, executes once for each candidate
row considered by the outer query. In other
words, the inner query is driven by the outer
query.
GROUP BY
o The GROUP BY Statement in SQL is used to
arrange identical data into groups with the help
of some functions. i.e if a particular column has
same values in different rows then it will
arrange these rows in a group.
o Syntax:
o Example
GEMS: [email protected]
HAVING CLAUSE EXIST
o The HAVING Clause enables you to specify o The EXISTS operator is used to test for the
conditions that filter which group results existence of any record in a subquery.
appear in the results. o EXISTS returns true if the subquery returns
one or more records.
o The WHERE clause places conditions on the
o EXISTS is commonly used with correlated
selected columns, whereas the HAVING clause subqueries.
o places conditions on groups created by the o Syntax:
GROUP BY clause.
o The HAVING clause was added to SQL
because the WHERE keyword could not be
used with aggregate functions.
o Syntax:
o Example
cus
o Example
ord
GEMS: [email protected]
ANY / ALL Any
o ANY and ALL keywords are used with a SELECT * FROM employee WHERE Age >
WHERE or HAVING clause. ANY( SELECT Age FROM employee
o ANY and ALL operate on subqueries that WHERE Salary > 5000)
return multiple values.
o ANY returns true if any of the subquery values
meet the condition.
o ALL returns true if all of the subquery values
meet the condition.
o Syntax
Any
The sub-query returns 23, 27 i.e, These are the
ages for which salary is greater than 5000.
Then main query is compared with this, if any
of the ages in table is greater than any of the
values of sub-query(i.e the ages in table
should be either greater than 23 or 27) . Now
it returns (A, 25, 2000) (B, 33, 4000) (D, 27,
6000) (E, 24, 4150).
All
All
SELECT * FROM employee WHERE Age >
ALL( SELECT Age FROM employee
WHERE Salary > 5000)
GEMS: [email protected]
JOIN OPERATIONS AND ITS TYPES o Equi Join
o Join is a combination of a Cartesian product It is a Theta join using the equality
followed by selection process. operators.
o It is used to combine related tuples from two
o Natural join
relations into single tuple.
It is an equi join on attribute that has same
o It is denoted by ⋈ name in each relation.
o Join operation can be divided into two:
Inner join
Theta Join
Equi Join
o Outer Join
Natural Join The results will contain all tuple from one or
Outer join both the relations.
Left outer join Notice that much of the data is lost when
Right outer join applying a join to two relation. In some
Full outer join cases this lost data might hold useful
information. An outer join retains the
o Inner Join
information that would have been lost from
Outcomes of the results contain only the the tables, replacing missing data with nulls.
matching tuple. Outer join can be categorized into three
Inner join can be categorized into three: Left outer join
Theta Join Right outer join
Equi Join Full outer join
Natural Join o Left outer join
Keep data from left hand side table.
o Theta Join
Denoted by ⟕
Theta join combines tuples from different o Right outer join
relations provided, they satisfy theta Keep data from right hand side table
condition. Denoted by ⟖
Theta join can use all kinds of comparison o Full outer join
operators. Keep data from both tables
Denoted by ⟗
GEMS: [email protected]
JOIN AND ITS TYPES 2. LEFT JOIN
o The SQL Joins clause is used to combine It return all records from the left table, and
records from two or more tables in a database. the matched records from the right table.
o A JOIN is a means for combining fields from
two tables by using values common to each.
o There are different types of joins available in
SQL:
Example
3. RIGHT JOIN
It return all records from the right table, and
the matched records from the left table.
Example
1. INNER JOIN
It returns rows when there is a match in both
tables.
4. FULL JOIN
It return all records when there is a match in
either left or right table.
Example
Example
GEMS: [email protected]
VIEW
o Views in SQL are kind of virtual tables.
o A view also has rows and columns as they are
in a real table in the database.
o We can create a view by selecting fields from
one or more tables present in the database.
o A View can either have all the rows of a table
or specific rows based on certain condition.
CREATION
o SYNTAX
o Example
create view emp as
select name,age
from employee
where salary >5000;
DROP A VIEW
o Syntax
o Example
DROP VIEW emp
GEMS: [email protected]