0% found this document useful (0 votes)
3 views

DBMS Unit-II (1)

The document provides an overview of SQL commands, focusing on the 'Create Database' statement and its syntax, as well as various SQL command types including DDL, DML, and aggregate functions. It explains how to create, modify, and delete databases and tables, along with examples of SQL queries for data manipulation. Additionally, it covers key concepts such as primary keys, unique keys, constraints, and the use of operators like BETWEEN and LIKE.

Uploaded by

helper bisht
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

DBMS Unit-II (1)

The document provides an overview of SQL commands, focusing on the 'Create Database' statement and its syntax, as well as various SQL command types including DDL, DML, and aggregate functions. It explains how to create, modify, and delete databases and tables, along with examples of SQL queries for data manipulation. Additionally, it covers key concepts such as primary keys, unique keys, constraints, and the use of operators like BETWEEN and LIKE.

Uploaded by

helper bisht
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 79

SQL Create Database

In SQL, the 'Create Database' statement is a first step for storing the structured data in the database.
The database developers and the users use this statement in SQL for creating the new database in the database
systems. It creates the database with the name which has been specified in the Create Database statement.

Syntax

CREATE DATABASE Database_Name;

In this syntax, Database_Name specifies the name of the database which we want to create in the system. We
have to type the database name in query just after the 'Create Database' keyword.

Example

CREATE DATABASE Student ;

When this query is executed successfully, then it will show the following output:
Database created successfully

We can also verify that your database is created in SQL or not by using the following query:

SHOW DATABASE ;
Following are the most important points which are required to learn while creating a database:
 The database we want to create should be a simple and unique name, which can be easily identified.
 Database name should be no more than 128 characters.
SQL does not allow developers to create the database with the existing database name. Suppose if you want to create
another Student database in the same database system, then the Create Database statement will show the following error in
the output:
Can't create database 'Student'; database exists
So, firstly you have to delete the existing database by using the Drop Statement. You can also replace the existing database
with the help of Replace keyword.
If you want to replace the existing Student database, then you have to type the following SQL query:

CREATE OR REPLACE DATABASE Student ;


SQL Commands
• SQL commands are instructions. It is used to communicate with the database. It is also used to perform specific
tasks, functions, and queries of data.

• SQL can perform various tasks like create a table, add data to tables, drop the table, modify the table, set
permission for users.

Types of SQL Commands


There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.
1. Data Definition Language (DDL)
 DDL changes the structure of the table like creating a table, deleting a table, altering a table, etc.
 All the command of DDL are auto-committed that means it permanently save all the changes in the database.

Here are some commands that come under DDL:

 CREATE
 ALTER
 DROP
 TRUNCATE

a. 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 VARCHAR2(20), Email VARCHAR2(100), DOB DATE);


b. 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;

To modify existing column in the table:

ALTER TABLE table_name MODIFY(column_definitions....);

Example:

ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));

ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));


c. DROP: It is used to delete both the structure and record stored in the table.

Syntax

DROP TABLE table_name;

Example

DROP TABLE EMPLOYEE;

d. 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;


2. Data Manipulation Language

 DML commands are used to modify the database. It is responsible for all form of changes in the database.
 The command of DML is not auto-committed that means it can't permanently save all the changes in the
database. They can be rollback.
Here are some commands that come under DML:
 INSERT
 UPDATE
 DELETE

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);
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]

For example:

UPDATE students SET emp_dept= ’Account' WHERE emp_id = ’123’

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

Syntax:

DELETE FROM table_name [WHERE condition];

For example:

DELETE FROM emp_info WHERE emp_id=‘123’;


SELECT Statement

The SELECT statement in MySQL is used to fetch data from one or more tables. We can retrieve
records of all fields or specified fields that match specified criteria using this statement.

Syntax

SELECT * FROM table_name1 [WHERE condition]


