Module 4 SQL
Module 4 SQL
Module 4 SQL
Data Description
type
int It is used to specify an integer value.
smallint It is used to specify small integer
value.
bit It has the number of bits to store.
decimal It specifies a numeric value that can
have a decimal number.
Structured query Language (SQL):
Datatype of SQL:
4. Character String Datatype
The subtypes are given below:
Data Description
type
char It has a maximum length of 8000
characters. It contains Fixed-length non-
unicode characters.
varchar It has a maximum length of 8000
characters. It contains variable-length
non-unicode characters.
text It has a maximum length of
2,147,483,647 characters. It contains
Structured query Language (SQL):
Datatype of SQL:
Date and time Datatypes
Datatype Description
date It is used to store the year,
month, and days value.
time It is used to store the hour,
minute, and second values.
timestamp It stores the year, month, day,
hour, minute, and the second
value.
Data Definition
Language (DDL)-Syntax
Here are some commands that come
under DDL:
•CREATE
•ALTER
•DROP
•TRUNCATE
Data Definition
Language (DDL)-Syntax
a. CREATE It is used to create a new table in
the database.
Syntax:
CREATE TABLE TABLE_NAME (COLUMN_NA
ME DATATYPES[,....]);
Example:
CREATE TABLE EMPLOYEE
(Name VARCHAR(20),
Email VARCHAR(100),
DOB DATE);
Data Definition
Language
b. DROP: (DDL)-Syntax
It is used to delete both the structure
and record stored in the table.
Syntax
1.DROP TABLE TABLE-
NAME;
Example
1.DROP TABLE EMPLOYEE;
Data Definition
Language (DDL)-Syntax
c. 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
1.ALTER TABLE table_name ADD column_name COL
Example:-
UMN-definition;
ALTER TABLE Employee ADD
Phone_nO INT
Data Definition
Language (DDL)-Syntax
c. 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 modify existing column in the table:
ALTER TABLE MODIFY(COLUMN DEFINITION....);
Example:-
ALTER TABLE Employee MODIFY
Phone_nO VARCHAR(10)
Data Definition
Language (DDL)-Syntax
c. 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 DROP existing column in the table:
ALTER TABLE DROP(COLUMN NAME....);
Example:-
ALTER TABLE Employee DROP Phone_nO
Data Definition
Language (DDL)-Syntax
d. TRUNCATE: It is used to delete all the rows
from the table and free the space containing the
table.
Syntax:
1.TRUNCATE TABLE table_name;
Example:
1.TRUNCATE TABLE EMPLOY
EE;
2. 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, value
3, .... valueN);
2. 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')
2. 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’
2. Data Manipulation Language
Example:-
DELETE FROM employee
3. Data Control Language
COMMIT
ROLLBACK
4. Transaction Control Language
a. Commit: Commit command is used to save all
the transactions to the database.
Syntax:
COMMIT;
Example:
DELETE FROM CUSTOMERS
WHERE AGE = 25;
COMMIT;
4. Transaction Control Language
Rollback: Rollback command is used to
undo transactions that have not
already been saved to the database..
Syntax:
ROLLBACK;
Example:
DELETE FROM CUSTOMERS
WHERE AGE = 25;
ROLLBACK;
4. Transaction Control Language
Syntax:
SAVEPOINT SAVEPOINT_NAME;
5. Data Query Language
DQL is used to fetch the data from the database.
Example:-
SELECT Fname,Ssn,Salary
FROM employee
Where Dno=5;
SQL Constraints
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'));
SQL Constraints
SQL CHECK Constraint
SQL CHECK on ALTER TABLE
To create a CHECK constraint on the "Age" column when
the table is already created,
use the following SQL:
-
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.
Integrity constraints :
Entity integrity constraints
The entity integrity constraint states that
primary key value can't be null.
This is because the primary key value is used to
identify individual rows in relation and if the
primary key has a null value, then we can't identify
those rows.
A table can contain a null value other than the
primary key field.
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 :
Key constraints
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 null value
in the relational table.
Structured Query Language (SQL)
Syntax
Simple query example
Simple query –string operation
Simple Query--Set operations
Simple Query--Arithmetic Operation
Structured Query Language (SQL)-
Syntax
SQL SELECT Statement
Select *
from
Students;
Structured Query Language (SQL)-Examples
Example 3:-Retrieves the students
whose age is bigger and equal to 20.
Structured Query Language (SQL)-String Operation
LIKE Syntax:-
SELECT column1, column2, ...
FROM table_name
Structured Query Language (SQL)-String
Operation-Examples
CUSTOME
R
SELECT * FROM
Customers WHERE
CustomerName
LIKE 'a%';
Structured Query Language (SQL)-String
Operation-Examples
Example 6:-Selects all customers with a
CustomerName that have "or" in any position
CUSTOME
R
SELECT * FROM
Customers
WHERE
CustomerName LIKE
'%or%';
Structured Query Language (SQL)-String
Operation-Examples
Example 7:-Selects all customers with a
CustomerName that have "r" in the second position:
CUSTOME
R
SELECT * FROM
Customers
WHERE
CustomerName LIKE
'_r%';
Structured Query Language (SQL)-String
Operation-Examples
Example 8:-selects all customers with a
CustomerName that starts with "a" and are at least 3
characters in length:
CUSTOME
R
SELECT * FROM
Customers
WHERE CustomerName
LIKE 'a__%';
Structured Query Language (SQL)-String
Operation-Examples
Example 9:-selects all customers with a
ContactName that starts with "a" and ends with "o":
CUSTOME
R
SELECT * FROM
Customers
WHERE ContactName
LIKE 'a%o';
Structured Query Language (SQL)-String
Operation-Examples
Example 10:-Selects all customers with a
CustomerName that does NOT start with "a":
CUSTOME
R
SELECT * FROM
Customers
WHERE CustomerName
NOT LIKE 'a%';
Structured Query Language (SQL)- Simple
Query--Set operations
NOTE:
1.The fields to be used in both the select
statements must be in same order, same
number and same data type.
2.The Union clause produces distinct values in
the result set, to fetch the duplicate values too
Structured Query Language (SQL)-
Simple Query--Set operations
Basic Syntax:
SELECT column_name(s)
FROM table1
UNION
SELECT column_name(s)
FROM table2;
Resultant set consists of distinct values.
SELECT column_name(s)
FROM table1
UNION ALL
SELECT column_name(s)
FROM table2;
Resultant set consists of duplicate values too .
Structured Query Language (SQL)-
Simple Query--Set operations
Structured Query Language (SQL)-
Simple Query--Set operations
MINUS
Minus operator displays the rows which are present in
the Example:-
first query but absent in the second query, with no
duplicates and data arranged in ascending order by
SELECT JOB_ID FROM employees WHERE
default.
DEPARTMENT_ID = 10
MINUS
SELECT JOB_ID FROM employees WHERE
DEPARTMENT_ID = 20;
Structured Query Language (SQL)
Syntax
Simple query example
Simple query –string operation
Simple Query--Set operations
Simple Query--Arithmetic Operation
Structured Query Language (SQL)-Simple Query--
Arithmetic Operation
BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Structured Query Language (SQL)-Simple Query--
Arithmetic Operation
Example1:-selects all products with a price
BETWEEN 10 and 20:
Ssn Salary
123456 33000
789
333445 44000
555
UPDATE 999887 25000
777
EMPLOYEE
SET Salary = 987654 43000
321
Salary * 1.1
666884 41800
WHERE Dno
Aggregate Functions
Aggregate Functions
These functions return a single value after
performing calculations on a group of values.
Following are some of the frequently used Aggregate
functions.
AVG() Function
Average returns average value after calculating it
from values in a numeric column.
Its general syntax is,
FIRST() Function
First function returns first value of a selected column
Aggregate Functions
LAST() Function
LAST function returns the return last value of the
selected column.
MAX() Function
MAX function returns maximum value from
selected column of the table.
Syntax of MAX function is,
SELECT MAX(column_name) from table-
name;
MIN() Function
MIN function returns minimum value from a
selected column of the table.
Syntax for MIN function is
SELECT MIN(column_name) from table-name;
SUM() Function
SUM function returns total sum of a selected
columns numeric values.
Syntax for SUM is,
SELECT SUM(column_name) from table-name;
IN clause usage
AND ,OR operators in where clause
NOT IN Clause
Problem: List products with order quantities
greater than 100.
SELECT ProductName
FROM Product
WHERE Id IN (SELECT ProductId
FROM
OrderItem
WHERE
Quantity > 100)
EXAMPLE-2
Return the details of only those customers
whose order value in the orders table is more
than 5000 dollar
SELECT *
FROM customers
WHERE cust_id IN (SELECT
DISTINCT cust_id
FROM
orders
WHERE
order_value > 5000);
SQL ORDER
Ordering BYResult
the Clause Set
Generally when you use the SELECT statement to fetch data from a
table, the rows in result set are not in any particular order. If you
want your result set in a particular order, you can specify the
ORDER BY clause at the end of the statement which tells the
server how to sort the data returned by the query. The default
sorting order is ascending.
Syntax
The ORDER BY clause is used to sort the data returned by a
query in ascending or descending order. The basic syntax of this
clause can be given with:
Points to Remember:
GROUP BY Clause is utilized with the SELECT statement.
GROUP BY aggregates the results on the basis of
selected column: COUNT, MAX, MIN, SUM, AVG, etc.
GROUP BY returns only one result per group of data.
GROUP BY Clause always follows the WHERE Clause.
GROUP BY Clause always precedes the ORDER BY
GROUP BY Clause
Ex:-Table is grouped based on the DeptID column and
Salary is aggregated department-wise.
The SQL GROUP BY Statement
Syntax:-
SELECT column1,function_name(column2)
FROM table_name
WHERE condition
GROUP BY column1, column2
ORDER BY column1, column2;
Syntax
ECT column_name(s)
M table_name
ERE column_name operator ALL
LECT column_name FROM table_name WHERE condition);
EXAMPLE 1:-lists the product names if it finds ANY
records in the OrderDetails table that quantity = 10
EXAMPLE 2:-lists the product names if ALL the records
in the OrderDetails table has quantity = 10
SQL - Alias Syntax
Syntax
DROP VIEW view_n
ame;
Example:
If we want to delete the View
MarksView, we can do this as: