You are on page 1of 74

SQL

UNIT – II
RDBMS
 RDBMS stands for Relational Database Management
System.
 It is the basis for SQL, and for all modern database
systems.
 MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.

 The data will be stored in database objects called tables.


 A table is a collection of related data entries and it consists
of columns and rows.
 The relational Model concerned with three aspects of data:
data structure, data integrity, and data
manipulation.
RDBMS TERMINOLOGY
Formal relational term Informal equivalent(s)

Relation Table

Tuple Row, record

Cardinality Number of rows

Attribute Column, field

Degree Number of columns

Primary Key Unique identifier

Domain Set of legal values


INTRODUCTION TO SQL

 SQL stands for Structured Query Language

 It is used to access and manipulate the databases

 SQL became a standard of the American National

Standards Institute (ANSI) in 1986, and of the

International Organization for Standardization (ISO)

in 1987
PURPOSE OF USING SQL
SQL can
 Execute queries against a database
 Retrieve data from a database
 Insert records in a database
 Update records in a database
 Delete records from a database
 Create new databases
 Create new tables in a database
 Create stored procedures in a database
 Create views in a database
 Set permissions on tables, procedures, and views
FEATURES OF SQL
 High Performance.

 High Availability.

 Scalability and Flexibility

 Robust Transactional Support.

 High Security.

 Comprehensive Application Development.

 Management Ease.

 Open Source.
TYPES OF SQL COMMANDS
1) Data definition language:- used to create, alter and
delete the database objects.
Commands : CREATE, ALTER and DROP
Data Definition Statements:

 CREATE TABLE
 CREATE VIEW
 CREATE INDEX
 ALTER TABLE
 DROP TABLE
 DROP VIEW
 DROP INDEX
TYPES OF SQL COMMANDS CONT…
2. Data Manipulation Language:- lets user can insert, delete
or modify the data in the database.

Data manipulation statements:


 INSERT
 UPDATE
 DELETE

3. Data Query Language:- enables the user to query one or


more table to get the information they want.

Data Query statement:


 SELECT
TYPES OF SQL COMMANDS CONT…

4. Data Control Language:- control the user access to


the database objects.

DCL Commands:
 GRANT
 REVOKE
5. Data Administration Statements:- user to perform
audits and analysis on operation within the database.

Data Administration commands:


START AUDIT
STOP AUDIT
TYPES OF SQL COMMANDS CONT…

6. Transaction Control Statements:- which manage all


the changes made by the DML statements.

Transaction Control Statements:

 COMMIT

 ROLLBACK

 SAVEPOINT

 SET TRANSACTION
CREATING TABLE
 Tables are basic building blocks in any relational
database management system.

 They contains rows and columns of your data.

Syntax:

CREATE TABLE table_name


(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....
);
SELECT STATEMENT
 The SELECT statement is used to select data from a
database.
 The result is stored in a result table, called the result-set.
Syntax:

SELECT column_name,column_name
FROM table_name;

Note: If we need to select all the columns, use * symbol instead


of giving all the column names.
For example:

CREATE TABLE BOOK


(
ISBN CHAR(10) NOT NULL,
TITLE CHAR(30) NOT NULL,
Table  AUTHOR CHAR(30) NOT NULL,
PUBLISHER CHAR(30) NOT
NULL,
YEAR INTEGER NOT NULL,
PRICE INTEGER NOT NULL,
PRIMARY KEY (ISBN)
);

Select  SELECT * FROM Customers;


WORKING EXAMPLE
Program coding:

SQL> create table emp


(
empno number(10),
empname varchar(10),
designation varchar(10),
salary number(10),
bonus number(10)
);
Table created.

SQL>select * from emp;


WORKING EXAMPLE

Output:

EMPNO EMPNAME DESIGNATION SALARY BONUS


------------------------------------------------------------------------------------
“INSERT INTO“- STATEMENT
 The INSERT INTO statement is used to insert new records in a
table.
Syntax:

INSERT INTO table_name


VALUES(&column_name1,&column
-name2,……,&coulmn_nameN);

INSERT INTO table_name


(column1,column2,column3,...)
VALUES (value1,value2,value3,...);

Note: Single quotes should be used for string values before and after
the column_name. Eg: ‘&name’
For Example:

INSERT INTO Flight033


1st Method  VALUES('&flight_no','&flight_name',&a_seat,&
b_seat,&c_seat);

INSERT INTO Customers


(CustomerName, City, Country)
2nd Method  VALUES ('Cardinal', 'Stavanger',
'Norway');
WORKING EXAMPLE
Program Coding:

Insert into values(&empno, ’&empname’, ‘&designation’, &salary, &bonus);

Enter value for empno: 10678

Enter value for empname: malika

Enter value for designation: system analystic

Enter value for salary: 25000

Enter value for bonus: 300

old 1: insert into emp values(&empno,‘&empname',’&designation’,&salary,&bonus)

new 1: insert into emp values(10678,’MALIKA‘,’SYSTEM


ANALYSTIC’,25000,300)

1 row created.

SQL>select * from emp;


WORKING EXAMPLE
Output:

EMPNO EMPNAME DESIGNATION SALARY BONUS


------------------------------------------------------------------------------------
10678 MALIKA SYSTEM ANALYTIC 25000 300

Note: If we need to add more records, put slash symbol ( / )


after the SQL> statement.
Eg: SQL>/
We can add any number of records. At last we can give the
”Select” statement.
VIEW - STATEMENT
 A view is a virtual table based on the result-set of an
SQL statement.

 A view contains rows and columns, just like a real table.


The fields in a view are fields from one or more tables in
the database.

Syntax:

CREATE VIEW view-name (COLUMN_NAME1,


COLUMN_NAME2,……) FROM table_name [WITH
CHECK OPTION];
For example:

CREATE VIEW BOOKV


(ISBN, TITLE, PUBLISHER, YEAR,
PRICE) AS
SELECT
ISBN, TITLE, PUBLISHER, YEAR, PRICE
FROM BOOK
WHERE YEAR IN (1993,1997);
WORKING EXAMPLE
Actual table:

EMPNO EMPNAME DESIGNATION SALARY BONUS


------------------------------------------------------------------------------------
10678 MALIKA SYSTEM ANALYTIC 25000 300
10679 MALAR SUPPORTER 15000 150
21367 BALU COMPUTER PROGRAMMER 15600 250
45768 BELLU MANAGER 35000 500
67897 ULLU TEAM LEADER 20000 260

Program coding:
SQL>CREATE VIEW empdet AS SELECT * FROM emp;
view created
0.09 seconds
SQL> Select * from empdet;
OUTPUT
EMPNO EMPNAME DESIGNATION SALARY BONUS
------------------------------------------------------------------------------------
10678 MALIKA SYSTEM ANALYTIC 25000 300
10679 MALAR SUPPORTER 15000 150
21367 BALU COMPUTER PROGRAMMER 15600 250
45768 BELLU MANAGER 35000 500
67897 ULLU TEAM LEADER 20000 260

Note: we can create the view using where clause also.


Eq:
CREATE VIEW agentview AS SELECT agent_code,agent_name,wor
king_area FROM agents WHERE working_area='Bangalore';
WHERE CLAUSE

 The SQL WHERE clause is used to specify a condition


while fetching the data from single table or joining
with multiple tables.

 Also condition can be used in the where clause, like >,


<, =, LIKE, NOT, etc.

Syntax:

SELECT column1, column2, columnN FROM


table_name WHERE [condition];
FOR EXAMPLE

SQL> SELECT ID, NAME,


SALARY FROM CUSTOMERS
WHERE
SALARY > 2000;
WORKING EXAMPLE
Actual table:

EMPNO EMPNAME DESIGNATION SALARY BONUS


------------------------------------------------------------------------------------
10678 MALIKA SYSTEM ANALYTIC 25000 300
10679 MALAR SUPPORTER 15000 150
21367 BALU COMPUTER PROGRAMMER 15600 250
45768 BELLU MANAGER 35000 500
67897 ULLU TEAM LEADER 20000 260

Program code:
SQL> SELECT * FROM EMP WHERE BONUS > 300;
OUTPUT

EMPNO EMPNAME DESIGNATION SALARY BONUS


------------------------------------------------------------------------------------
10678 MALIKA SYSTEM ANALYTIC 25000 300
45768 BELLU MANAGER 35000 500
DROP OR DELETE TABLE
 The SQL DROP TABLE statement is used to remove a
table definition and all data, indexes, triggers, constraints,
and permission specifications for that table.
Syntax:

DROP TABLE table_name;

NOTE: We need to be careful while using this command,


because once a table is deleted then all the information
available in the table would also be lost forever.
FOR EXAMPLE

DROP TABLE CUSTOMERS;


WORKING EXAMPLE
Actual table name “emp”:

EMPNO EMPNAME DESIGNATION SALARY BONUS


------------------------------------------------------------------------------------
10678 MALIKA SYSTEM ANALYTIC 25000 300
10679 MALAR SUPPORTER 15000 150
21367 BALU PROGRAMMER 15600 250
45768 BELLU MANAGER 35000 500
67897 ULLU TEAM LEADER 20000 260

Program coding:

SQL>DROP TABLE emp;


OUTPUT

Query OK, 0 rows affected (0.01 sec)

Note :If you would try DESC command, then you


would get error as follows.

Coding: SQL> DESC emp;

ERROR 1146 (42S02): Table 'TEST.CUSTOMERS' doesn't exist


AND OPERATOR
 The AND operator allows the existence of multiple
conditions in an SQL statement's WHERE clause.

Syntax

SELECT column1, column2, columnN FROM


table_name WHERE [condition1] AND
[condition2]...AND [conditionN];
FOR EXAMPLE

SELECT ID, NAME, SALARY FROM


CUSTOMERS WHERE SALARY > 2000 AND
age < 25;
WORKING EXAMPLE
Actual table name “emp”:

EMPNO EMPNAME DESIGNATION SALARY BONUS


------------------------------------------------------------------------------------
10678 MALIKA SYSTEM ANALYTIC 25000 300
10679 MALAR SUPPORTER 15000 150
21367 BALU COMPUTER PROGRAMMER 15600 250
45768 BELLU MANAGER 35000 500
67897 ULLU TEAM LEADER 20000 260

Program coding:

SQL> SELECT * FROM emp WHERE SALARY > 20000 AND BONUS < 300;
OUTPUT

EMPNO EMPNAME DESIGNATION SALARY BONUS


------------------------------------------------------------------------------------
10678 MALIKA SYSTEM ANALYTIC 25000 300
45768 BELLU MANAGER 35000 500
OR OPERATOR
 The OR operator is used to combine multiple
conditions in an SQL statement's WHERE clause.

Syntax:

SELECT column1, column2, columnN FROM


table_name WHERE [condition1] OR
[condition2]...OR [conditionN]
FOR EXAMPLE

SELECT ID, NAME, SALARY FROM


CUSTOMERS WHERE SALARY > 2000
OR age < 25;
WORKING EXAMPLE
Actual table name “emp”:

EMPNO EMPNAME DESIGNATION SALARY BONUS


------------------------------------------------------------------------------------
10678 MALIKA SYSTEM ANALYTIC 25000 300
10679 MALAR SUPPORTER 15000 150
21367 BALU COMPUTER PROGRAMMER 15600 250
45768 BELLU MANAGER 35000 500
67897 ULLU TEAM LEADER 20000 260

Program coding:

SQL> SELECT * FROM emp WHERE SALARY < 20000 OR BONUS < 300;
OUTPUT

EMPNO EMPNAME DESIGNATION SALARY BONUS


------------------------------------------------------------------------------------
10678 MALIKA SYSTEM ANALYTIC 25000 300
10679 MALAR SUPPORTER 15000 150
21367 BALU COMPUTER PROGRAMMER 15600 250
67897 ULLU TEAM LEADER 20000 260
UPDATE QUERY

 The SQL UPDATE Query is used to modify the


existing records in a table.

 Use WHERE clause with UPDATE query to update


selected rows otherwise all the rows would be affected.

Syntax:

UPDATE table_name SET column1 = value1,


column2 = value2...., columnN = valueN WHERE
[condition];
FOR EXAMPLE

UPDATE customers SET address = 'pune'


WHERE id = 6;
WORKING EXAMPLE
Actual table name “ emp”:
EMPNO EMPNAME DESIGNATION SALARY BONUS
------------------------------------------------------------------------------------
10678 MALIKA SYSTEM ANALYTIC 25000 300
10679 MALAR SUPPORTER 15000 150
21367 BALU COMPUTER PROGRAMMER 15600 250
45768 BELLU MANAGER 35000 500
67897 ULLU TEAM LEADER 20000 260
Program coding:
SQL > UPDATE emp SET designation=‘Team leader’ WHERE empno=45768;
OUTPUT
EMPNO EMPNAME DESIGNATION SALARY BONUS
------------------------------------------------------------------------------------
10678 MALIKA SYSTEM ANALYTIC 25000 300
10679 MALAR SUPPORTER 15000 150
21367 BALU COMPUTER PROGRAMMER 15600 250
45768 BELLU TEAM LEADER 35000 500
67897 ULLU TEAM LEADER 20000 260
DELETE QUERY

 The SQL DELETE Query is used to delete the


existing records from a table.

 Use WHERE clause with DELETE query to delete


selected rows, otherwise all the records would be
deleted.

Syntax:

DELETE FROM table_name WHERE [condition];


FOR EXAMPLE

DELETE FROM CUSTOMERS WHERE ID = 6;


WORKING EXAMPLE

Actual table name “emp”:


EMPNO EMPNAME DESIGNATION SALARY BONUS
------------------------------------------------------------------------------------
10678 MALIKA SYSTEM ANALYTIC 25000 300
10679 MALAR SUPPORTER 15000 150
21367 BALU COMPUTER PROGRAMMER 15600 250
45768 BELLU MANAGER 35000 500
67897 ULLU TEAM LEADER 20000 260
Program coding:
SQL > DELETE FROM emp WHERE empno=21367;
OUTPUT
EMPNO EMPNAME DESIGNATION SALARY BONUS
------------------------------------------------------------------------------------
10678 MALIKA SYSTEM ANALYTIC 25000 300
10679 MALAR SUPPORTER 15000 150
45768 BELLU MANAGER 35000 500
67897 ULLU TEAM LEADER 20000 260
LIKE CLAUSE
 The SQL LIKE clause is used to compare a value to similar
values using wildcard operators.
 There are two wildcards used in conjunction with the LIKE
operator:
 The percent sign (%)
 The underscore (_)
 The percent sign represents zero, one, or multiple
characters.
 The underscore represents a single number or character.

Note: The symbols can be used in combinations.


Syntax:

SELECT FROM table_name WHERE column LIKE


'XXXX%'
Or
SELECT FROM table_name WHERE column LIKE
'%XXXX%'
or
SELECT FROM table_name WHERE column LIKE 'XXXX_'
or
SELECT FROM table_name WHERE column LIKE '_XXXX'
Or
SELECT FROM table_name WHERE column LIKE
'_XXXX_'
FOR EXAMPLE

Statement Description

WHERE SALARY LIKE '200%' Finds any values that start with 200

Finds any values that have 200 in any


WHERE SALARY LIKE '%200%'
position
Finds any values that have 00 in the
WHERE SALARY LIKE '_00%'
second and third positions
Finds any values that start with 2 and
WHERE SALARY LIKE '2_%_%'
are at least 3 characters in length

WHERE SALARY LIKE '%2' Finds any values that end with 2

Finds any values that have a 2 in the


WHERE SALARY LIKE '_2%3'
second position and end with a 3
Finds any values in a five-digit number
WHERE SALARY LIKE '2___3'
that start with 2 and end with 3
WORKING EXAMPLE
Actual table name “emp”:

EMPNO EMPNAME DESIGNATION SALARY BONUS


------------------------------------------------------------------------------------
10678 MALIKA SYSTEM ANALYTIC 25000 300
10679 MALAR SUPPORTER 15000 150
21367 BALU COMPUTER PROGRAMMER 15600 250
45768 BELLU MANAGER 35000 500
67897 ULLU TEAM LEADER 20000 260

Program coding:

SQL > WHERE SALARY LIKE ‘2%'


OUTPUT

EMPNO EMPNAME DESIGNATION SALARY BONUS


------------------------------------------------------------------------------------
10678 MALIKA SYSTEM ANALYTIC 25000 300
67897 ULLU TEAM LEADER 20000 260
ORDER BY
 The SQL ORDER BY clause is used to sort the data
in ascending or descending order, based on one or
more columns.

 Some database sorts query results in ascending order


by default.

Syntax:

SELECT column-list FROM table_name [WHERE condition]


[ORDER BY column1, column2, .. columnN] [ASC | DESC];
FOR EXAMPLE

SELECT * FROM CUSTOMERS ORDER


BY NAME, SALARY;
WORKING EXAMPLE
Actual table name “emp”:

EMPNO EMPNAME DESIGNATION SALARY BONUS


------------------------------------------------------------------------------------
10678 MALIKA SYSTEM ANALYTIC 25000 300
10679 MALAR SUPPORTER 15000 150
21367 BALU COMPUTER PROGRAMMER 15600 250
45768 BELLU MANAGER 35000 500
67897 ULLU TEAM LEADER 20000 260

Program coding:

SQL > SELECT * FROM EMP ORDER BY NAME;


OUTPUT
EMPNO EMPNAME DESIGNATION SALARY BONUS
------------------------------------------------------------------------------------
21367 BALU COMPUTER PROGRAMMER 15600 250
45768 BELLU MANAGER 35000 500
10679 MALAR SUPPORTER 15000 150
10678 MALIKA SYSTEM ANALYTIC 25000 300
67897 ULLU TEAM LEADER 20000 260
DISTINCT KEYWORD
 The SQL DISTINCT keyword is used in conjunction with
SELECT statement to eliminate all the duplicate records and
fetching only unique records.

 There may be a situation when you have multiple duplicate


records in a table. While fetching such records, it makes more
sense to fetch only unique records instead of fetching
duplicate records.

Syntax:

SELECT DISTINCT column1, column2,.....columnN


FROM table_name WHERE [condition];
FOR EXAMPLE

SELECT DISTINCT SALARY


FROM CUSTOMERS ORDER BY
SALARY;
WORKING EXAMPLE
Actual table name “emp”:
EMPNO EMPNAME DESIGNATION SALARY BONUS
------------------------------------------------------------------------------------
10678 MALIKA SYSTEM ANALYTIC 25000 300
10679 MALAR SUPPORTER 15000 150
21367 BALU COMPUTER PROGRAMMER 15600 250
45768 BELLU MANAGER 35000 500
67897 ULLU TEAM LEADER 20000 260
45896 MANJU SYSTEM ANLYSTIC 35000 380
Program coding:
SQL > SELECT DISTINCT SALARY FROM EMP ORDER BY SALARY;
OUTPUT

SALARY
-------------
15000
15600
20000
25000
35000
CONSTRAINS
 Constraints are the rules enforced on data columns on
table.

 Constraints can be defined in two ways

 The constraints can be specified immediately after


the column definition. This is called column-level
definition.

 The constraints can be specified after all the


columns are defined. This is called table-level
definition.
CONSTRAINS CONT…
 NOT NULL Constraint: Ensures that a column cannot have
NULL value.
 DEFAULT Constraint: Provides a default value for a column
when none is specified.
 UNIQUE Constraint: Ensures that all values in a column are
different.
 PRIMARY Key: Uniquely identified each rows/records in a
database table.
 FOREIGN Key: Uniquely identified a rows/records in any another
database table.
 CHECK Constraint: The CHECK constraint ensures that all
values in a column satisfy certain conditions.
 INDEX: Use to create and retrieve data from the database very
quickly.
INTEGRITY CONSTRAINTS
 Integrity Constraints are used to apply business rules for
the database tables.
 The Integrity constraints are,
 Primary key
 Foreign Key
Primary Key:
 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, which may consist of
single or multiple fields.
PRIMARY KEY CONT…
 Syntax:
 Primary key at column level

column name datatype


[CONSTRAINT constraint_name]
PRIMARY KEY

 Primary key at table level

[CONSTRAINT constraint_name]
PRIMARY KEY
(column_name1,column_name2,..)
EXAMPLE
 Primary Key at column level
CREATE TABLE employee
( id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10)
);

 Primary Key at table level