or
SELECT field_name1, field_name 2,... field_nameN FROM table_name1 [WHERE condition]
Practical - 1
CREATE TABLE stud_info
(
RollNo number(10),
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
**************************************************************************
Desc stud_info;

**************************************************************************
Alter Command
a. Add b. Modify
**************************************************************************

INSERT INTO stud_info


(RollNo, LastName, FirstName, Address, City)
VALUES (1234567890, ’xyz', ’abc’, ’Karol Bagh', ’New Delhi’);

*******************************************************************
*
Select * from stud_info;
UPDATE stud_info
SET LastName = ’pqr’, FirstName= ’efg'
WHERE RollNo = 1234567890;

*****************************************************************

DELETE FROM stud_info WHERE RollNo = 1234567890;

*****************************************************************

Rollback;

***********************************************************************

Commit;

***********************************************************************

TRUNCATE TABLE stud_info ;


Comparison DELETE TRUNCATE
Basis
Definition The delete statement is used to remove single or The truncate command removes the complete data from an
multiple records from an existing table depending existing table but not the table itself. It preserves the table
on the specified condition. structure or schema.

Language It is a DML (Data Manipulation Language) It is a DDL (Data Definition Language) command.
command.
WHERE It can use the WHERE clause to filter any specific It does not use the WHERE clause to filter records from the
row or data from the table. table.
Permission We need to have DELETE permission to use this We need to have ALTER permission to use this command.
command.
Working This command eliminates records one by one. This command deletes the entire data page containing the
records.
Lock It will lock the row before deletion. It will lock the data page before deletion.
Table This command does not reset the table identity It always resets the table identity.
Identity because it only deletes the data.
Transactio It maintains transaction logs for each deleted It does not maintain transaction logs for each deleted data
n record. page.
Speed Its speed is slow because it maintained the log. Its execution is fast because it deleted entire data at a time
without maintaining transaction logs.
Trigger This command can also activate the trigger applied This command does not activate the triggers applied on the
on the table and causes them to fire. table to fire.
Restore It allows us to restore the deleted data by using the We cannot restore the deleted data after using executing this
COMMIT or ROLLBACK statement. command.
Indexed It can be used with indexed views. It cannot be used with indexed views.
view
Space The DELETE statement occupies more transaction The TRUNCATE statement occupies less transaction space
space than truncate because it maintains a log for because it maintains a transaction log for the entire data page
BETWEEN Operator

The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.

Ex.- SELECT * FROM Products WHERE Price BETWEEN 10 AND 20;

NOT BETWEEN Operator

To display the products outside the range of the previous example, use NOT BETWEEN:

Ex.- SELECT * FROM Products WHERE Price NOT BETWEEN 10 AND 20;

IN Operator

SELECT * FROM Customers WHERE Country IN ('Germany', 'France', 'UK');

NOT IN Operator

SELECT * FROM Customers WHERE Country NOT IN ('Germany', 'France', 'UK');


SQL statement selects all fields from "Customers" where country is "Germany" AND city is "Berlin":

SELECT * FROM Customers WHERE Country='Germany' AND City='Berlin’;

SQL statement selects all fields from "Customers" where country is "Germany" OR "Spain":

SELECT * FROM Customers WHERE City='Berlin' OR City='München’;

SQL statement selects all fields from "Customers" where country is NOT "Germany":

SELECT * FROM Customers WHERE NOT Country='Germany’;

SQL statement selects all fields from "Customers" where country is "Germany" AND city must be "Berlin" OR "München"

SELECT * FROM Customers WHERE Country='Germany' AND (City='Berlin' OR City='München');


SQL Aggregate Functions

 SQL aggregation function is used to perform the calculations on multiple rows of a single column of a table. It returns a single value.
 It is also used to summarize the data.

Types of SQL Aggregation Function


1. COUNT FUNCTION

 COUNT function is used to Count the number of rows in a database table. It can work on both numeric and non-numeric data types.
 COUNT function uses the COUNT(*) that returns the count of all the rows in a specified table. COUNT(*) considers duplicate and Null.

Ex.- SELECT COUNT(*) FROM PRODUCT_MAST;


SELECT COUNT(*) FROM PRODUCT_MAST WHERE RATE>=20;

2. SUM Function

Sum function is used to calculate the sum of all selected columns. It works on numeric fields only.

Ex. SELECT SUM(COST) FROM PRODUCT_MAST;


SELECT SUM(COST) FROM PRODUCT_MAST WHERE QTY>3;

3. AVG function

The AVG function is used to calculate the average value of the numeric type. AVG function returns the average of all non-Null values.

Ex.- SELECT AVG(COST) FROM PRODUCT_MAST;


4. MAX Function

MAX function is used to find the maximum value of a certain column. This function determines the largest value of all selected values of a
column.

Ex.- SELECT MAX(RATE) FROM PRODUCT_MAST;

5. MIN Function

MIN function is used to find the minimum value of a certain column. This function determines the smallest value of all selected values of a
column.

Ex.- SELECT MIN(RATE) FROM PRODUCT_MAST;


CREATE TABLE Worker (
WORKER_ID NUMBER(5),
FIRST_NAME VARCHAR2(25),
LAST_NAME VARCHAR2(25),
SALARY NUMBER(15),
DEPARTMENT VARCHAR2(25)
);

INSERT INTO Worker


WORKER_ID, FIRST_NAME, LAST_NAME, SALARY, DEPARTMENT)
VALUES

(001, 'Monika‘ , 'Arora‘ , 100000 , 'HR'),

(002, 'Niharika‘ , 'Verma‘ , 80000 , 'Admin'),

