0% found this document useful (0 votes)
12 views163 pages

Module No - 4 DBMS

This document provides an overview of Structured Query Language (SQL), detailing its sub-languages including DDL, DML, and DCL, as well as various commands and integrity constraints. It covers the creation, modification, and management of relational databases, emphasizing the importance of data integrity through constraints like primary keys, foreign keys, and checks. Additionally, it discusses data types and operations available in SQL, making it a comprehensive guide for understanding database concepts.

Uploaded by

litdumacc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views163 pages

Module No - 4 DBMS

This document provides an overview of Structured Query Language (SQL), detailing its sub-languages including DDL, DML, and DCL, as well as various commands and integrity constraints. It covers the creation, modification, and management of relational databases, emphasizing the importance of data integrity through constraints like primary keys, foreign keys, and checks. Additionally, it discusses data types and operations available in SQL, making it a comprehensive guide for understanding database concepts.

Uploaded by

litdumacc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 163

MODULE NO:-4

Structured Query Language


(SQL)

Computer Engineering Department


Semester-IV
MODULE NO:-4 Introduction to Database Concepts:

4.1 Overview of SQL


4.2 Data Définition Command,
4.3. Integrity constraints :- key constraints, Domain Constraints,
Referential integrity , check constraints .
4.4. Data Manipulation command,
4.5. Data Control command,
4.6. Set and string operations, aggregate function - group by, having.
4.7. Views in SQL, joins , Nested and complex queries,
4.8. Triggers
Overview of SQL

➢ SQL stands for Structured Query Language.


➢ It is used for storing and managing data in relational database management system
(RDBMS).
➢ It is a standard language for Relational Database System.
➢ It enables a user to create, read, update and delete relational databases and tables.
➢ All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use SQL as
their standard database language.
➢ SQL allows users to query the database in a number of ways, using English-like
statements.
Overview of SQL

SQL Sub Languages

➢ DDL – Data Definition Language.


➢ DML – Data Manipulation Language.
➢ DRL/DQL – Data Retrieval Language/Data Query Language.
➢ TCL – Transaction Query Language.
➢ DCL – Data Control Language.
Overview of SQL
MODULE NO:-4 Introduction to Database Concepts:

4.1 Overview of SQL


4.2 Data Définition Command,
4.3. Integrity constraints :- key constraints, Domain Constraints,
Referential integrity , check constraints .
4.4. Data Manipulation command,
4.5. Data Control command,
4.6. Set and string operations, aggregate function - group by, having.
4.7. Views in SQL, joins , Nested and complex queries,
4.8. Triggers
4.2 DDL – Data Definition Language
Data Definition Language (DDL): to create and modify the structure of the database;
➢ This includes changes to the structure of the table like creation of table, altering table,
deleting a table etc.
➢ All DDL commands are auto-committed. That means it saves all the changes permanently
in the database
4.2 DDL – Data Definition Language
Attribute Data Types and Domains in SQL

The basic data types available for attributes include


➢ numeric,
➢ character string,
➢ bit string,
➢ Boolean,
➢ date, and
➢ time.
4.2 DDL – Data Definition Language
Attribute Data Types and Domains in SQL

Numeric data types


➢ Integer numbers of various sizes (INTEGER or INT, and SMALLINT) and
➢ floating-point (real) numbers of various precision (FLOAT or REAL, and DOUBLE
PRECISION).
Formatted numbers can be declared by using DECIMAL(i,j)—or DEC(i,j)
NUMERIC(i,j)—where i, the precision, is the total number of decimal digits and j, the
scale, is the number of digits after the decimal point. The default for scale is zero, and the
default for precision is implementation-defined.
Data Types
➢ DECIMAL and NUMERIC
Fixed precision and scale decimal numbers. DECIMAL and NUMERIC are
functionally equivalent.
Data Types
➢ FLOAT and REAL
Approximate-number data types for use with floating point numeric data.
Data Types
Integers
Exact-number data types that use integer data.
Data Types
BINARY and VARBINARY
Binary data types of either fixed length or variable length.
Data Types
Character-string data types
➢ fixed length—CHAR(n) or CHARACTER(n), where n is the number of characters—or
➢ varying length— VARCHAR(n) or CHAR VARYING(n) or CHARACTER VARYING(n),
where n is the maximum number of characters. When specifying a literal string value, it is
placed between single quotation marks (apostrophes), and it is case sensitive (a distinction is
made between uppercase and lowercase).