CREATE TABLE employee (
id number(5), NOT NULL,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10),
PRIMARY KEY (id)
);
INTEGRITY CONSTRAINTS CONT…

Foreign Key:

 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.

 The table containing the candidate key is called the


referenced or parent table.
FOREIGN KEY CONT…
 Syntax:
 Foreign key at column level

[CONSTRAINT constraint_name] REFERENCES


Referenced_Table_name(column_name)

 Foreign key at table level

[CONSTRAINT constraint_name] FOREIGN


KEY(column_name) REFERENCES
referenced_table_name(column_name);
EXAMPLE
 Foreign Key at column level
CREATE TABLE order_items
( order_id number(5) CONSTRAINT od_id_pk
PRIMARY KEY,
product_id number(5) CONSTRAINT pd_id_fk
REFERENCES,
product(product_id),
product_name char(20),
supplier_name char(20),
unit_price number(10)
);

 Foreign Key at table level

CREATE TABLE order_items


( order_id number(5) ,
product_id number(5),
product_name char(20),
unit_price number(10)
CONSTRAINT pd_id_fk FOREIGN KEY(product_id)
REFERENCES product(product_id)
);
GROUP BY
 The SQL GROUP BY clause is used in collaboration
with the SELECT statement to arrange identical data
into groups.

