Bca320 Dbms SQL Unit-3
Bca320 Dbms SQL Unit-3
Topics Covered:
• History of SQL.
• SQL Operators.
• SQL Expressions.
• SQL Constraints.
• Complex Queries.
• VIEWS.
• Modification of Database.
• Transaction Commands.
• JOIN Expressions.
• Authorization Commands.
History of SQL:
• Early 1970’s ---- IBM , which is called as IBM Sequel XRM language.
• SQL is the standard language for Relational Database System. All the Relational Database Management
Systems (RDBMS) like MySQL, MS Access, Oracle, Sybase, Informix, Postgres and SQL Server use SQL as
their standard database language.
• Why SQL?
SQL is widely popular because it offers the following advantages −
1. Allows users to access data in the relational database management systems.
2. Allows users to describe the data.
3. Allows users to define the data in a database and manipulate that data.
4. Allows to embed within other languages using SQL modules, libraries & pre-compilers.
5. Allows users to create and drop databases and tables.
6. Allows users to create view, stored procedure, functions in a database.
7. Allows users to set permissions on tables, procedures and views.
SQL Process/Architecture:
NOTE :
A classic query
engine handles
all the non-SQL
queries, but a
SQL query
engine won't
handle logical
files.
SQL Types:
• 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 , like:
1. DDL-Data Definition Language: CREATE, ALTER, DROP, RENAME, TRUNCATE, COMMENT.
2.DML- Data Manipulation Language: SELECT, INSERT, UPDATE, DELETE, MERGE, CALL, LOCK
1. Numeric :
- Integer/Int. - Small Int. - Floating Int ( Float/Real , Double Precision) - Bit( 0 or 1)
2. Character String :
- Fixed Length ( Char).
- Variable Length ( VarChar) ) Characters will be varied).
- Literal String. ( Which are placed Between Single Quotation Marks ).
- Concatenation String : ‘abc’ || ‘xyz’
3. Bit String :
- Fixed ( Bit(n)).
- Variable ( Bit Varying(n)).
SQL Data Types Continued …..
4. BOOLEAN : TRUE, FALSE, UNKNOWN (NULL).
NOTE: 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.
Checks if the values of two operands are equal or not, if yes then condition
= becomes true. (a = b) is not true.
Checks if the values of two operands are equal or not, if values are not equal
!= then condition becomes true. (a != b) is true.
Checks if the values of two operands are equal or not, if values are not equal
<> then condition becomes true. (a <> b) is true.
Checks if the value of left operand is greater than the value of right operand,
> if yes then condition becomes true. (a > b) is not true.
Checks if the value of left operand is less than the value of right operand, if
< yes then condition becomes true. (a < b) is true.
Checks if the value of left operand is greater than or equal to the value of
>= right operand, if yes then condition becomes true. (a >= b) is not true.
Checks if the value of left operand is less than or equal to the value of right
<= operand, if yes then condition becomes true. (a <= b) is true.
Checks if the value of left operand is not less than the value of right operand,
!< if yes then condition becomes true. (a !< b) is false.
Checks if the value of left operand is not greater than the value of right
!> operand, if yes then condition becomes true. (a !> b) is true.
3.Logical Operators:
No. Operator & Description
ALL The ALL operator is used to compare a value to all values in another value set.
1
AND The AND operator allows the existence of multiple conditions in an SQL statement's WHERE clause.
2
ANY The ANY operator is used to compare a value to any applicable value in the list as per the condition.
3
BETWEEN The BETWEEN operator is used to search for values that are within a set of values, given the minimum value and the maximum value.
4
EXISTS The EXISTS operator is used to search for the presence of a row in a specified table that meets a certain criterion.
5
6 IN The IN operator is used to compare a value to a list of literal values that have been specified.
7 LIKE 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 used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc.
This is a negate operator.
8
OR The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause.
9
IS NULL The NULL operator is used to compare a value with a NULL value.
10
11 UNIQUE The UNIQUE operator searches every row of a specified table for uniqueness (no duplicates).
SQL Expressions:
EXPRESSION is a combination of one or more values, operators and SQL functions that evaluate to a value.
NOTE: These SQL EXPRESSIONs are like formulae and they are written in query language .
There are different types of SQL expressions, which are mentioned below −
• Boolean : SQL Boolean Expressions fetch the data based on matching a single value.
• Numeric : These expressions are used to perform any mathematical operation in any query.
• Date : Date Expressions return current system date and time values.
• NOTE: 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.
Data Integrity Constraints:
Attributes
FROM r1,r2,……...,rn
Relations
WHERE P ---------- Predicate/Condition.
used Comparison
<,>,<=,>=,=,#) Operator along with
Boolean operator's)
7. SELECT loan-no
from loan
Where amount BETWEEN 9000 and 10000; ( Here I have used Between key word )
{OR}
SELECT loan-no
from loan
Where amount <= 9000 and amount >= 10000;
8. SELECT cust-name, borrower, loan-no as loan-id, amount
from borrower, loan (Used to RENAME )
where borrower.loan-no = loan.loan-no ; ( & we can also write query using as,)
SELECT Cust-name, T.loan-no, S.amount
from borrower as T.laon-no as S
where T.loan-no = S.loan-no ;
9. String Operations : LIKE --- Keyword, % ----- Symbhol.
Variations :
‘xyz%’ – ( Matches any beginning with ‘xyz’ )
‘%xyz’ – ( Matches any string containing ‘xyz’ as a sub string )
‘%xyz%’ – ( Both )
“ || “ – ( Concatenation to join two strings )
“viceversa” – ( Used to convert Uppercase to Lowercase and ViceVersa )
10. Ordered By Clause:
SELECT distinct customer-name
from borrower, loan
where borrower.loan-no = loan.loan-no and branch-name = ‘xyz’
Ordered by customer-name;
{OR}
ii. (SELECT customer-name From depositor) UNION ALL (SELECT customer-name From borrower);
iii. (SELECT customer-name From depositor) INTERSECTION (SELECT customer-name From borrower);
iv. (SELECT customer-name From depositor) INTERSECTION ALL (SELECT customer-name From borrower);
vi. (SELECT customer-name From depositor) EXCEPT ALL (SELECT customer-name From borrower);
12. Aggregate Functions : MIN, MAX , AVG , SUM , COUNT
Examples :
- SELECT Avg(balance)
from account
Where branch-name = ‘xyz’;
13. Group By Clause:
SELECT branch-name, Avg(balance)
from account
group by branch-name ;
clause.
• A sub query is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.
• Sub queries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <,
• Syntax :
SELECT column_name [, column_name ]
Main Query FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
Sub Query FROM table1 [, table2 ]
[WHERE])
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.
• The BETWEEN operator cannot be used with a subquery. However, the BETWEEN operator can be used within
the subquery.
Set Membership Function's:
• Giving membership to access tuples in a table/relation is known as set membership.
• To perform this function , we use TWO keywords : IN and NOT IN
(SQL Connectives)
Example : SELECT distinct customer-name
From borrower
Where customer-name IN/NOT IN ( SELECT customer-name from Depositor);
[ OR ]
SELECT S.name
From Sailors S
Where S.sid NOT IN (SELECT R.sid
From Reserves R
Where R.bid IN (SELECT B.bid
From Boats B
Where B.color = ‘red’));
Set Comparison Function's:{ Correlated Nested Queries}
• The ANY/SOME and ALL operators are used with a WHERE or HAVING clause.
• The ANY/SOME operator returns true if any of the subquery values meet the condition.
• The ALL operator returns true if all of the subquery values meet the condition
Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
( <ANY/SOME, >ANY/SOME,………. & <ALL, >ALL………. ) can be used in optional Cases.
Examples:
SELECT S.sid
FROM Sailors S
WHERE S.rating > ANY ( SELECT S2.rating
FROM Sailors S2
WHERE S2.sname = “xyz’);
[OR]
SELECT S.sid
FROM Sailors S
WHERE S.rating >= ALL ( SELECT S2.rating
FROM Sailors S2);
Test for EMPTY Relations:{ Correlated Nested Queries}
• We use TWO Keywords here, EXISTS and NOT EXISTS along with WHERE clause.
• For EXISTS : Each selected row be such that the subquery following EXISTS
does return something, i.e., the subquery doesnot return a NULL result.
( Argument subquery is not empty)
• For NOT EXISTS : Each selected row be such that the subquery following
NOT EXISTS does not return anything, i.e., the subquery returns a NULL
result. ( Argument subquery is empty )
Examples:
• SELECT Fname, Lname
From player
WHERE EXISTS ( SELECT *
From bating
WHERE playerID = PID
AND matchID = ‘1111’) ;
• SELECT PID As PlayerID
From batting b1
WHERE NOT EXISTS ( SELECT *
From Batting b2
WHERE b1.PID = b2.PID
AND Nruns < 31 ) ;
Test for the Absence of Duplicate Tuples : { Correlated Nested Queries }
• Here we Use TWO Keywords : UNIQUE & NOT UNIQUE
SQL Constructs
• UNIQUE : Argument sub query contains NO TUPLES.
• NOT UNIQUE : Argument sub query contains TUPLES.
Examples :
SELECT FirstName, LastName
FROM CUSTOMER
WHERE UNIQUE (SELECT CustomerID
FROM SALES
WHERE SALES.CustomerID = CUSTOMER.CustomerID);
NOTE : For NOT UNIQUE, We use SELECT DISTINCT at the first query.
Complex Queries:
• The WITH Clause: The SQL WITH clause allows you to give a sub-query block a name (a process also
called sub-query refactoring), which can be referenced in several places within the main SQL query.
• The clause is used for defining a temporary relation such that the output of this temporary relation is available and
is used by the query that is associated with the WITH clause.
• Queries that have an associated WITH clause can also be written using nested sub-queries but doing so add more
complexity to read/debug the SQL query.
• WITH clause is not supported by all database system.
• The name assigned to the sub-query is treated as though it was an inline view or table
• The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database.
• Example: WITH temporaryTable (averageValue) as
(SELECT avg(Attr1)
FROM Table),
SELECT Attr1
FROM Table
WHERE Table.Attr1 > temporaryTable.averageValue;
NOTE: In complex queries, we are unable to see the data storage and attributes all. Hence to overcome this
drawback , they introduced VIEWS.
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.
• A view is nothing more than a SQL statement that is stored in the database with an associated name and is
actually a composition of a table in the form of a predefined SQL query.
• Views, which are a type of virtual tables allow users to do the following −
- Structure data in a way that users or classes of users find natural or intuitive.
- Restrict access to the data in such a way that a user can see and (sometimes) modify exactly
- Summarize data from various tables which can be used to generate reports.
Creating VIEWS:
• Database views are created using the CREATE VIEW statement. Views can be created from a single table,
multiple tables or another view.
• To create a view, a user must have the appropriate system privilege according to the specific implementation.
• The basic CREATE VIEW syntax is as follows −
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];
Example:
CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age
FROM CUSTOMERS;
• You can include multiple tables in your SELECT statement in a similar way as you use them in a normal SQL
SELECT query.
WITH CHECK option in VIEWS:
• The purpose of the WITH CHECK OPTION is to ensure that all UPDATE and INSERTs satisfy the condition(s) in the
view definition.
• If they do not satisfy the condition(s), the UPDATE or INSERT returns an error.
• The following code block has an example of creating same view CUSTOMERS_VIEW with the WITH CHECK OPTION:
Syntax: CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age
FROM CUSTOMERS
WHERE age IS NOT NULL
WITH CHECK OPTION;
NOTE: The WITH CHECK OPTION in this case should deny the entry of any NULL values in the view's AGE column,
because the view is defined by data that does not have a NULL value in the AGE column.
How to UPDATE a VIEW:
• A view can be updated under certain conditions which are given below −
• The SELECT clause may not contain the keyword DISTINCT.
• The SELECT clause may not contain summary functions.
• The SELECT clause may not contain set functions.
• The SELECT clause may not contain set operators.
• The SELECT clause may not contain an ORDER BY clause.
• The FROM clause may not contain multiple tables.
• The WHERE clause may not contain subqueries.
• The query may not contain GROUP BY or HAVING.
• Calculated columns may not be updated.
• All NOT NULL columns from the base table must be included in the view in order for the INSERT query to function.
• So, if a view satisfies all the above-mentioned rules then you can update that view.
• The following code block has an example to update the age of Ramesh:
UPDATE CUSTOMERS_VIEW
SET AGE = 35
WHERE name = 'Ramesh';
Modification of the Database:
1. CREATE DATABASE Command:
The SQL CREATE DATABASE statement is used to create a new SQL database.
Syntax:
CREATE DATABASE DatabaseName;
NOTE: Always the database name should be unique within the RDBMS.
2. CREATE Command:
The SQL CREATE TABLE statement is used to create a new table.
Here, 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 −
You can verify if your table has been created successfully by looking at the message displayed by the SQL server,
otherwise you can use the DESC command as follows −
3. INSERT Command :
• 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.
Here, column1, column2, column3,...columnN are the names of the columns in the table into which you want to insert the
data.
You may not need to specify the column(s) name in the SQL query if you are adding values for all the columns of the table.
But make sure the order of the values is in the same order as the columns in the table.
The SQL INSERT INTO syntax will be as follows −
• Syntax: The basic syntax of the UPDATE query with a WHERE clause is as follows −
UPDATE table_name
WHERE [condition];
• You can combine N number of conditions using the AND or the OR operators.
• Example:The following query will update the ADDRESS for a customer whose ID number is
6 in the table.
UPDATE CUSTOMERS
WHERE ID = 6;
6. ALTER Command:
• The SQL ALTER TABLE command is used to add, delete or modify columns in an existing table.
• You should also use the ALTER TABLE command to add and drop various constraints on an existing table.
• Syntax: The basic syntax of an ALTER TABLE command to add a New Column in an existing
table is as follows.
ALTER TABLE table_name ADD column_name datatype;
• The basic syntax of an ALTER TABLE command to DROP COLUMN in an existing table is as follows.
ALTER TABLE table_name DROP COLUMN column_name;
• The basic syntax of an ALTER TABLE command to change the DATA TYPE of a column in a table is as
follows.
ALTER TABLE table_name MODIFY COLUMN column_name datatype;
• The basic syntax of an ALTER TABLE command to add a NOT NULL constraint to a column in a table is as
follows.
ALTER TABLE table_name MODIFY column_name datatype NOT NULL;
• The basic syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a table is as follows.
ALTER TABLE table_name
ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...);
7. DELETE Command :
• The SQL DELETE Query is used to delete the existing records from a table.
• You can use the WHERE clause with a DELETE query to delete the selected rows, otherwise all the records would be
deleted.
• Syntax: the basic syntax of the DELETE query with the WHERE clause is as follows −
DELETE FROM table_name
WHERE [condition];
• You can combine N number of conditions using AND or OR operators.
• Example:
DELETE FROM CUSTOMERS
WHERE ID = 6;
NOTE: If you want to DELETE all the records from the CUSTOMERS table, you do not need to use
the WHERE clause and the DELETE query would be as follows −
DELETE FROM CUSTOMERS;
Now, the CUSTOMERS table would not have any record.
8. DROP Command:
• The SQL DROP DATABASE statement is used to drop an existing database in SQL schema.
NOTE: Always the database name should be unique within the RDBMS.
NOTE : Be careful before using this operation because by deleting an existing database
would result in loss of complete information stored in the database.
9. RENAME/Alias Command:
• You can rename a table or a column temporarily by giving another name known as Alias.
• The renaming is a temporary change and the actual table name does not change in the database. The column aliases are
used to rename a table's columns for the purpose of a particular SQL query.
Syntax :
• The basic syntax of a table alias is as follows.
SELECT column1, column2....
FROM table_name AS alias_name
WHERE [condition];
• The basic syntax of a column alias is as follows.
SELECT column_name AS alias_name
FROM table_name
WHERE [condition];
Example:
SELECT C.ID, C.NAME, C.AGE, O.AMOUNT
FROM CUSTOMERS AS C, ORDERS AS O Table Alias
WHERE C.ID = O.CUSTOMER_ID;
-------------------------------------------------------------------------------------------------
SELECT ID AS CUSTOMER_ID, NAME AS CUSTOMER_NAME
FROM CUSTOMERS Column Alias
WHERE SALARY IS NOT NULL;
Transaction Commands:
- A transaction is a unit of work that is performed against a database.
- Transactions are units or sequences of work accomplished in a logical order, whether in a manual fashion by a
user or automatically by some sort of a database program.
- NOTE: Practically, you will club many SQL queries into a group and you will execute all of them together as a part
of a transaction.
• Properties of Transactions: Transactions have the following four standard properties, usually referred to
by the acronym ACID.
1. Atomicity − ensures that all operations within the work unit are completed successfully. Otherwise, the
transaction is aborted at the point of failure and all the previous operations are rolled back to their former
state.
2. Consistency − ensures that the database properly changes states upon a successfully committed transaction.
3. Isolation − enables transactions to operate independently of and transparent to each other.
4. Durability − ensures that the result or effect of a committed transaction persists in case of a
system failure.
Transaction Control Commands:
The following commands are used to control transactions.
10. COMMIT − to save the changes. The COMMIT command saves all the transactions to the database
since the last COMMIT or ROLLBACK command.
The syntax for the COMMIT command is as follows.
COMMIT;
Example: SQL> DELETE FROM CUSTOMERS
WHERE AGE = 25;
SQL> COMMIT;
11. ROLLBACK − to roll back the changes. This command can only be used to undo transactions
since the last COMMIT or ROLLBACK command was issued.
The syntax for a ROLLBACK command is as follows −
ROLLBACK;
Example: SQL> DELETE FROM CUSTOMERS
WHERE AGE = 25;
SQL> ROLLBACK;
12. SAVEPOINT − creates points within the groups of transactions in which to ROLLBACK.
SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain point
without rolling back the entire transaction.
The syntax for a SAVEPOINT command is as shown below.
SAVEPOINT SAVEPOINT_NAME;
This command serves only in the creation of a SAVEPOINT among all the transactional
statements. The ROLLBACK command is used to undo a group of transactions.
ROLLBACK TO SAVEPOINT_NAME;
13. SET TRANSACTION − Places a name on a transaction.
• The SET TRANSACTION command can be used to initiate a database transaction. This command is used to
specify characteristics for the transaction that follows. For example, you can specify a transaction to be read
only or read write.
Now, let us join these two tables in our SELECT statement as shown below.
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
• 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.
Authorization Commands: 14. GRANT Command
• When the SQL standard authorization mode is enabled, object owners can use the GRANT
and REVOKE SQL statements to set the user privileges for specific database objects or for
specific SQL actions. They can also use roles to administer privileges.
• The GRANT statement is used to grant specific privileges to users or to roles, or to grant
roles to users or to roles. The REVOKE statement is used to revoke privileges and role
grants. The grant and revoke privileges are:
• DELETE,EXECUTE,INSERT,SELECT,REFERENCES,TRIGGER,UPDATE