For fixed length strings, a shorter string is padded with blank characters to the right. For
example, if the value ‘Smith’ is for an attribute of type CHAR(10), it is padded with five blank
characters to become ‘Smith ’ if needed. Padded blanks are generally ignored when strings are
compared.
Data Types
CHAR and VARCHAR
String data types of either fixed length or variable length.
Data Types
Bit-string data types
fixed length n—BIT(n)—or
varying length—BIT VARYING(n), where n is the maximum number of bits.

➢ The default for n, the length of a character string or bit string, is 1. Literal bit strings
are placed between single quotes but preceded by a B to distinguish them from
character strings; for example, B‘10101’.
➢ Another variable-length bitstring data type called BINARY LARGE OBJECT or BLOB
is also available to specify columns that have large binary values, such as images
Data Types
A Boolean data type has the traditional values of TRUE or FALSE.
In SQL, because of the presence of NULL values, a three-valued logic is used,
so a third possible value for a Boolean data type is UNKNOWN.
Data Types
Data Types
➢ The DATE data type has ten positions, and its components are YEAR, MONTH, and
DAY in the form YYYY-MM-DD.

➢ The TIME data type has at least eight positions, with the components HOUR,
MINUTE, and SECOND in the form HH:MM:SS.

➢ for example, DATE ‘2008-09- 27’ or TIME ‘09:12:47’


Data Types
A timestamp data type (TIMESTAMP) includes the DATE and TIME fields,
plus a minimum of six positions for decimal fractions of seconds and an optional WITH
TIME ZONE qualifier.

Literal values are represented by single quoted strings preceded by the keyword
TIMESTAMP, with a blank space between data and time; for example, TIMESTAMP ‘2008-
09-27 09:12:47.648302’
DDL

CREATE It is used to create a new table in the database.


Syntax: CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);

Example:
CREATE TABLE EMPLOYEE
(Name VARCHAR(20),
Email VARCHAR(100),
DOB DATE);
DDL

DROP: It is used to delete both the structure and record stored in the table.
Syntax
DROP TABLE TABLE-NAME;

Example
DROP TABLE EMPLOYEE;
DDL
ALTER: It is used to alter the structure of the database. This change could be either to
modify the characteristics of an existing attribute or probably to add a new attribute.

Syntax:
To add a new column in the table
ALTER TABLE table_name ADD column_name COLUMN-definition;

Example:-
ALTER TABLE Employee ADD Phone_no INT
DDL
Syntax:
To modify existing column in the table:
ALTER TABLE TABLE_NAME MODIFY(COLUMN DEFINITION....);

Example:-
ALTER TABLE Employee MODIFY Phone_no VARCHAR(10)
DDL
Syntax:
To DROP existing column in the table:
ALTER TABLE TABLE NAME DROP(COLUMN NAME....);

Example:-
ALTER TABLE Employee DROP Phone_no
DDL
TRUNCATE: It is used to delete all the rows from the table and free the space containing
the table.
Syntax: TRUNCATE TABLE table_name;
Example:
TRUNCATE TABLE EMPLOYEE
MODULE NO:-4 Introduction to Database Concepts:

4.1 Overview of SQL


4.2 Data Définition Command,
4.3. Integrity constraints :- key constraints, Domain Constraints,
Referential integrity , check constraints .
4.4. Data Manipulation command,
4.5. Data Control command,
4.6. Set and string operations, aggregate function - group by, having.
4.7. Views in SQL, joins , Nested and complex queries,
4.8. Triggers
Integrity Constraint
Integrity Constraints are the protocols that a table's data columns must follow.
➢ These are used to restrict the types of information that can be entered into a table.
➢ This means that the data in the database is accurate and reliable.
➢ You may apply integrity Constraints at the column or table level.
➢ The table-level Integrity constraints apply to the entire table, while the column level
constraints are only applied to one column.
Integrity Constraint
Integrity Constraint

The following constraints are commonly used in SQL:


➢ 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
➢ INDEX - Used to create and retrieve data from the database very quickly
Integrity Constraint
SQL NOT NULL Constraint
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.
Integrity Constraint
SQL NOT NULL on CREATE TABLE
The following SQL ensures that the "ID", "LastName", and "FirstName"
columns will NOT accept NULL values when the "Persons" table is created:
Example
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int);
Integrity Constraints
SQL UNIQUE Constraint
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.
Integrity Constraints
SQL UNIQUE Constraint on CREATE TABLE
The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons"
table is created:

CREATE TABLE Persons (


ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int);
Integrity Constraints

➢ To name a UNIQUE constraint, and to define a UNIQUE constraint on


multiple columns, use the following SQL syntax:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT UC_Person UNIQUE (ID,LastName));
Integrity Constraints