(003, 'Vishal‘ , 'Singhal', 300000 , 'HR'),

(004, 'Amitabh‘ , 'Singh‘ , 500000 , 'Admin'),

(005, 'Vivek‘ , 'Bhati‘ , 500000 , 'Admin'),

(006, 'Vipul‘ , 'Diwan‘ , 200000 , 'Account'),

(007, 'Satish‘ , 'Kumar‘ , 75000 , 'Account'),

(008, 'Geetika‘ , 'Chauhan', 90000 , 'Admin');


1. Select * from Worker;

2. Select FIRST_NAME from Worker;

3. Select FIRST_NAME AS WORKER_NAME from Worker;

4. Select upper(FIRST_NAME) from Worker;

5. Select distinct DEPARTMENT from Worker;

6. Select * from Worker order by FIRST_NAME asc;

7. Select * from Worker order by DEPARTMENT desc;

8. Select * from Worker order by FIRST_NAME asc, DEPARTMENT desc;

9. Select * from Worker where FIRST_NAME in ('Vipul','Satish');

10.Select * from Worker where FIRST_NAME not in ('Vipul','Satish');

11.Select * from Worker where SALARY BETWEEN 100000 and 500000;

12.Select * from Worker where SALARY NOT BETWEEN 100000 and 500000;
SQL PRIMARY KEY
A primary key is a field in a table which uniquely identifies each row/record in a database table.
Primary keys must contain unique values. A primary key column cannot have NULL values.

A table can have only one primary key, which may consist of single or multiple fields. When multiple
fields are used as a primary key, they are called a composite key.

If a table has a primary key defined on any field, then you cannot have two records having the same
value of that field.

Points to remember for primary key:

 Primary key enforces the entity integrity of the table.


 Primary key always has unique data.
 A primary key length cannot be exceeded than 900 bytes.
 A primary key cannot have null value.
 There can be no duplicate value for a primary key.
 A table can contain only one primary key constraint.
Ex. –
CREATE TABLE students
(
StudentID number(10) NOT NULL PRIMARY KEY,
LastName varchar2 (255) ,
FirstName varchar2 (255),
Address varchar2 (255),
City varchar2 (255),
)

Or

CREATE TABLE students


(
StudentID number(10) NOT NULL,
LastName varchar (255) ,
FirstName varchar (255),
Address varchar (255),
City varchar (255),
PRIMARY KEY (StudentID)
)

SQL primary key on ALTER TABLE

ALTER TABLE students ADD PRIMARY KEY (StudentID)

DROP a PRIMARY KEY constraint

ALTER TABLE students DROP CONSTRAINT pk_StudentID


What is NOT NULL constraint?

The NOT NULL is a constraint in SQL which does not allow you to insert NULL values in the specified
column.
If any column is defined as a NOT NULL constraint in the table, we cannot insert a new record in the
table without adding the value to the column.

Ex. –
CREATE TABLE students
(
StudentID number(10) NOT NULL ,
LastName varchar2 (255) NOT NULL ,
FirstName varchar2 (255) NOT NULL ,
Address varchar2 (255),
City varchar2 (255),
)
Note - We can define NOT NULL constraint to one or more columns in one SQL table.

Add NOT NULL constraint from the table

ALTER TABLE Table_Name MODIFY Column_Name Datatype [size] NOT NULL;

Delete NOT NULL constraint from the table

ALTER TABLE Table_Name MODIFY Column_Name Datatype [size] NULL;


What is a Unique Key
A unique key in DBMS is used to uniquely identify a tuple in a table and is used to prevent duplicity
of the values in a table.

Role of Unique Key

A unique key is used to remove the duplicity of values in a table. However, the usage of a primary
key is the same, but there is a difference between both keys. A primary key cannot take
a NULL value, but a unique key can have one NULL value as its value.

How Unique Key is different from Primary Key

There are the following difference points that will let us understand the difference between a Unique
key and a Primary key:

 A primary key field can never have a NULL value as its value, whereas a unique key can have one
of its field values as NULL.
 A table cannot have more than one primary key, but a table can have more than one unique key.
 There are different types of relational databases, but in some of these databases, the primary key
can generate a clustered index by default. On the other hand, a unique key is able to generate a
non-clustered index by default.
Ex.-
CREATE TABLE Persons (
ID number(10) NOT NULL UNIQUE,
LastName varchar2(255) NOT NULL,
SQL - CHECK Constraint

The CHECK Constraint enables a condition to check the value being entered into a record. If the
condition evaluates to false, the record violates the constraint and isn't entered the table.

The following program creates a new table called CUSTOMERS and adds five columns. Here, we add a
CHECK with AGE column, so that you cannot have any CUSTOMER who is below 18 years.

CREATE TABLE CUSTOMERS(


ID NUMBER(10) NOT NULL,
NAME VARCHAR2(20) NOT NULL,
AGE NUMBER(3) NOT NULL CHECK (AGE >= 18),
ADDRESS VARCHAR2 (25) ,
SALARY NUMBER (6) );
The SQL LIKE Operator

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards often used in conjunction with the LIKE operator:
 The percent sign (%) represents zero, one, or multiple characters
 The underscore sign (_) represents one, single character

LIKE Operator Description


WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends with "o"
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position
The following SQL statement selects all customers with a CustomerName starting with "a":

SELECT * FROM Customers WHERE CustomerName LIKE 'a%';

The following SQL statement selects all customers with a CustomerName ending with "a":

SELECT * FROM Customers WHERE CustomerName LIKE '%a’;

The following SQL statement selects all customers with a CustomerName that have "r" in the
second position:

SELECT * FROM Customers WHERE CustomerName LIKE '_r%’;

The following SQL statement selects all customers with a ContactName that starts with "a"
and ends with "o":

SELECT * FROM Customers WHERE ContactName LIKE 'a%o';


1. Select the detail of the employee whose name start with P.

select * from employee where empname like 'p%’

2. How many candidate take salary more than 5000.

select count(salary) as count from employee where salary>5000

3. Select the detail of employee whose emailId is in gmail.

select * from employee where emailid like '%@gmail.com’

4. Select the details of the employee who work either for department E-104
or E-102.

select * from employee where department='E-102' or department='E-104’


or select * from employee where department in ('E-102','E-104')

5. List name of all employees whose name ends with a.

select * from employee where empname like '%a'


Candidate Key in DBMS
A candidate key is a part of a key known as Super Key where the super key is the super set of all
those attributes that can uniquely identify a table.

What is a Candidate Key


A candidate key is a subset of a super key set where the key which contains no redundant attribute
is none other than a Candidate Key. In order to select the candidate keys from the set of super key,
we need to look at the super key set.

Role of a Candidate Key


The role of a candidate key is to identify a table row or column uniquely. Also, the value of a
candidate key cannot be Null. The description of a candidate key is "no redundant attributes" and
being a "minimal representation of a tuple," according to the Experts.

How a Candidate key is different from a Primary Key


Although the purpose of both candidate and the primary key is the same, that is to uniquely identify
the tuples, and then also they are different from each other. It is because, in a table, we can have
one or more than one candidate key, but we can create only one primary key for a table. Thus, from
the number of obtained candidate keys, we can identify the appropriate primary key. However, if
there is only one candidate key in a table, then it can be considered for both key constraints.
Now, from these sets of super keys, we can conclude the candidate keys. In order to pick up the
candidate keys, the best way is to analyze and form the primary keys as much as we can. So, we
need to identify those sets from the super key sets that alone can identify the whole table, or we can
say the other attributes of the table. Thus, the result is:

All these are the candidate keys and from which we can pick the most appropriate attribute that
can easily identify all records of the table, which will be described as the Primary key.
Alternate Key in SQL

Alternate Key or Secondary Key is the key that has not been selected to be the primary key, but are
candidate keys. A candidate key not selected as a primary key is called alternate or secondary key.
Candidate key is an attribute or set of attributes that you can consider as a Primary key.
If a table has more than one candidate key, one of them will become the primary key and rest of all
are called alternate keys.
Super Key in DBMS

We can define a super key as a set of those keys that identify a row or a tuple uniquely. The word
super denotes the superiority of a key. Thus, a super key is the superset of a key known as
a Candidate key . It means a candidate key is obtained from a super key only.

Here, we will discuss about the super key, i.e., what is the role of a super key, how to use it, and will
be looking at some practical examples that will help us to understand it in a better way.

Role of Super Key

The role of the super key is simply to identify the tuples of the specified table in the database. It is
the superset where the candidate key is a part of the super key only. So, all those attributes in a table
that is capable of identifying the other attributes of the table in a unique manner are all super keys.
Difference between Candidate Key and Super Key

Super Key Candidate Key


It is the superset of all such attributes that can It is the subset or the part of the Super key.
uniquely identify the table.

It is not at all compulsory that all super keys are On the other hand, all candidate keys are super
candidate keys. keys.
The super key attribute can be NULL, which means An attribute holding a candidate key can never be
its values can be null. NULL, which means its values cannot be null.

All the super keys formed together to bring the Similarly, candidate keys are put together to create
candidate keys. primary keys.

The number of super keys formed is always seen Here, Candidate keys are less than super keys.
more.

Note- The super key is the super set, the candidate key is the subset, and the primary key is the
sub-subset of the super key.
What is a DEFAULT constraint
The DEFAULT is a constraint in SQL which allows users to fill a column with the default or fixed
value.
If no value is specified to the column at the time of insertion, then the default value will be added
automatically to that column.
CREATE TABLE Client_Info
(
Ex.-
Client_ID INT PRIMARY KEY,
Client_Name VARCHAR (100),
Client_Gender Varchar(20),
Client_Age INT NOT NULL DEFAULT 18,
Client_Address Varchar (80)
);
Ex.-
CREATE TABLE Doctor_Info
(
Doctor_ID INT PRIMARY KEY,
Doctor_Name VARCHAR (100),
Doctor_Specialist VARCHAR (80) DEFAULT Heart,

Doctor_GenderVarchar (20) DEFAULT Male,


Doctor_Country Varchar (80) DEFAULT Russia
CREATE TABLE Employee (
Emp_ID INT NOT NULL,
Emp_Name VARCHAR2(20) NOT NULL,
Emp_Age INT,
Country VARCHAR2(10) DEFAULT 'INDIA',
DOJ DATE DEFAULT SYSDATE
);

1. INSERT INTO Employee (ID, Name, Age) values(1, 'Anurag', 30);


2. INSERT INTO Employee (ID, Name, Age, Country) values(2, 'Sambit', 35, 'UK');
3. INSERT INTO Employee (ID, Name, Age, DOJ) values(3, 'Priyanka', 30, '25-DEC-17');
4. INSERT INTO Employee (ID, Name, Age, Country, DOJ) values(4, 'Hina', 27, 'USA', '20-OCT-18');
5. INSERT INTO Employee (ID, Name, Age, Country, DOJ) values(5, 'Rohit', 28, 'India', '25-JAN-16');

Statement1: In Statement 1, we have not specified the value for Country and DOJ columns, so it will take the default values
i.e. INDIA and Current system date for the Country and DOJ columns.
Statement2: In Statement 2, we have not specified the value for the DOJ column, so it will take the default system date value
for the DOJ column. In the Country column, it will store the given value i.e. UK.
Statement3: In Statement 3, we have not specified the value for the Country column, so it will take the default value i.e.
INDIA for the Country column. In the DOJ column, it will store the given value.
Statement4/5: In Statement 4 and 5, it will not insert the default values as we have specified the values for the Country and
DOJ columns.
Once you execute the INSERT Statements and if you verify the Employee table, then you will get the following
records.

Examples to add Default Constraint using ALTER Table Statement:


In order to understand this, let us, first, create the Student table by executing the following SQL Script without any default constraints.

CREATE TABLE Student (


Id INT NOT NULL,
Name VARCHAR2(20) NOT NULL,
Age INT,
Country VARCHAR2(20)
);

ALTER TABLE Student MODIFY Country DEFAULT ‘INDIA’;


Write an SQL query to fetch “FIRST_NAME” from the Worker table using the alias name
<WORKER_NAME>.

A. SELECT column_name AS alias_name FROM table_name WHERE [condition];

Write an SQL query to fetch “FIRST_NAME” from the Worker table in upper case.

Write an SQL query to fetch unique values of DEPARTMENT from the Worker table.

Write an SQL query to find the employee id whose salary lies in the range of 9000 and
15000.

Write an SQL query to find the maximum, minimum, and average salary of the
employees.

Write an SQL query to fetch the count of employees working in project ‘P1’.

Write an SQL query to fetch all those employees who work on Projects other than P1.
Write an SQL query to fetch all the EmpIds which are present in either of the tables –
‘EmployeeDetails’ and ‘EmployeeSalary’.

A- SELECT EmpId FROM EmployeeDetails UNION SELECT EmpId FROM EmployeeSalary;

Write an SQL query to fetch common records between two tables.

A- SELECT * FROM EmployeeSalary INTERSECT SELECT * FROM ManagerSalary;

Write an SQL query to fetch records that are present in one table but not in another
table.

A- SELECT * FROM EmployeeSalary MINUS SELECT * FROM ManagerSalary;


SQL FOREIGN KEY
In the relational databases, a foreign key is a field or a column that is used to establish a link
between two tables.
In simple words you can say that, a foreign key in one table used to point primary key in another
table.
We have a table Department which contains the information about a department and has DeptNo, DName,
and Location as its columns.

CREATE TABLE Department(


DeptNo int PRIMARY KEY,
DName varchar(50),
Location varchar(50) );

The above query will create a table with DeptNo as the primary key, which will act as a reference table or a
parent table for another table that will contain the foreign key.

Create another table Employee, which will be the child table for the Department table. It contains
the EmpNo, EmpName, Salary, and DeptNo as its fields.

CREATE TABLE Employee(


EmpNo int,
EmpName varchar(50),
DeptNo int,
FOREIGN KEY (DeptNo) REFERENCES Department(DeptNo) );
Child Table

Parent Table
Difference between primary key and foreign key in SQL:

 Primary key cannot be null on the other hand foreign key can be null.
 Primary key is always unique while foreign key can be duplicated.
 Primary key uniquely identify a record in a table while foreign key is a
field in a table that is
primary key in another table.
 There is only one primary key in the table on the other hand we can
have more than one
foreign key in the table.
Roll No (PK) Name Address
1 Rahul Delhi
2 Mohan UP
3 Ram Punjab

Student – Parent Table / Base Table / Referenced Table


Roll No (FK) Course Name Course ID
1 Cyber Security C1
2 AI C2
3 Robotics C3

Course – Child Table / Referencing Table

Operations Parent Table / Referenced Table Child Table / Referencing Table


Insert No Violation May cause Violation
Delete May cause Violation Will Not cause any Violation
Update May cause Violation May cause Violation
MySQL ON DELETE CASCADE
ON DELETE CASCADE constraint is used in MySQL to delete the rows from the child table
automatically, when the rows from the parent table are deleted. If you do not specify cascading
deletes, the default behavior of the database server prevents you from deleting data in a table if
other tables reference it.

PARENT TABLE
CREATE TABLE Employee (
emp_id int(10) PRIMARY KEY ,
name varchar(40) NOT NULL,
birthdate date NOT NULL,
gender varchar(10) NOT NULL,
hire_date date NOT NULL
);

CHILD TABLE
CREATE TABLE Payment (
payment_id int(10) PRIMARY KEY,
emp_id int(10) NOT NULL,
amount float NOT NULL,
payment_date date NOT NULL,
FOREIGN KEY (emp_id) REFERENCES Employee (emp_id) ON DELETE CASCADE
INSERT INTO Employee (emp_id, name, birthdate, gender, hire_date) VALUES
(101, 'Bryan', '1988-08-12', 'M', '2015-08-26'),
(102, 'Joseph', '1978-05-12', 'M', '2014-10-21'),
(103, 'Mike', '1984-10-13', 'M', '2017-10-28'),
(104, 'Daren', '1979-04-11', 'M', '2006-11-01'),
(105, 'Marie', '1990-02-11', 'F', '2018-10-12');

INSERT INTO Payment (payment_id, emp_id, amount, payment_date) VALUES


(301, 101, 1200, '2015-09-15'),
(302, 101, 1200, '2015-09-30'),
(303, 101, 1500, '2015-10-15'),
(304, 101, 1500, '2015-10-30'),
(305, 102, 1800, '2015-09-15'),
(306, 102, 1800, '2015-09-30');

DELETE FROM Employee WHERE emp_id = 102;

The above statement will delete the employee records whose emp_id =
102 and referencing data into the child table.
Introduction to Nested Queries or Sub Query
A Subquery is a query within another SQL query and embedded within the WHERE clause.

Important Rule:

 A subquery can be placed in a number of SQL clauses like WHERE clause, FROM clause, HAVING
clause.

 You can use Subquery with SELECT, UPDATE, INSERT, DELETE statements along with the operators
like =, <, >, >=, <=, IN, BETWEEN, etc.

 A subquery is a query within another query. The outer query is known as the main query, and the
inner query is known as a subquery.

 Subqueries are on the right side of the comparison operator.

 A subquery is enclosed in parentheses.

 In the Subquery, ORDER BY command cannot be used. But GROUP BY command can be used to
perform the same function as ORDER BY command.
1. Subqueries with the Select Statement

SELECT * FROM EMPLOYEE WHERE ID IN (SELECT ID FROM EMPLOYEE WHERE SALARY > 4500);

ID NAME AGE ADDRESS SALARY


1 John 20 US 2000.00
2 Stephan 26 Dubai 1500.00
3 David 27 Bangkok 2000.00
4 Alina 29 UK 6500.00
5 Kathrin 34 Bangalore 8500.00
6 Harry 42 China 4500.00
7 Jackson 25 Mizoram 10000.00

ID NAME AGE ADDRESS SALARY


4 Alina 29 UK 6500.00
5 Kathrin 34 Bangalore 8500.00
7 Jackson 25 Mizoram 10000.00
2. Subqueries with the INSERT Statement

SQL subquery can also be used with the Insert statement. In the insert statement, data returned
from the subquery is used to insert into another table.

Example

Consider a table EMPLOYEE_BKP with similar as EMPLOYEE.

Now use the following syntax to copy the complete EMPLOYEE table into the EMPLOYEE_BKP table.

INSERT INTO EMPLOYEE_BKP SELECT * FROM EMPLOYEE WHERE ID IN (SELECT ID FROM EMPLOYEE);

3. Subqueries with the UPDATE Statement

The subquery of SQL can be used in conjunction with the Update statement. When a subquery is
used with the Update statement, then either single or multiple columns in a table can be updated.

Example
The given example updates the SALARY by .25 times in the EMPLOYEE table for all employee
whose AGE is greater than or equal to 29.

UPDATE EMPLOYEE SET SALARY = SALARY * 0.25 WHERE AGE IN (SELECT AGE FROM
EMPLOYEE WHERE AGE >= 29);
4. Subqueries with the DELETE Statement

Example

The given example deletes the records from the EMPLOYEE table for all EMPLOYEE whose AGE is
greater than or equal to 29.
DELETE FROM EMPLOYEE WHERE AGE IN (SELECT AGE FROM EMPLOYEE WHERE AGE >= 29 );
SQL GROUP BY

In SQL, The Group By statement is used for organizing similar data into groups. The data is further
organized with the help of equivalent function. It means, if different rows in a precise column have
the same values, it will arrange those rows in a group.

 The SELECT statement is used with the GROUP BY clause in the SQL query.
 WHERE clause is placed before the GROUP BY clause in SQL.
 ORDER BY clause is placed after the GROUP BY clause in SQL.
 It is often used with aggregate functions like SUM, COUNT, AVG, MAX, or MIN, which allows us to
perform calculations on the grouped data.
For example, let us suppose you have a table of sales data consisting of date, product, and sales
amount. To calculate the total sales of an organization in an year, the GROUP BY clause can be used
to group the sales of products together. Similarly, you can group the data by date to calculate the
total sales for each day, or by a combination of product and date to calculate the total sales for
each product on each day.
Syntax-
SELECT column_name(s) FROM table_name GROUP BY column_name(s);
GROUP BY with Single Column

When we use the GROUP BY clause with a single column, SQL will place all rows in the table that
have the same value in that particular column into a single record.

S.no Name AGE Salary


1 John 24 25000
2 Nick 22 22000
3 Amara 25 15000
4 Nick 22 22000
5 John 24 25000

SELECT NAME, SUM (SALARY) FROM Employee GROUP BY NAME;

NAME SALARY
John 50000
Nick 44000
Amara 15000
GROUP BY with Multiple Columns

When we use the GROUP BY clause with multiple columns, SQL will place all rows in the table that
have the same values in all of the specified columns into a single group.
SUBJECT YEAR NAME
C language 2 John
C language 2 Ginny
C language 2 Jasmeen
C language 3 Nick
C language 3 Amara
Java 1 Sifa
Java 1 dolly

SELECT SUBJECT, YEAR, Count (*) FROM Student Group BY SUBJECT, YEAR;

SUBJECT YEAR Count


C language 2 3
C language 3 2
Java 1 2
HAVING clause
The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate
functions.
SQL HAVING clause is similar to the WHERE clause; they are both used to filter rows in a table
based on conditions. However, the HAVING clause was included in SQL to filter grouped rows
instead of single rows. These rows are grouped together by the GROUP BY clause, so, the HAVING
clause must always be followed by the GROUP BY clause. It can be used with aggregate functions,
whereas the WHERE clause cannot.
HAVING clause can also contain multiple conditions in it to filter the grouped results. These
conditions are separated Emp_Id Emp_Name like AND,
by various operators Emp_Salary
OR etc. Emp_City
201 Abhay 2000 Goa
202 Ankit 4000 Delhi
203 Bheem 8000 Jaipur
204 Ram 2000 Goa

205 Sumit 5000 Delhi

1 SELECT SUM(Emp_Salary), Emp_City FROM Employee GROUP BY Emp_City;


2 SELECT SUM(Emp_Salary), Emp_City FROM Employee GROUP BY Emp_City HAVING SUM(
Emp_Salary)>5000;
SUM(Emp_Salary) Emp_City
4000 Goa
9000 Delhi
8000 Jaipur

SUM(Emp_Salary) Emp_City
9000 Delhi
8000 Jaipur
Roll_No Name Marks Age
1 Rithik 91 20
2 Kapil 60 19
3 Arun 82 17
4 Ram 92 18
5 Anuj 50 20
6 Suman 88 18
7 Sheetal 57 19
8 Anuj 64 20

SELECT COUNT(Roll_No), Age FROM Student_details GROUP BY Age ;

SELECT COUNT(Roll_No), Age FROM Student_details GROUP BY Age HAVING CO


UNT(Roll_No) >= 2 ;
Count(Roll_No) Age
3 20
2 19
1 17
2 18

Count(Roll_No) Age
3 20
2 19
2 18
Emp_ID Name Emp_Salary Emp_Dept
1001 Anuj 9000 Finance
1002 Saket 4000 HR
1003 Raman 3000 Coding
1004 Renu 6000 Coding
1005 Seenu 5000 HR
1006 Mohan 10000 Marketing
1007 Anaya 4000 Coding
1008 Parul 8000 Finance

1. SELECT MIN(Emp_Salary), Emp_Dept FROM Employee GROUP BY Emp_Dept;


2.
SELECT MIN(Emp_Salary), Emp_Dept FROM Employee GROUP BY Emp_Dept HAVING MIN(E
mp_Salary) > 4000 ;
MIN(Emp_Salary) Emp_Dept
8000 Finance
4000 HR
3000 Coding
10000 Marketing

MIN(Emp_Salary) Emp_Dept
8000 Finance
10000 Marketing
SQL Server Comparison Operator
Index Comparison Operator Description
1) = It specifies equal symbol.
2) <> It specifies not equal symbol.
3) != It specifies not equal symbol.
4) > It specifies greater than symbol.
5) >= It specifies greater than or equal symbol.
6) < It specifies less than symbol.
7) <= It specifies less than or equal symbol.
8) !> It specifies not greater than symbol.
9) !< It specifies not less than symbol.
10) IN ( ) It matches a value in a list.
11) NOT It is used to negate a condition.
12) BETWEEN It is used to specify within a range (inclusive) value.
13) IS NULL It specifies null value.
14) IS NOT NULL It specifies non-null value.
15) LIKE It specifies pattern matching with % and _
16) EXISTS It specifies that the condition is met if subquery returns at
least one row
SQL JOINS

