sql (2)
sql (2)
Asst.Professor CSE
CE, Cherthala
Module 3
Structured Query Language (SQL): Basic SQL Structure, examples, Set
operations, Aggregate Functions, nested sub-queries, Views, assertions and
triggers
SQL Constraints
● NOT NULL - Ensures that a column cannot have a NULL value
● UNIQUE - Ensures that all values in a column are different
● PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies
each row in a table
● FOREIGN KEY - Uniquely identifies a row/record in another table
● CHECK - Ensures that all values in a column satisfies a specific condition
● DEFAULT - Sets a default value for a column when no value is specified
SQL Commands
● DDL: Data Definition Language
● DML: D ata Manipulation Language
● DCL: Data Control Language
● TCL:Transaction Control Language
DDL:The SQL DDL allows specification of not only a set of relations, but also
information about each relation, including:
● The schema for each relation.
● The types of values associated with each attribute.
● The integrity constraints.
● The set of indices to be maintained for each relation.
Basic data types used are,
char A fixed-length character string with user-specified length n. The full
form, character, can be used instead.
int An integer (a finite subset of the integers that is machine dependent). The
full form, integer, is equivalent.
Main Commands,
CREATE Creates a new table, a view of a table, or other object in the
database.
Create
● To create database,
CREATE DATABASE database_name
● To create Table Statement is used to create tables to store data. Integrity Constraints
can also be defined for the columns while creating the table.
CREATE TABLE Persons (PID int(10) NOT NULL PRIMARY KEY, LastName varchar(25),
FirstName varchar(25));
Or
CREATE TABLE Persons (PID int (10) NOT NULL, LastName varchar(25),FirstName
varchar(25), primary key(id));
-Foreign Key
CREATE TABLE Orders ( OrderID int NOT NULL PRIMARY KEY, OrderNumber int NOT
NULL, PersonID int, FOREIGN KEY (PID) REFERENCES Persons(PID));
ALTER:
● To add column
ALTER TABLE table_name ADD column_name datatype;
● To delete column
ALTER TABLE table_name Drop column column_name;
DROP:
DROP DATABASE database_name;
DROP TABLE table_name;
RENAME:
● To rename a table
RENAME TABLE tbl_name TO new_tbl_name;
● To rename a column
ALTER TABLE table_name Rename column old column name to new name;
DML: The SQL commands that deals with the manipulation of data present in database belong
to DML or Data Manipulation Language and this includes most of the SQL statements.
INSERT
INSERT INTO tablename (column1, column2, ..)VALUES (value1, value2,.. .);
OR
INSERT INTO table_name V ALUES (value1, value2, value3, ...);
SELECT
● To select a entire table
SELECT * FROM table_name;
● To select column
SELECT column1, column2, ...FROM table_name;
● To select rows
SELECT column1, column2, ...F
ROM table_name WHERE condition;
UPDATE
UPDATE table_name SET column1 = value1, column2 = value2,... WHERE condition;
DELETE
● To delete all rows
DELETE FROM table_name;
● To delete specific row
DELETE FROM table_name WHERE condition;
DCL : DCL mainly deals with the rights, permissions and other controls of the database system
GRANT
GRANT privilege_name ON Table_name TO user_name;
Eg. GRANT SELECT ON employee TO user1
REVOKE
REVOKE privilege_name ON Table_name FROM user_name;
Eg. REVOKE SELECT ON employee FROM user1;
TCL
Transaction Control Language(TCL) commands are used to manage transactions in the
database. These are used to manage the changes made to the data in a table by DML
statements.
COMMIT command is used to permanently save any transaction into the database.
SAVEPOINT command is used to temporarily save a transaction so that you can rollback
to that point whenever required.
COMMIT:
Syntax- COMMIT;
ROLLBACK:
● The ROLLBACK command to rollback those changes, if they were not committed using
the COMMIT command
Rollback;
● The command restores the database to last committed state by using SAVEPOINT
command.
ROLLBACK TO savepoint_name;
SAVEPOINT
SAVEPOINT savepoint_name;
3.2 Basic SQL Structure
The basic structure of an SQL query consists of three clauses: select, from,
and where. The query takes as its input the relations listed in the from clause,
operates on them as specified in the where and select clauses, and then produces
a relation as the result.
The result is a relation consisting of a single attribute. If want to force the elimination of
duplicates, we insert the keyword distinct after select. We can rewrite the preceding query as:
DEPT
CS
EC
SQL allows us to use the keyword all to specify explicitly that duplicates are not removed:
select all DEPTNAME from DEPT;
The select clause may also contain arithmetic expressions involving the operators +, −, ∗, and /
operating on constants or attributes of tuples. For example,the query returns a relation that is
the same as the Faculty relation, except that the attribute salary is multiplied by 1.1.
● Retrieve CID, Address and amount from relation CUSTOMER and ORDER
whose name= jisy
SELECT CUSTOMER.CID, Addr, AMOUNT FROM CUSTOMER, ORDER WHERE
CUSTOMERS.CID = ORDERS.CID and NAME=’Jisy’;
● Retrieve customer id, name, Address and amount from relation CUSTOMER
and ORDER
SELECT CUSTOMER.CID, NAME, Addr, AMOUNT FROM CUSTOMER, ORDER
WHERE CUSTOMERS.CID = ORDERS.CID;
Join
Select CID, NAME, Addr, AMOUNT from CUSTOMER Natural join ORDER
Select C ID, NAME, Addr, AMOUNT from C USTOMER Inner join ORDER on
CUSTOMER.CID = ORDER.CID;
SQL aliases/ correlation name/ tuple variable.
SQL aliases are used to give a table, or a column in a table, a temporary name.
● To rename column,
Select old column name as new name from table name;
Eg. Select CID as CustomerID , Name from C USTOMER;
● To rename table
Select Name from Customer as Cust where CID=1;
ELECT C.CID, NAME, Addr, AMOUNT FROM CUSTOMER as C, ORDER
S
WHERE C.CID = ORDERS.CID;
String Operations
SQL specifies strings by enclosing them in single quotes, for example, ’Computer’. The
SQL standard specifies that the equality operation on strings is case sensitive; as a result the
expression “ ’computer’ = ’Computer’ ” evaluates to false.
SQL also permits a variety of functions on character strings, such as concatenating
(using “ ||”), extracting substrings, finding the length of strings, converting strings to uppercase
(using the function upper(s) where s is a string) and lowercase (using the function lower(s)),
removing spaces at the end of the string (using trim(s)). Pattern matching can be performed on
strings, using the operator like. We describe patterns by using two special characters:
WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any
position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the
second position
WHERE CustomerName LIKE 'a_%_%' Finds any values that start with "a" and are
at least 3 characters in length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and
ends with "o"
SQL ORDER BY
The ORDER BY statement in sql is used to sort the fetched data in either ascending or
descending according to one or more columns. By default ORDER BY sorts the data in
ascending order.
SELECT column1, column2, ...F
ROM table_name ORDER BY column1,
SC/DESC;
column2, ... A
Eg. SELECT NAME FROM CUSTOMER ORDER BY Name DESC;
NAME
Vishnu
Manju
Jisy
ROM table_name W
SELECT column_name(s) F HERE column_name B
ETWEEN
value1 AND value2;
ID Name ID Name
1 JISY 3 SWETHA
2 SANTHY 2 SANTHY
UNION Operation: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.
SELECT * FROM First UNION SELECT * FROM Second;
ID Name
1 JISY
2 SANTHY
3 SWETHA
UNION ALL:This operation is similar to Union. But it also shows the duplicate rows.
SELECT * FROM First UNION ALL SELECT * FROM Second;
ID Name
1 JISY
2 SANTHY
3 SWETHA
2 SANTHY
INTERSECT: Intersect operation is used to combine two SELECT statements, but it only retuns
the records which are common from both SELECT statements. In case of Intersect the number
of columns and datatype must be same
SELECT * FROM First INTERSECT SELECT * FROM Second;
ID Name
2 SANTHY
Minus/ Except: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.
SELECT * FROM First Except SELECT * FROM Second;
ID Name
1 JISY
ID Name
3 SWETHA
Stud
RollNo. Name Mark Dept
1 A 40 cs
2 B 36 cs
3 C 28 ec
4 B 30 ec
5 F 46 ee
6 G 34 cs
COUNT(): The aggregate function count used to count the number of tuples in a relation.
Select Count(*) from Stud;
Count(*)
Count(*)
Name
MIN(): The MIN() function returns the smallest value of the columns.
Select Min(Mark) from Stud ;
Min
28
Max(): The MAX() function returns the largest value of the selected column.
Select Max(Mark) from Stud ;
Max
46
Sum(): The SUM() function returns the total sum of a numeric column.
Select sum(Mark) from Stud ;
Select sum(M1+M2) from Stud ; (also possible)
3.4.2 Aggregation with Group by: The GROUP BY statement is often used with aggregate
functions.
Select Aggregate fn(column name) from table_name group by column name;
Select Dept, Count(RollNo) from Stud Group By Dept;
Dept Count
cs 3
ec 2
ee 1
Group by using the HAVING clause: Grouping data with certain condition.
SELECT column_name(s) FROM table_name WHERE condition GROUP BY column name(s)
HAVING condition
Select Dept, Count(RollNo) from Stud Group By Dept Having Mark>35;
Dept Count
cs 2
ec 0
ee 1
In general, aggregate functions treat nulls according to the following rule: All aggregate
functions except count (*) ignore null values in their input collection. As a result of null values
being ignored, the collection of values may be empty. The count of an empty collection is
defined to be 0, and all other aggregate operations return a value of null when applied on an
empty collection. A Boolean data type that can take values true, false, and unknown.
1 A 40 cs c1 DBMS 1 c1
2 B 36 cs c2 DS 1 c2
3 C 28 ec c3 CP 2 c3
3 c2
4 B 30 ec
4 c3
5 F 46 ee
6 G 34 cs
Q1. If we want to find out SID who are enrolled in Cname ‘DS’ or ‘DBMS’.
From Course table, we can find out CID for Cname ‘DS’ or DBMS’ and we can use these CIDs
for finding SIDs from Scourse TABLE.
Q2. Find out names of STUDENTs who have either enrolled in ‘DS’ or ‘DBMS’, it can be done
as:
Select Name from Stud where SID IN (Select SID from Scourse where CID IN (Select
CID from Course where Cname = ‘DS’ or Cname = ‘DBMS’));
Q3. If we want to find out SIDs of STUDENTs who have neither enrolled in ‘DSA’ nor in ‘DBMS’,
it can be done as:
Select Name from Stud where SID NOT IN (Select SID from Scourse where CID IN
(Select CID from Course where Cname = ‘DS’ or Cname = ‘DBMS’));
Q1. If we want to find out NAME of Student who are enrolled in CID ‘C1’
Select NAME from Stud where EXISTS(select * from Scourse where Stud.SID=Scourse.SID
and Scourse.CID=’C1’);
Correlated Query: 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 is a
subquery that uses values from the outer query.
Eg.SELECT employee_number, name FROM employees emp WHERE salary > ( SELECT
AVG(salary) FROM employees WHERE department = emp.department);
SELECT Course.CID FROM Course WHERE UNIQUE (SELECT CID FROM Scourse where
Scourse.CID=Course.CID);
3.5.4 ALL
The ALL operator returns TRUE if all of the subqueries values meet the condition.
Q1. Returns the names, Rollno of students whose mark is greater than the mark of all the
students in department ec:
SELECT Name , SID FROM Stud WHERE Mark > ALL ( SELECT Mark FROM Stud WHERE
Dept =ec );
SD SM
To see the data in the View, we can query the view in the same manner as we query a table.
SELECT * FROM Details;
We can use the CREATE OR REPLACE VIEW statement to add or remove fields from a view.
WHERE condition;
For example, if we want to update the view Marks and add the field AGE to this View from SM
Materialized views are also the logical view of our data-driven by the select query but the result
of the query will get stored in the table or disk.
Views query result is not stored in the disk or Materialized view allow to store the query
database result in disk or table.
when we create a view using any table, rowid Materialized view rowid is different.
of view is same as the original table
View we always get latest data Materialized view we need to refresh the
view for getting latest data.
A trigger is a statement or a block of statement which are executed automatically by the system
when an event like insert, update or delete takes place on a table.
1. The event(s): These are usually database update operations that are explicitly applied to the
database.. The events are specified with two keyword BEFORE and AFTER. Before means that
the trigger should be executed before the triggering operation is executed. The keyword AFTER,
which specifies that the trigger should be executed after the operation specified in the event is
completed.
2. The condition that determines whether the rule action should be executed: Once the
triggering event has occurred, an optional condition may be evaluated. If no condition is
specified, the action will be executed once the event occurs. If a condition is specified, it is first
evaluated, and only if it evaluates to true will the rule action be executed. The condition is
specified in the WHEN clause of the trigger.
3. The action to be taken: The action is usually a sequence of SQL statements,but it could also
be a database transaction or an external program that will be automatically executed. In this
example, the action is to execute the stored
procedure INFORM_SUPERVISOR.
Assertions - An assertion is a piece of SQL which makes sure a condition is satisfied or it stops action
being taken on a database object. It could mean locking out the whole table or even the whole database.
CREATE ASSERTION name CHECK ( NOT EXISTS ( SELECT column name FROM table name
WHERE condition ) );
Trigger Assertion
executed automatically by the system when a piece of SQL which makes sure a condition is
an event like insert, update or delete takes satisfied or it stops action being taken on a
more powerful because the can check conditions do not modify the data, they only check certain
and also modify the data conditions.
Triggers are linked to specific tables and specific Assertions are not linked to specific tables in the
events. database and not linked to specific events.