➢ SQL UNIQUE Constraint on ALTER TABLE


To create a UNIQUE constraint on the "ID" column when the table is already
created, use the following SQL:

ALTER TABLE Persons ADD UNIQUE (ID);


Integrity Constraints
➢ SQL UNIQUE Constraint on ALTER TABLE
To create a UNIQUE constraint on the "ID" column when the table is already created, use
the following SQL:

ALTER TABLE Persons ADD UNIQUE (ID);

➢ To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple columns,


use the following SQL syntax:

ALTER TABLE Persons ADD CONSTRAINT UC_ Person UNIQUE (ID,LastName);


Integrity Constraints

SQL PRIMARY KEY Constraint


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; and in the table, this primary key can consist of single or multiple
columns (fields).
Integrity Constraints

SQL PRIMARY KEY on CREATE TABLE


The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table
is created:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID));
Integrity Constraints

➢ SQL PRIMARY KEY on ALTER TABLE


To create a PRIMARY KEY constraint on the "ID" column when the table is already
created, use the following SQL:

ALTER TABLE Persons ADD PRIMARY KEY (ID);

➢ To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:

ALTER TABLE Persons ADD CONSTRAINT PK _ Person PRIMARY KEY (ID,LastName);


Integrity Constraints
➢ DROP a PRIMARY KEY Constraint , To drop a PRIMARY KEY constraint, use
the following SQL:

ALTER TABLE Persons DROP PRIMARY KEY;


Integrity Constraints
Key constraints/entity integrity constraint
➢ Keys are the entity set that is used to identify an entity within its entity set uniquely.
➢ An entity set can have multiple keys, but out of which one key will be the primary key.
➢ A primary key can contain a unique and not null value in the relational table.
Integrity Constraints

SQL FOREIGN KEY Constraint


➢ 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 primary key is called the referenced or parent table.
Integrity Constraints
Person table

Foreign key

Primary key
Integrity Constraints
Referential Integrity Constraints
➢ A referential integrity constraint is specified between two tables .
➢ In the Referential integrity constraints, if a foreign key in Table 1 refers to
the Primary Key of Table 2, then every value of the Foreign Key in Table 1
must be null or be available in Table 2.
Integrity Constraints
Integrity Constraints
SQL FOREIGN KEY on CREATE TABLE
The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders"
table is created:

CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID));
Integrity Constraints
➢ To create a FOREIGN KEY constraint on the "PersonID" column when the "Orders" table is
already created, use the following SQL:

ALTER TABLE Orders ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

DROP a FOREIGN KEY Constraint


To drop a FOREIGN KEY constraint, use the following SQL:

ALTER TABLE Orders DROP FOREIGN KEY FK_PersonOrder;


Integrity Constraints

SQL CHECK Constraint


➢ The CHECK constraint is used to limit the value range that can be placed in
a column.
➢ If you define a CHECK constraint on a single column it allows only certain
values for this column.
➢ If you define a CHECK constraint on a table it can limit the values in certain
columns based on values in other columns in the row.
Integrity Constraints
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 the age of a person must be 18, or
older:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18));
Integrity Constraints
SQL CHECK Constraint
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following
SQL syntax:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes'));
Integrity Constraints
SQL CHECK Constraint
➢ SQL CHECK on ALTER TABLE
To create a CHECK constraint
SQL CHECK on the "Age" column when the table is already
Constraint
➢ SQL CHECK on ALTER TABLE
created, use the following SQL:
To create a CHECK constraint on the "Age" column when the table is already
created,
use the following SQL:
ALTER TABLE Persons ADD CHECK (Age>=18);
ALTER TABLE Persons ADD CHECK (Age>=18);
Integrity Constraints

➢ DROP a CHECK Constraint


To drop a CHECK constraint, use the following SQL:

ALTER TABLE Persons DROP CONSTRAINT CHK_PersonAge;


Integrity Constraints

SQL DEFAULT Constraint


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.
Integrity Constraints
SQL DEFAULT on CREATE TABLE
The following SQL sets a DEFAULT value for the "City" column when the "Persons"
table is created:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes');
Integrity Constraints
Domain constraints
➢ Domain constraints can be defined as the definition of a valid set of values for an
attribute.
➢ The data type of domain includes string, character, integer, time, date, currency, etc.
➢ The value of the attribute must be available in the corresponding domain.
MODULE NO:-4 Introduction to Database Concepts:

4.1 Overview of SQL