Syntax:

SELECT column1, column2 FROM


table_name WHERE [ conditions ] GROUP
BY column1, column2 ORDER BY column1,
column2;
FOR EXAMPLE:

SELECT NAME, SUM(SALARY) FROM


CUSTOMERS GROUP BY NAME;
WORKING EXAMPLE
Actual table name “emp”:
EMPNO EMPNAME DESIGNATION SALARY BONUS
------------------------------------------------------------------------------------
10678 MALIKA SYSTEM ANALYTIC 25000 300
10679 MALAR SUPPORTER 15000 150
21367 BALU COMPUTER PROGRAMMER 15600 250
45768 BELLU MANAGER 35000 500
67897 ULLU TEAM LEADER 20000 260
Program coding:
SQL> Select Name, Sum(salary) from emp groupby name;
OUTPUT

EMPNAME SALARY
---------------- --------------
BALU 15600
BELLU 35000
MALAR 15000
MALIKA 25000
ULLU 20000
HAVING CLAUSE

 The HAVING clause was added to SQL because


the WHERE keyword could not be used with
aggregate functions.

 Syntax:

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
EXAMPLE
 The SQL statement lists the number of customers in
each country. Only include countries with more than
5 customers:

SELECT COUNT(CustomerID), Country


FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;

 Reference Link:
https://www.w3schools.com/sql/trysql.asp?filename=tr
ysql_select_having

You might also like