3.1 Structured Query Language (SQL) : Unit-Iii
3.1 Structured Query Language (SQL) : Unit-Iii
Structured Query Language (SQL): Introduction to SQL, Data Definition Languange, Data Manipulation
Language, Data Control Language, and Transaction Control Language, SELECT queries, creating a view, joining
database tables, sub queries and correlated queries.
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: Data 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.
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.
INSER
T
INSERT INTO tablename (column1, column2, ..)VALUES (value1, value2,.. .);
OR
INSERT INTO table_name VALUES (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, ...FROM 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.
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 CID, NAME, Addr, AMOUNT from CUSTOMER 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 CUSTOMER;
● To rename table
Select Name from Customer as Cust where CID=1;
SELECT C.CID, NAME, Addr, AMOUNT FROM CUSTOMER as C, ORDER
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, ...FROM table_name ORDER BY column1,
column2, ... ASC/DESC;
Eg. SELECT NAME FROM CUSTOMER ORDER BY Name DESC;
NAME
Vishnu
Manju
Jisy
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
SID CID
2 B 36 cs
3 C 28 ec
CID Cname
1 c1
4 B 30 ec
1 c2
5 F 46 ee
2 c3
6 G 34 cs
3 c2
● Independent Nested Queries: In independent nested queries, query execution starts from
innermost query to outermost queries. The execution of inner query is independent of outer query,
but the result of inner query is used in execution of outer query. Various operators like IN, NOT
IN, ANY, ALL etc are used in writing independent nested queries.
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 of Materialized view rowid is different.
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.
SQL JOINS
We can retrieve data from more than one tables using the JOIN statement. There are mainly 4 different types of
JOINS in SQL server. We will learn all JOINS in SQL server with examples:
INNER JOIN
This type of SQL server JOIN returns rows from all tables in which the join condition is true. It takes the
following syntax:
SELECT columns
FROM table_1
INNER JOIN table_2
ON table_1.column = table_2.column;
We will use the following two tables to demonstrate this:
Students Table:
Fee table:
The following command demonstrates an INNER JOIN in SQL server with example:
We can tell the students who have paid their fee. We used the column with common values in both tables, which
is the admission column.
The reason for the above output is that all rows in the Fee table are available in the Students table when matched
on the admission column.