The join clause allows us to retrieve data from two or more related tables into a meaningful
result set. We can join the table using a SELECT statement and a join condition. It indicates how SQL
Server can use data from one table to select rows from another table. In general, tables are related to
each other using foreign key constraints.

In a JOIN query, a condition indicates how two tables are related:

 Choose columns from each table that should be used in the join. A join condition indicates a foreign
key from one table and its corresponding key in the other table.
 Specify the logical operator to compare values from the columns like =, <, or >.
INNER JOIN

The INNER JOIN keyword selects records that have matching values in both tables. An Inner Join
retrieves the intersection of two tables. It compares each row of the first table with each row of the
second table. If the pairs of these rows satisfy the join-predicate, they are joined together. This is a
default join.

The following visual representation explains how INNER JOIN returns the matching records
from table1 and table2:
Table: Student Table: Fee

Output
SELECT Student.admission_no,
Student.first_name,
Student.last_name,
Fee.course,
Fee.amount_paid
FROM Student
INNER JOIN Fee
ON Student.admission_no = Fee.admission_no;
LEFT OUTER JOIN

The LEFT OUTER JOIN retrieves all the records from the left table and matching rows from the right
table. It will return NULL when no matching record is found in the right side table. Since OUTER is an
optional keyword, it is also known as LEFT JOIN.
The below visual representation illustrates the LEFT OUTER JOIN:
Table: Student Table: Fee