4.2 Data Définition Command,
4.3. Integrity constraints :- key constraints, Domain Constraints,
Referential integrity , check constraints .
4.4. Data Manipulation command,
4.5. Data Control command,
4.6. Set and string operations, aggregate function - group by, having.
4.7. Views in SQL, joins , Nested and complex queries,
4.8. Triggers
Data Manipulation Language
DML: Data Manipulation Language
➢ DML commands are used for manipulating the data stored in the table and not the
table itself.
➢ DML commands are not auto-committed. It means changes are not permanent to
database, they can be rolled back.
Data Manipulation Language
a. INSERT:
The INSERT statement is a SQL query. It is used to insert data into the row of a table.

Syntax:
INSERT INTO TABLE_NAME (col1, col2, col3,.... col N) VALUES (value1, value2, value3, .... valueN);
Or
INSERT INTO TABLE_NAME VALUES (value1, value2, value3, .... valueN);
Data Manipulation Language

Example:-
INSERT INTO employee VALUES ('RAVI','[email protected]','1990-10-18’)

Or
INSERT INTO `employee`(`Name`, `Email`, `DOB`)
VALUES ('RAVI','[email protected]','1990-10-18')
Data Manipulation Language
Data Manipulation Language
b. UPDATE: This command is used to update or modify the value of a column in the table.
Syntax:
UPDATE table_name
SET [column_name1= value1,...column_nameN = valueN]
[WHERE CONDITION]

Example:-
UPDATE employee
SET Email=‘[email protected]
Where Name=‘SANJAY’
Data manipulation language

c. DELETE: It is used to remove one or more row from a table.


Syntax:
DELETE FROM table_name [WHERE condition];

Example:-
DELETE FROM employee where Name=‘SANJAY’

Example:-
DELETE FROM employee
MODULE NO:-4 Introduction to Database Concepts:

4.1 Overview of SQL


4.2 Data Définition Command,
4.3. Integrity constraints :- key constraints, Domain Constraints,
Referential integrity , check constraints .
4.4. Data Manipulation command,
4.5. Data Control command,
4.6. Set and string operations, aggregate function - group by, having.
4.7. Views in SQL, joins , Nested and complex queries,
4.8. Triggers
Data control language
Data Control Language(DCL) is used to control privileges in Database.

➢ To perform any operation in the database, such as for creating tables,


sequences or views, a user needs privileges.
➢ Privileges are of two types,
▪ System: This includes permissions for creating session, table, etc and all
types of other system privileges.
▪ Object: This includes permissions for any command or query to perform
any operation on the database tables.
Data control language
DCL includes commands such as GRANT and REVOKE which mainly deal
with the rights, permissions, and other controls of the database system.
List of DCL commands:
➢ GRANT: This command gives users access privileges to the database.
➢ REVOKE: This command withdraws the user’s access privileges given
by using the GRANT command.
Data control language
a. Grant: It is used to give user access privileges to a database.
Example
GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHE
R_USER;

b. Revoke: It is used to take back permissions from the user.


Example
REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2; ;
https://www.youtube.com/watch?v=-IRSrWFQtC8
MODULE NO:-4 Introduction to Database Concepts:

4.1 Overview of SQL


4.2 Data Définition Command,
4.3. Integrity constraints :- key constraints, Domain Constraints,
Referential integrity , check constraints .
4.4. Data Manipulation command,
4.5. Data Control command,
4.6. Set and string operations, aggregate function - group by, having.
4.7. Views in SQL, joins , Nested and complex queries,
4.8. Triggers
Data Query language

➢ Queries are SQL functions that help us to access a particular set of records from a
database table.
➢ We can request any information or data from the database using the clauses or, let’s
say, SQL statements.
➢ For example, SQL Clauses receives a conditional expression that can be a column
name or valid term involving columns where this supports the MySQL functions to
calculate the result values for a table in the database.
Data Query language
What are Clauses in SQL?
➢ Clauses are in-built functions available to us in SQL.
➢ With the help of clauses, we can deal with data easily stored in the table.
➢ Clauses help us filter and analyze data quickly.
➢ When we have large amounts of data stored in the database, we use
Clauses to query and get data required by the user.
Data Query language

There are generally five kinds of SQL Clauses in MySQL Server. They
are listed as follows:
•WHERE Clause
•ORDER BY clause
•HAVING Clause
•TOP Clause
•GROUP BY Clause
Data Query language
Where Clause in SQL
We use the WHERE clause to specify conditionals in our SQL query. Where clause can be
used in the update and delete statements as well as to perform operations on the desired
data.
Rules and Usage:
1. Rules:
When using a Where clause, we need to mention at least one condition.
2. Usage:
•Used to query and transact the database.
•Used with an update and delete statements to make sure the right data points are deleted.
Data Query language

Syntax

SELECT * FROM tableName WHERE condition ;

Example 1: Let us find the details of all employees who earn more than 25,000 and are
above 25.
Select * from employee WHERE age>25 and salary >25000 ;
Data Query language
And Clause in SQL
We use And clause while specifying multiple conditions together in a query with the Where
clause.
Rules and Usage:
1. Rules:
•When using an And clause, we need to mention at least two conditions(the result would
satisfy both.)
2. Usage:
•Used to query and transact the database.
•Used with an update and delete statements to make sure the right data points are deleted.
•Returns a data point only if all conditions meet the requirements.
Data Query language

Syntax:

SELECT * FROM tableName WHERE condition1 AND condition2 ;

Example 1: Let us find the details of employees whose age is between 22 to 28 and earn
less than 30,000.

Select * from employee where age>22 and age<28 and salary<30000 ;


Data Query language
Or Clause in SQL
Or clause is beneficial when we need to pass multiple conditions, and we need data that
satisfies any one of those specified conditions.
Rules and Usage:
1. Rules:
•When using an Or clause, we need to mention at least two conditions(the result would be at
least one of the specified conditions.)
2. Usage:
•Used while transacting and querying a database.
•Used in the update and delete statements.
•Or clause returns a data point when any one of the specified conditions is met.
Data Query language

Syntax:

SELECT * FROM tableName WHERE condition1 OR condition2 ;

Example 1: Let us find the employees with age more than 26 or a salary more
than 30000

Select * from employee where salary > 30000 OR age > 26


Data Query language
Like Clause in SQL
LIKE clause is beneficial to find specific patterns in the data. We use specific
symbols i.e (%) and ( _ ). The rules and usage is specified below.
Rules and Usage:
1. Rules:
•% – Represents zero, one, or multiple characters.
•_ – Represents one single character.
2. Usage:
•Used to retrieve data points that satisfy the pattern passed using the like
clause.
Data Query language

Syntax :

SELECT * FROM tableName WHERE column2 LIKE pattern ;

Example 1: Let us find the details of employees whose name starts with A.

Select * from employee where name_emp LIKE 'A%' ;


Data Query language
Limit Clause in SQL
We use the limit clause when we have a large amount of data in the table. With the help of
the limit clause, we can restrict the number of rows our query returns.
Rules and Usage:
1. Rules:
•We need to specify a number after the limit clause.
•Float and exponential values can’t be utilized.
2. Usage:
•Used to limit the data that a query would return.
Data Query language

Syntax:

SELECT * FROM tableName LIMIT number ;

Example 1: Let us view the first 5 rows of data from our table

Select * from employee limit 5 ;


Data Query language
Order By Clause in SQL
We use order by clause to sort data in ascending or descending order as required by the user.
By default, the data is sorted in ascending order.
Rules and Usage:
1. Rules:
•A comparable data column should be passed in the query.
•Any column can be used in the order by clause, even those which do not appear in our select
statement.
•We can sort data in ascending or descending order (by default sorting is done in ascending ).
2. Usage:
•Order by clause is useful to get data in required sorting orders.
Data Query language

Syntax:

SELECT * FROM tableName ORDER BY column1, column2, ... ASC/DESC;

Example 1: Let us view the details of employees ordered in Descending order


according to salary.

Select * from employee Order by salary desc ;


Data Query language
Group By Clause in SQL
We use order by clause to get the summary of data in rows and is mostly taken in usage with
the aggregate functions like Count, Sum, etc.
Rules and Usage:
1. Rules:
•Columns appearing in the Select clause can only be taken care of in the Group By clause.
•Columns we are passing to the Group By clause should be of comparable type.
2. Usage:
•We use Group by clause to get the groups present in data.
Data Query language

Syntax

SELECT * FROM table_name WHERE condition GROUP BY column1 ;

Example 1: Let us count the employees with each age.

SELECT COUNT(age), age FROM employee GROUP BY age ;


Data Query language
Ex:-Table is grouped based on the DeptID column and Salary is aggregated department-wise.
Data Query language

HAVING clause
➢ A HAVING clause restricts the results of a GROUP BY in a SelectExpression.
➢ The HAVING clause is applied to each group of the grouped table, much as a
WHERE clause is applied to a select list.
➢ If there is no GROUP BY clause, the HAVING clause is applied to the entire result
as a single group.
➢ The SELECT clause cannot refer directly to any column that does not have a
GROUP BY clause. It can, however, refer to constants, aggregates, and special
registers.
Data Query language
HAVING Clause utilized in SQL as a conditional Clause with GROUP BY Clause.
This conditional clause returns rows where aggregate function results matched with
given conditions only.
It added in the SQL because WHERE Clause cannot be combined with aggregate results,
so it has a different purpose.

The primary purpose of the WHERE Clause is to deal with non-aggregated or individual
records.
•HAVING Clause always utilized in combination with GROUP BY Clause.
•HAVING Clause restricts the data on the group records rather than individual records.
•WHERE and HAVING can be used in a single query.
Data Query language
Table is grouped based on DeptID column and these grouped rows filtered using HAVING
Clause with condition AVG(Salary) > 3000.
DatainQuery
Order which language
clauses can be applied

SELECT column_name(s)
FROM table_name
WHERE condition(s)
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
Data Query language

Example 1: Let us first find employees whose age, if doubled, will be more than 50.
Query: SELECT * FROM employee WHERE age*2 > 50 ;
Data Query language

A JOIN combines records from two tables.


JOIN matches related column values in two tables.
A query can contain zero, one, or multiple JOIN operations.
Data Query language
Data Query language
List all orders with customer information.

SELECT OrderNumber, TotalAmount, FirstName, LastName, City, Country


FROM Order O JOIN Customer C ON C.Id = O.CustomerId
Data Query language

Find the Cartesian product instructor X teaches

Select * from instructor, teaches


Data Query language
Data Query language Retrieve employee from Research Department
SELECT *
FROM EMPLOYEE, DEPARTMENT
WHERE DNAME='Research' AND DNO=DNUMBER
SELECT * SELECT *
FROM EMPLOYEE FROM EMPLOYEE
WHERE DNO in WHERE exists
(SELECT DNUMBER (SELECT DNUMBER
FROM DEPARTMENT FROM DEPARTMENT
WHERE DNAME='Research’ ) WHERE
DNAME='Research’ and DNO=Dnumber)
Data Query language
Retrieve Details of manager from Research Department

SELECT *
FROM EMPLOYEE
WHERE SSN in
(SELECT MGR_SSN
FROM DEPARTMENT
WHERE DNAME='Research’ )
Data Query language
Examples:
Q1: SELECT FNAME, LNAME, ADDRESS
FROM EMPLOYEE , DEPARTMENT
WHERE DNAME='Research' AND DNUMBER=DNO
could be written as:
Q1: SELECT FNAME, LNAME, ADDRESS
FROM (EMPLOYEE JOIN DEPARTMENT ON DNUMBER=DNO)
WHERE DNAME='Research’
or as:
Q1: SELECT FNAME, LNAME, ADDRESS
FROM (EMPLOYEE NATURAL JOIN DEPARTMENT AS DEPT(DNAME, DNO,
MSSN, MSDATE)
WHERE DNAME='Research’
Data Query
Operators language
in Where Clause
Data Query
Operators language
in Where Clause
Data Query language

Find the names of all instructors whose salary is greater than the salary of all
instructors in the Biology department

select name
from instructor
where salary > all (select salary
from instructor
where dept name = ’Biology’);
Data Query language

Find names of instructors with salary greater than that of some (at least one)
instructor in the Biology department's

select name
from instructor
where salary > some (select salary
from instructor
where dept name = ’Biology’);
Data Query language

Retrieve the names of employees who have no dependents.

SELECT FNAME, LNAME


FROM EMPLOYEE
WHERE NOT EXISTS (SELECT *
FROM DEPENDENT
WHERE SSN=ESSN)
Data Query language

Delete all instructors whose salary is less than the average salary of instructors

delete from instructor


where salary < (select avg (salary)
from instructor);
Data Query language
Data Query language
Find all information of sailors who have reserved boat number 103.
Data Query language
Find all information of sailors who have reserved boat number 103.
Data Query language

Find the names of sailors who have reserved boat 103.


Data Query language
Find the ids of sailors who have reserved a red boat or a green boat
Data Query language
Find the ids of sailors who have reserved a red boat or a green boat
Data Query language
Find the ids of sailors who have reserved a red boat AND a green boat
Data Query language
Find sid’s of all sailors who’ve reserved red boat but not green boat.
Data Query language
Find sid’s of all sailors who have a rating of 10 or reserved boat 104.
Data Query language
Find the name and the age of the youngest sailor
Data Query language
Find the names and ratings of sailor whose rating is better than some sailor called Horatio.
Data Query language

Count the number of different sailor names


Calculate the average age of all sailors.
Data Query language

Find the name and the age of the youngest sailor.


Data Query language
: Find the average age of sailors for each rating level
Data Query language
: Find the colors of boats reserved by Lubber
Data Query language
Data Query language
Find the total number of people who owned cars that were involved in accidents in 1989.

SELECT COUNT(DISTINCT DRIVER_ID)


FROM PARTICIPATED,ACCIDENT
WHERE PARTICIPATED.DRIVER_ID= ACCIDENT.DRIVER_ID
AND DATE BETWEEN ‘1989-01-01’ AND ‘1989-12-31’
Find the number of accidents in which the cars belonging to “ John Smith” were involved.

SELECT COUNT (REPORT –NUMBER)


FROM ACCIDENT,PARTICIPATED,PERSON
WHERE ACCIDENT. REPORT –NUMBER= PARTICIPATED. REPORT –NUMBER
AND PARTICIPATED.DRIVER_ID=PERSON.DRIVER_ID
AND PERSON.NAME=‘’JOHN SMITH’; 124
Data Query language
Find the number of accidents in which the cars belonging to “ John Smith” were involved.
Data Query language
Add a new accident to the database; assume any values for required attribute

insert into accident values (4007, ’2001-09-01’, ’Berkeley’)


Data Query language
Delete the Mazda belonging to “John Smith”

Delete car
where model = ’Mazda’ and license in
(select license
from person p, owns o
where p.name = ’John Smith’
and p.driver-id = o.driver-id)
Data Query language
Update the damage amount for the car with license number “AABB2000” in the accident
with report number “AR2197” to $3000.

update participated
set damage-amount = 3000 where report-number = “AR2197”
and driver-id in (select driver-id
from owns
where license = “AABB2000”)
Data Query language

Employee (employee-name, street, city)


Works (employee-name, company-name, salary)
Company (company-name, city)
Manages (employee-name, manager-name)
Data Query language
. Find the names of all employees who work for First Bank Corporation.

Employee (employee-name, street, city)


Works (employee-name, company-name, salary)
Company (company-name, city)
Manages (employee-name, manager-name)

select employee-name
from works
where company-name = ’First Bank Corporation’
Data Query language
Find the names and cities of residence of all employees who work for First Bank Corporation

Employee (employee-name, street, city)


Works (employee-name, company-name, salary)
Company (company-name, city)
Manages (employee-name, manager-name)

select e.employee-name, city


from employee e, works w
where w.company-name = ’First Bank Corporation’ and
w.employee-name = e.employee-name
Data Query language
Find the names, street address, and cities of residence of all employees who work for First
Bank Corporation and earn more than $10,000.
Employee (employee-name, street, city)
Works (employee-name, company-name, salary)
Company (company-name, city)
Manages (employee-name, manager-name)

select *
from employee
where employee-name in (select employee-name
from works
where company-name = ’First Bank Corporation’ and salary > 10000)
Data Query language
Find all employees in the database who live in the same cities as the companies for which they
work.
Employee (employee-name, street, city)
Works (employee-name, company-name, salary)
Company (company-name, city)
Manages (employee-name, manager-name)

select e.employee-name
from employee e, works w, company c
where e.employee-name = w.employee-name and e.city = c.city
and w.company -name = c.company -name
Data Query language
Find all employees in the database who do not work for First Bank Corporation
Employee (employee-name, street, city)
Works (employee-name, company-name, salary)
Company (company-name, city)
Manages (employee-name, manager-name)

select employee-name
from works
where company-name ≠’First Bank Corporation’
Data Query language
Find all employees in the database who do not work for First Bank Corporation

Employee (employee-name, street, city)


Works (employee-name, company-name, salary)
Company (company-name, city)
Manages (employee-name, manager-name)

select employee-name
from employee
where employee-name not in (select employee-name
from works
where company-name = ’First Bank Corporation’)
Data Query language
Find all employees in the database who earn more than every employee of Small Bank Corporation

Employee (employee-name, street, city)


Works (employee-name, company-name, salary)
Company (company-name, city)
Manages (employee-name, manager-name)

select employee-name
from works
where salary > all (select salary
from works
where company-name = ’Small Bank Corporation’)
Data Query language
Find all employees who earn more than the average salary of all employees of their company.
Employee (employee-name, street, city)
Works (employee-name, company-name, salary)
Company (company-name, city)
Manages (employee-name, manager-name)

select employee-name
from works T
where salary > (select avg (salary)
from works S
where T.company-name = S.company-name)
Data Query language
Modify the database so that Jones now lives in Newtown..

Employee (employee-name, street, city)


Works (employee-name, company-name, salary)
Company (company-name, city)
Manages (employee-name, manager-name)

update employee
set city = ’Newton’
where person-name = ’Jones’
Data Query language
Give all employees of First Bank Corporation a 10-percent raise
Employee (employee-name, street, city)
Works (employee-name, company-name, salary)
Company (company-name, city)
Manages (employee-name, manager-name)

update works
set salary = salary * 1.1
where company-name = ’First Bank Corporation’
Data Query language
Give all managers of First Bank Corporation a 10-percent raise.
Employee (employee-name, street, city)
Works (employee-name, company-name, salary)
Company (company-name, city)
Manages (employee-name, manager-name)
update works
set salary = salary * 1.1
where company-name = ’First Bank Corporation’ AND
employee-name in (select manager-name
from manages)
MODULE NO:-4 Introduction to Database Concepts:

4.1 Overview of SQL


4.2 Data Définition Command,
4.3. Integrity constraints :- key constraints, Domain Constraints,
Referential integrity , check constraints .
4.4. Data Manipulation command,
4.5. Data Control command,
4.6. Set and string operations, aggregate function - group by, having.
4.7. Views in SQL, joins , Nested and complex queries,
4.8. Triggers
VIEWS IN SQL

▪ A View in SQL as a logical subset of data from one or more tables.


▪ Views are used to restrict data access.
▪ A View contains no data of its own but its like window through which data from tables
can be viewed or changed.
▪ The table on which a View is based are called BASE Tables.
▪ The SQL VIEW is, in essence, a virtual table that does not physically exist.
▪ Rather, it is created by a SQL statement that joins one or more tables.
VIEWS IN SQL
VIEWS IN SQL

TYPES OF VIEWS
➢ Simple views can only contain a single base table.
➢ Complex views can be constructed on more than one base table. In
particular, complex views can contain: join conditions, a group by
clause, a order by clause.
VIEWS IN SQL
VIEWS IN SQL
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name SQL CREATE VIEW Examples
WHERE condition;
Creates a view that shows all customers from Brazil:

CREATE VIEW [Brazil Customers] AS


SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';
VIEWS IN SQL EXAMPLE RELATION
VIEWS IN SQL
Creating View from a single table(SIMPLEX VIEW)
View named DetailsView from the table Student_Detail.
CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM Student_Details
WHERE STU_ID < 4;
VIEWS IN SQL
Creating View from multiple tables(COMPLEX VIEW)
View is created named MarksView from two tables Student_Detail and Student_Marks
CREATE VIEW MarksView AS
SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.MARKS
FROM Student_Detail, Student_Mark
WHERE Student_Detail.NAME = Student_Marks.NAME;
VIEWS IN SQL
Deleting View
Syntax
DROP VIEW view_name;

Example:
If we want to delete the View MarksView, we can do this as:

DROP VIEW MarksView;


VIEWS IN SQL 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.
6.If the view is created using multiple tables then we will not be allowed to update the view.
VIEWS IN SQL
CREATE OR REPLACE VIEW

We can use the CREATE OR REPLACE VIEW statement to add or


remove fields from a view.
Syntax:
CREATE OR REPLACE VIEW view_name AS
SELECT column1,coulmn2,..
FROM table_name
WHERE condition
VIEWS IN SQL
Create a View named MarksView from two tables StudentDetails and StudentMarks
CREATE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
UpdateVIEWS
the viewINMarksView
SQL and add the field AGE to this View from StudentMarks Table, we
can do this as:
CREATE OR REPLACE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, MarksView
StudentMarks.MARKS, StudentMarks.AGE
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
MarksView
VIEWS IN SQL
Inserting a row in a view
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:
INSERT INTO view_name(column1, column2 , column3,..) VALUES(value1, value2, value3..);
VIEWS IN SQL
Inserting a row in a view
Insert a new row in the View DetailsView which we have created above in the
example of “creating views from a single table”.
INSERT INTO DetailsView(NAME, ADDRESS)
VALUES("Suresh","Gurgaon");
VIEWS IN SQL
Deleting a row from a View:

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
VIEWS IN SQL

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";


VIEWS IN SQL
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";


MODULE NO:-4 Introduction to Database Concepts:

4.1 Overview of SQL


4.2 Data Définition Command,
4.3. Integrity constraints :- key constraints, Domain Constraints,
Referential integrity , check constraints .
4.4. Data Manipulation command,
4.5. Data Control command,
4.6. Set and string operations, aggregate function - group by, having.
4.7. Views in SQL, joins , Nested and complex queries,
4.8. Triggers
Triggers
Triggers
Be good do good

You might also like