Output
SELECT Student.admission_no,
Student.first_name,
Student.last_name,
Fee.course,
Fee.amount_paid
FROM Student
LEFT OUTER JOIN Fee
ON Student.admission_no = Fee.admission_no;
RIGHT OUTER JOIN

The RIGHT OUTER JOIN retrieves all the records from the right-hand table and matched
rows from the left-hand table. It will return NULL when no matching record is found in the left-
hand table. Since OUTER is an optional keyword, it is also known as RIGHT JOIN.
Table: Student Table: Fee

Output
SELECT Student.admission_no,
Student.first_name,
Student.last_name,
Fee.course,
Fee.amount_paid
FROM Student
RIGHT OUTER JOIN Fee
ON Student.admission_no = Fee.admission_no;
FULL OUTER JOIN

The FULL OUTER JOIN in SQL Server returns a result that includes all rows from both tables.
The columns of the right-hand table return NULL when no matching records are found in the left-
hand table. And if no matching records are found in the right-hand table, the left-hand table column
returns NULL.
Table: Student Table: Fee

SELECT Student.admission_no, Output


Student.first_name,
Student.last_name,
Fee.course,
Fee.amount_paid
FROM Student
FULL OUTER JOIN Fee
ON Student.admission_no = Fee.admission_no;
Views in SQL

 Views in SQL are considered as a virtual table. A view also contains rows and columns.
 To create the view, we can select the fields from one or more tables present in the database.
 A view can either have specific rows based on certain condition or all the rows of a table.
 A view is nothing more than a SQL statement that is stored in the database with an associated
name. A view is actually a composition of a table in the form of a predefined SQL query.
 Restrict access to the data in such a way that a user can see and (sometimes) modify exactly
what they need and no more.
 Summarize data from various tables which can be used to generate reports.

Creating View from a single table


Syntax
CREATE VIEW view_name AS SELECT column1, column2..... FROM table_name
WHERE condition;

Example
CREATE VIEW DetailsView AS SELECT NAME, ADDRESS FROM Student_Details WHERE
STU_ID < 4;
Creating View from multiple tables

CREATE VIEW MarksView AS SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Stud


ent_Marks.MARKS
FROM Student_Detail, Student_Mark WHERE Student_Detail.NAME = Student_Marks.NAM
E;

Deleting View
Ex.-
DROP VIEW MarksView;
Deleting Rows into a View
Ex.-
DELETE FROM CUSTOMERS_VIEW WHERE age =
22;
DCL - DATA CONTROL LANGUAGE
The Data Control Language is the sublanguage responsible for the administrative tasks of
controlling the database itself, most notably granting and revoking database permissions
for users.

Grant Privilege
MySQL has a feature that provides many control options to the administrators and users on the
database. MySQL provides GRANT statements to give access rights to a user account.
Use the GRANT statement to give privileges to a specific user or role, or to all users, to perform
actions on database objects. You can also use the GRANT statement to grant a role to a user, to
PUBLIC, or to another role.
Syntax
Parameter Name Descriptions
GRANT privilege_name(s) ON object TO user_account_name;
privilege_name( It specifies the access rights or grant privilege to user accounts. If we want to give
s) multiple privileges, then use a comma operator to separate them.
object It determines the privilege level on which the access rights are being granted. It
means granting privilege to the table; then the object should be the name of the
table.
user_account_n It determines the account name of the user to whom the access rights would be
Privilege Levels

MySQL supports the following privilege levels:

Privilege Syntax Descriptions


Level
Global GRANT ALL It applies to all databases on MySQL server. We need to use *.* syntax for
ON *.* applying global privileges. Here, the user can query data from all databases
TO john@localhost; and tables of the current server.
Databas GRANT ALL It applies to all objects in the current database. We need to use the
e ON mydb.* db_name.* syntax for applying this privilege. Here, a user can query data
TO john@localhost; from all tables in the given database.
Table GRANT DELETE It applies on all columns in a specified table. We need to use
ON mydb.employees db_name.table_name syntax for assigning this privilege. Here, a user can
TO john@localhsot; query data from the given table of the specified database.

Column GRANT SELECT (col1), INSERT (col1, col2), It applies on a single column of a table. Here, we must have to specify the
UPDATE (col2) column(s) name enclosed with parenthesis for each privilege. The user can
ON mydb.mytable select one column, insert values in two columns, and update only one column
TO john@localhost; in the given table.

Stored GRANT EXECUTE It applies to stored routines (procedure and functions). It contains CREATE
Routine ON PROCEDURE mydb.myprocedure ROUTINE, ALTER ROUTINE, EXECUTE, and GRANT OPTION privileges. Here, a
TO john@localhost; user can execute the stored procedure in the current database.

Proxy GRANT PROXY It enables one user to be a proxy for other users.
ON root
TO peter@localhost;
SQL REVOKE statement

Issue REVOKE statements to withdraw privileges. The revoke statement enables system
administrators to revoke privileges and roles to the MySQL user accounts so that they cannot use
the assigned permission on the database in the past.

Syntax

REVOKE privilege_name(s) ON object FROM user_account_name;

Ex.-

GRANT ALL ON mystudentdb.* TO john@localhost;

GRANT SELECT, UPDATE, INSERT ON mystudentdb.* TO john@localhost;

SHOW GRANTS FOR john@localhost;

REVOKE ALL, GRANT OPTION FROM john@localhost;

REVOKE UPDATE, INSERT ON mystudentdb.* FROM john@localhost;


SQL Server Sequence
SQL Server Sequence is used to create a sequence object and its properties can also be specified.

A sequence object can be defined as a user-defined object which is bound to the schema that
generates a numeric values sequence according to the increment value that is defined at the time of
the creation of the sequence.

The numeric values sequence that is generated can be in a descending or ascending order depending
upon an already preset incremental value and it can also be started again (cycle) when it reaches its
termination limit. Unlike identity columns, the sequences are not associated with some particular
tables. In order to get the next value of the sequence generated, the applications can refer to an
object of sequence.

The application controls the relationship between tables and sequences. A sequence can be seen as a
schema-level object which any user can access. Unlike a procedure, a sequence belongs to no user.

How to use Sequence in SQL Server?

Let us take an example for a better understanding. Let us create a table named students having three
columns named studID, rollNo, Name to store the student ID, roll no, and Name of the student
respectively. The command for creating a table in SQL server with the above-mentioned schema will
be:
CREATE TABLE students (
studID varchar(10),
rollNo int,
Name varchar(30)
);
INSERT INTO students(rollNo, Name) VALUES(87459, "Andrew");
INSERT INTO students(rollNo, Name) VALUES(54786, "Samuel");
INSERT INTO students(rollNo, Name) VALUES(22149, "Nirnay");
INSERT INTO students(rollNo, Name) VALUES(94365, "Paul");
INSERT INTO students(rollNo, Name) VALUES(35479, "Casey");
INSERT INTO students(rollNo, Name) VALUES(74566, "Martin");
INSERT INTO students(rollNo, Name) VALUES(10259, "Raphel");

As we can see in the image, we have successfully added seven rows to the students' table and the same can be seen in
the result of the SELECT query.
Now we add data in the studID column using a sequence object. For this, a sequence object needs to be created. The
syntax for the same is:

CREATE SEQUENCE stud_seq AS INT START WITH 101 INCREMENT BY 1;

We have created a sequence object named stud_seq having the initial value as 101 and it gets incremented by 1 where
the value from the sequence object named stud_seq is fetched. For retrieving the next value from the sequence object,
the syntax is:
SQL Server Index
The Index in SQL is a special table used to speed up the searching of the data in the database tables.
It also retrieves a vast amount of data from the tables frequently. The INDEX requires its own space
in the hard disk.

The index concept in SQL is same as the index concept in the novel or a book.

It is the best SQL technique for improving the performance of queries. The drawback of using
indexes is that they slow down the execution time of UPDATE and INSERT statements. But they have
one advantage also as they speed up the execution time of SELECT and WHERE statements.

In SQL, an Index is created on the fields of the tables. We can easily build one or more indexes on a
table. The creation and deletion of the Index do not affect the data of the database.

Why SQL Index?

 SQL Indexes can search the information of the large database quickly.
 This concept is a quick process for those columns, including different values.
 This data structure sorts the data values of columns (fields) either in ascending or descending
order. And then, it assigns the entry for each value.
 Each Index table contains only two columns. The first column is row_id, and the other is indexed-
column.
 When indexes are used with smaller tables, the performance of the index may not be recognized.
Create an INDEX
Syntax - CREATE INDEX Index_Name ON Table_Name ( Column_Name);

Here, Index_Name is the name of that index that we want to create, and Table_Name is the name
of the table on which the index is to be created. The Column_Name represents the name of the
column on which index is to be applied.

If we want to create an index on the combination of two or more columns, then the following syntax
can be used in SQL:

Syntax -
CREATE INDEX Index_Name ON Table_Name ( column_name1, column_name2, ...., column_nameN);
Emp_Id Emp_Name Emp_Salary Emp_City Emp_State
Example for creating
1001 an Index in SQL:
Akshay 20000 Noida U.P
1002 Ram 35000 Jaipur Rajasthan
1003 Shyam 25000 Gurgaon Haryana
1004 Yatin 30000 Lucknow U.P
The following SQL query creates an Index 'Index_state' on the Emp_State column of
the Employee table.

CREATE INDEX index_state ON Employee (Emp_State);

Suppose we want to create an index on the combination of the Emp_city and


the Emp_State column of the above Employee table. For this, we have to use the following query:

CREATE INDEX index_city_State ON Employee (Emp_City, Emp_State);

Create UNIQUE INDEX

Unique Index is the same as the Primary key in SQL. The unique index does not allow selecting
those columns which contain duplicate values. This index is the best way to maintain the data
integrity of the SQL tables.

Syntax for creating the Unique Index is as follows:

CREATE UNIQUE INDEX Index_Name ON Table_Name ( Column_Name);

CREATE UNIQUE INDEX index_salary ON Employee (Emp_Salary);

Remove an INDEX
Stored Procedure in SQL Server

You might also like