You are on page 1of 21

SQL​ is a database computer language designed for the retrieval and

management of data in a relational database. ​SQL​ stands


for ​Structured Query Language

SQL is a standard language for storing, manipulating and retrieving


data in databases.

SQL Commands:

Data Definition Language Commands (DDL)

 The commands are as follows:

▪ CREATE
▪ DROP
▪ ALTER

1 CREATE

This statement is used to create a table or a database.

The ‘CREATE DATABASE’ Statement

As the name suggests, this statement is used to create a database.

Syntax

CREATE DATABASE DatabaseName;

Example

CREATE DATABASE Company;

Create database hospital;

● The ‘CREATE TABLE’ Statement

This statement is used to create a table.

Syntax

CREATE TABLE TableName (


Column1 datatype [constraints],
Column2 datatype [constraints],
Column3 datatype [constraints],
....

ColumnN datatype [constraints]


);
SQL constraints are used to specify rules for the data in a table.​ 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

Example

CREATE TABLE Employee


(
EmployeeID int primary key,
EmployeeName varchar(25) not null,
ContactName varchar(25),
PhoneNumber int unique ,
Address varchar(25),
City varchar(25),
Country varchar(25),
Dept_number number(10) foreign key dept(dept_no)
);

Create table dept ( dept_no number(10) primary key , dept_name


varchar(30) not null , dept_location varchar(40));

Create table Student(USN varchar(8) primary key ,Name


varchar(30) not null ,Date_of_birth date, address varchar(50));

2 DROP

This statement is used to drop an existing table or a database.


This statement is used to drop an existing database. When you use
this statement, complete

The ‘DROP TABLE’ Statement

This statement is used to drop an existing table. When you use this
 statement, complete information present in the table will be lost.

Syntax

DROP TABLE TableName;


Example

1 DROP Table Employee_Info;

The SQL INSERT INTO Statement

The INSERT INTO statement is used to insert new records in a


table.

INSERT INTO Syntax

It is possible to write the INSERT INTO statement in two ways.


The first way specifies both the column names and the values to be
inserted:

If you are adding values for all the columns of the table, you do not
need to specify the column names in the SQL query. However,
make sure the order of the values is in the same order as the
columns in the table.

The INSERT INTO syntax would be as follows:

1 INSERT​ ​INTO​ ​table_name


VALUES​ (​value1​,​ value2,​ ​ value3​, ...);
2 INSERT​ ​INTO​ ​table_name​ (c​olumn1,​ ​ column2​,​ column3​,
...)
VALUES​ (​value1​,​ value2,​ ​ value3​, ...);
Example
INSERT​ ​INTO​ Customers ​VALUES​ (​'91','Cardinal'​, ​'Tom B.
Erichsen'​, ​'Skagen 21'​, ​'Stavanger'​, ​'4006'​, ​'Norway'​);

ALTER TABLE - ADD Column

To add a column in a table, use the following syntax:

ALTER​ ​TABLE​ ​table_name


ADD​ ​column_name datatype;​

The following SQL adds an "Email" column to the "Customers"


table:

Example
ALTER​ ​TABLE​ Customers
ADD​ Email varchar(255);

ALTER​ ​TABLE​ Persons


ADD​ DateOfBirth date;
ALTER TABLE - DROP COLUMN

To delete a column in a table, use the following syntax (notice that


some database systems don't allow deleting a column):

ALTER​ ​TABLE​ ​table_name


DROP​ ​COLUMN​ ​column_name​;

The following SQL deletes the "Email" column from the


"Customers" table:

Example
ALTER​ ​TABLE​ Customers
DROP​ ​COLUMN​ Email;

ALTER TABLE - ALTER/MODIFY COLUMN

To change the data type of a column in a table, use the following


syntax:

ALTER​ ​TABLE​ ​table_name


MODIFY​ ​column_name datatype;​

DROP COLUMN Example

Next, we want to delete the column named "DateOfBirth" in the


"Persons" table.

We use the following SQL statement:

ALTER​ ​TABLE​ Persons


DROP​ ​COLUMN​ DateOfBirth;

The SQL SELECT Statement

The SELECT statement is used to select data from a database.

The data returned is stored in a result table, called the result-set.

SELECT
SELECT​ ​column1,​ ​ column2, ...
FROM​ ​table_name​;

SELECT DISTINCT Syntax


SELECT​ ​DISTINCT​ ​column1​,​ column2, ...
FROM​ ​table_name​;

SELECT column1, column2, columnN

FROM table_name

WHERE [condition]

SELECT ID​,​ NAME​,​ SALARY


FROM CUSTOMERS
WHERE SALARY ​>​ ​2000​;

SELECT ID​,​ NAME​,​ SALARY


FROM CUSTOMERS
WHERE NAME ​=​ ​'Hardik'​;

1. Write a query in SQL to find the salaries of all employees


2. Write a query in SQL to display the details of the employee
BLAZE
3. Write a query in SQL to list all the employees whose
designation is CLERK.

Select * from emp where job=’clerk’;

4. Write a query in SQL to display the unique designations for


the employees.

Select DICTINCT(JOB) from emp;

5. Write a query in SQL to list the emp_name and salary.


SELECT ENAME ,SAL FROM EMP;

6. Write a query in SQL to list the emp_name and salary.


Sort in ascending order by salary

SELECT ENAME,SAL FROM EMP


7. Write a query in SQL to list the emp_no, salary, of all the
employees who belong to dept 10.

SELECT EMPNO, SAL FROM EMP WHERE DEPTNO=10;

8. Write a query in SQL to list the employees who does not


belong to department 20
SELECT * FROM EMP WHERE NOT DEPTNO =20;

9. Write a query in SQL to display the average salaries of


all the employees who works as ANALYST.

SQL AND, OR and NOT Operators


AND Syntax
SELECT​ ​column1​,​ column2, ...
FROM​ ​table_name
WHERE​ ​condition1​ ​AND​ ​condition2​ ​AND​ ​condition3 ...​;

OR Syntax
SELECT​ ​column1​,​ column2, ...
FROM​ ​table_name
WHERE​ ​condition1​ ​OR​ ​condition2​ ​OR​ ​condition3 ...​;

NOT Syntax
SELECT​ ​column1​,​ column2, ...
FROM​ ​table_name
WHERE​ ​NOT​ ​condition​;

SELECT​ * ​FROM​ Customers


WHERE​ Country=​'Germany'​ ​AND​ City=​'Berlin'​;

SELECT​ * ​FROM​ Customers


WHERE​ Country=​'Germany'​ ​OR ​City=​'Berlin'​;

SELECT​ * ​FROM​ Customers


WHERE​ ​NOT​ Country=​'Germany'​;

ORDER BY Syntax
SELECT​ ​column1​,​ column2, ...
FROM​ ​table_name
​ SC​|​DESC​;
ORDER​ ​BY​ ​column1, column2, ... A
SELECT​ * ​FROM​ EMP
ORDER​ ​BY​ salary;

SELECT​ * ​FROM​ Customers


ORDER​ ​BY​ salary ​DESC​;

SELECT​ * ​FROM​ Customers


ORDER​ ​BY​ Country, CustomerName;

SELECT​ * ​FROM​ Customers


ORDER​ ​BY​ Country ​ASC​, CustomerName ​DESC​;

The SQL Aggregate Functions

The MIN() function returns the smallest value of the


selected column.
The MAX() function returns the largest value of the selected
column.
The COUNT() function returns the number of rows that
matches a specified criterion.
The AVG() function returns the average value of a numeric
column.
The SUM() function returns the total sum of a numeric
column.

Example

SELECT​ MIN(​column_name)​ ​ ​FROM​ ​table_name


WHERE​ ​condition​;

SELECT​ ​COUNT​(​column_name)​ ​FROM​ ​table_name;

SELECT​ max(​column_name)​ ​FROM​ ​table_name;

SELECT​ avg(​column_name)​ , sum(​column_name)


FROM​ ​table_name;
Example

Select count(empno) from Emp;

Select count(empno), max(sal), min(sal), Avg(sal) from Emp;

GROUP BY Syntax

The GROUP BY statement groups rows that have the same values
into summary rows, like "find the number of customers in each
country".

The GROUP BY statement is often used with aggregate functions


(COUNT, MAX, MIN, SUM, AVG) to group the result-set by one
or more columns.

SELECT​ ​column_name(s)
FROM​ ​table_name
[WHERE​ ​condition]
[GROUP​ ​BY​ ​column_name(s)]
[ORDER​ ​BY​ ​column_name(s)]

Example1

lists the number of Employes in each department

SELECT COUNT(empno), deptno


FROM Emp
GROUP BY deptno;

Example 2

Total amount of the salary in each department

Select deptno, sum(sal) as totalsalary from Emp

Group by deptno;

or

Select deptno, sum(sal) as totalsalary from Emp

Group by deptno

Order by deptno;
Example 3

Q Total amount of the salary on each employee

Select ename, sum(sal) from Emp

Group by ename

1. Write a query to display the name and salary of employees


earning more than 2850

SQL> Select ename, sal from emp where sal>2850;

2. Write a query to display the name and department number


for employee number 7856
SQL> Select name, deptno from emp where empno=7856
3. Displays employees' name and new salary after the
increment of 1000
SQL> select ename, (sal*1000) from emp ;

4. Write a query to display the name and department number


of all employees in departments 10 and 30 in alphabetical
order by name
Select ename,deptno from emp
Where deptno=10 or deptno=30
Order by ename​;

5. Write a query to display the name and salary of employees


who earned more than 1500 and are in department number
10 or 30
Select ename,sal from emp
Where sal>1500 and deptno in(10,30,40);

6. Write a query in SQL to list the employees whose salaries


are less than 3500
Select ename,sal from emp
Where sal<3500;
7. Write a query in SQL to list all the employees of designation
CLERK in department no 20.
Select * from emp
Where job=’CLERK’ and deptno=20;
8. Write a query in SQL to list the employees who joined
before 1991.
Select * from emp
Where hiredate <(‘1-1-1991’)

Hiredate<1991

9.Write a query in SQL to display the average salaries of all


the employees who works as ANALYST.
Select avg(sal) from emp
Where job=’ANALYST’;

EMP Table

Department Table

9. Write a query in SQL to display deptname and location

10. Write a query in SQL to display ​names, designation and


dept name of all employees
11. Write a query in SQL to list​ of all employess working in
Research department
12. Write a query in SQL to list names designation , empno
and deptno of employees located in NEW YORK

13. Write a query in SQL to list employee names and


SALARIES working in CHICAGO

Select dname,loc from dept

Select e.ename,e.job, e.deptno, d.dname from emp e,dept


d
where e.deptno=d.deptno

Select e.ename,e.job, d.dname from emp e,dept d


where e.deptno=d.deptno and d.dname='RESEARCH'

Select e.ename,e.job,e.empno, d.dname from emp e,


dept d
where e.deptno=d.deptno
and
d.loc='NEW YORK'

The SQL IN Operator

The IN operator allows you to specify multiple values in a WHERE


clause.

The IN operator is a shorthand for multiple OR conditions.

IN Syntax
SELECT​ ​column_name(s)
FROM​ ​table_name
WHERE​ ​column_name​ ​IN​ (​value1,​ ​ value2​, ...);

Find ​all customers that are located in "Germany", "France" or


"UK":

SELECT​ * ​FROM​ Customers


WHERE​ Country ​IN​ (​'Germany'​, ​'France'​, ​'UK'​);

SELECT​ * ​FROM​ Customers


WHERE​ Country =’Germany’ or country=’France’ or
Country=’UK’;
The SQL 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.

BETWEEN Syntax
SELECT​ ​column_name(s)
FROM​ ​table_name
WHERE​ ​column_name ​BETWEEN​ ​value1​ ​AND​ ​value2;

Find​ all products with a price BETWEEN 10 and 20:

SELECT​ * ​FROM​ Products


WHERE​ Price ​BETWEEN​ 10 ​AND​ 20;

SELECT​ * ​FROM​ Emp


WHERE​ Sal ​BETWEEN​ 10000 ​AND​ 25000;

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 represents a single character

SELECT​ ​column1, column2, ...


FROM​ ​table_name
WHERE​ ​columnN​ ​LIKE​ ​pattern;​

Find customers with a CustomerName starting with "a":

SELECT​ * ​FROM​ Customers


WHERE​ CustomerName ​LIKE​ ​'%a'​;

Fnd customers with a CustomerName that have "sri":

SELECT​ * ​FROM​ Customers


WHERE​ CustomerName ​LIKE​ %sri%;
1. Find all customers with a CustomerName
that have "s" in the second position:
Like ‘_s%’
3 Find employee names which starts with "a" and ends with
"o":

Like ‘a%o’

4 Find customers with a CustomerName that does NOT start


with "M":
Not like ‘M%’

The SQL HAVING Clause

The HAVING clause was added to SQL because the WHERE


keyword could not be used with aggregate functions.

HAVING Syntax
SELECT​ ​column_name(s)
FROM​ ​table_name
WHERE​ ​condition
GROUP​ ​BY​ ​column_name(s)
HAVING​ ​condition
ORDER​ ​BY​ ​column_name(s);

The following SQL statement lists the number of customers in each


country. Only include countries with more than 5 customers:

Example
SELECT​ ​COUNT​(CustomerID), Country
FROM​ Customers
GROUP​ ​BY​ Country
HAVING​ ​COUNT​(CustomerID) > 5;

SQL INSERT ,DELETE & UPDATE


The SQL ​UPDATE​ Query is used to modify the existing records in
a table. You can use the WHERE clause with the UPDATE query
to update the selected rows, otherwise all the rows would be
affected.
Syntax
The basic syntax of the UPDATE query with a WHERE clause is
as follows −
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
|​ ID ​|​ NAME ​|​ AGE ​|​ ADDRESS ​|​ SALARY ​|
+----+----------+-----+-----------+----------+
|​ ​1​ ​|​ ​Ramesh​ ​|​ ​32​ ​|​ ​Ahmedabad​ ​|​ ​2000.00​ ​|
|​ ​2​ ​|​ ​Khilan​ ​|​ ​25​ ​|​ ​Delhi​ ​|​ ​1500.00​ ​|
|​ ​3​ ​|​ kaushik ​|​ ​23​ ​|​ ​Kota​ ​|​ ​2000.00​ ​|
|​ ​4​ ​|​ ​Chaitali​ ​|​ ​25​ ​|​ ​Mumbai​ ​|​ ​6500.00​ ​|
|​ ​5​ ​|​ ​Hardik​ ​|​ ​27​ ​| ​|​ ​8500.00​ ​|
|​ ​6​ ​|​ ​Komal​ ​|​ ​22​ ​|​ Pune ​|​ ​4500.00​ ​|
|​ ​7​ ​|​ ​Muffy​ ​|​ ​24​ ​|​ ​Indore​ ​|​ ​10000.00​ ​|

UPDATE CUSTOMERS
SET ADDRESS ​=​ ‘PUNE’
WHERE ID ​=​ 2​;

UPDATE Customers
SET Age=32;

UPDATE CUSTOMERS
SET ADDRESS ​=​ ​'Pune' ,​ SALARY ​=​ ​10000.00, ​;

UPDATE CUSTOMERS
SET ADDRESS ​=​ ​'Pune'​,​ SALARY ​=​ ​15000.00
WHERE ID IN(3,5,6);
UPDATE CUSTOMERS
SET ADDRESS = 'Pune'

Where salary >1500

SQL DELETE

The SQL DELETE Query is used to delete the existing records


from a table.
You can use the WHERE clause with a DELETE query to delete
the selected rows, otherwise all the records would be deleted.
Syntax
The basic syntax of the DELETE query with the WHERE clause is
as follows −
DELETE FROM table_name
WHERE [condition]

DELETE FROM CUSTOMERS


WHERE ID ​=​ ​6​;

DELETE FROM CUSTOMERS​;

DELETE FROM CUSTOMERS


WHERE Address ​=​ ‘DELHI’​;

UPDATE CUSTOMERS_VIEW
SET AGE ​=​ ​35
WHERE name ​=​ ​'Ramesh'​;

VIEWS In SQL

In SQL, 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 real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a
view and present the data as if the data were coming from one
single table.

Create Table Tablename

CREATE​ ​VIEW​ ​view_name​ ​AS


SELECT​ ​column1​, ​column2,​ ...
FROM​ ​table_name
WHERE​ ​condition;​

Consider the CUSTOMERS table having the following records −


+----+----------+-----+-----------+----------+
|​ ID ​|​ NAME ​|​ AGE ​|​ ADDRESS ​|​ SALARY ​|
+----+----------+-----+-----------+----------+
|​ ​1​ ​|​ ​Ramesh​ ​|​ ​32​ ​|​ ​Ahmedabad​ ​|​ ​2000.00​ ​|
|​ ​2​ ​|​ ​Khilan​ ​|​ ​25​ ​|​ ​Delhi​ ​|​ ​1500.00​ ​|
|​ ​3​ ​|​ kaushik ​|​ ​23​ ​|​ ​Kota​ ​|​ ​2000.00​ ​|
|​ ​4​ ​|​ ​Chaitali​ ​|​ ​25​ ​|​ ​Mumbai​ ​|​ ​6500.00​ ​|
|​ ​5​ ​|​ ​Hardik​ ​|​ ​27​ ​| ​|​ ​8500.00​ ​|
|​ ​6​ ​|​ ​Komal​ ​|​ ​22​ ​|​ Pune ​|​ ​4500.00​ ​|
|​ ​7​ ​|​ ​Muffy​ ​|​ ​24​ ​|​ ​Indore​ ​|​ ​10000.00​ ​|

CREATE VIEW CUST_AGE AS SELECT * FROM


CUSTOMERS

WHERE AGE>25;

SELECT * FROM CUST_AGE;

ID ​|​ NAME ​|​ AGE ​|​ ADDRESS ​|​ SALARY ​|


+----+----------+-----+-----------+----------+
|​ ​1​ ​|​ ​Ramesh​ ​|​ ​32​ ​|​ ​Ahmedabad​ ​|​ ​2000.00

|​ ​5​ ​|​ ​Hardik​ ​|​ ​27​ ​| ​|​ ​8500.00​ ​|

CREATE VIEW CUSTOMERS_VIEW AS


SELECT name​,​ age
FROM CUSTOMERS​;
SELECT ​*​ FROM CUSTOMERS_VIEW​;

+----------+-----+
| name | age |
+----------+-----+
| Ramesh | 32 |
| Khilan | 25 |
| kaushik | 23 |
| Chaitali | 25 |
| Hardik | 27 |
| Komal | 22 |
| Muffy | 24 |
+----------+-----+

CREATE​ ​VIEW​ Indian_Cust ​AS


SELECT​ CustomerName, ContactName
FROM​ Customers
WHERE​ Country = ​'India'​;

Trigger Example 1

Given Student Report Database, in which student marks assessment


is recorded. In such schema, create a trigger so that the total and
average of specified marks is automatically inserted whenever a
record is insert.

Here, as trigger will invoke before record is inserted

Suppose the database

sql> desc Student;


| ​Field | Type | Null | Key | Default |
+-------+-------------+------+-----+---------+-
| tid | int(4) | NO | PRI | NULL |
| name | varchar(30) | YES | | NULL |
| subj1 | int(2) | YES | | NULL |
| subj2 | int(2) | YES | | NULL |
| subj3 | int(2) | YES | | NULL |
| total | int(3) | YES | | NULL |
| per | int(3) | YES | | NULL |
7 rows in set (0.00 sec)

SQL Trigger to problem statement.


Create trigger stud_marks
Before INSERT on Student
for each row
Set
Student.total = Student.subj1 + Student.subj2 + Student.subj3,
Student.per = Student.total * 60 / 100;

sql>insert into Student values(100, "John", 20, 20, 20, 0, 0);


Query OK, 1 row affected (0.09 sec)

sql> select * from Student;


+-----+-------+-------+-------+-------+-------+------+
| tid | name | subj1 | subj2 | subj3 | total | per |
+-----+-------+-------+-------+-------+-------+------+
| 100 | John | 20 | 20 | 20 | 60 | 36 |
+-----+-------+-------+-------+-------+-------+------+
1 row in set (0.00 sec)

Trigger Example 2

For example, given Library Book Management database schema


with Student database schema. In these databases, if any student
borrows a book from library then the count of that specified book
should be decremented. To do so,
Suppose the schema with some data,

sql> select * from book_det;


+-----+-------------+--------+
| bid | btitle | copies |
+-----+-------------+--------+
| 1 | Java | 8|
| 2 | C++ | 5|
| 3 | MySql | 10 |
| 4 | Oracle DBMS | 5|
+-----+-------------+--------+
4 rows in set (0.00 sec)
sql> select * from book_issue;
+------+------+--------+
| bid | sid | btitle |
+------+------+--------+
1 row in set (0.00 sec)
To implement such procedure, in which if the system inserts the
data into the book_issue database a trigger should automatically
invoke and decrements the copies attribute by 1 so that a proper
track of book can be maintained.
Trigger for the system –
create trigger book_copies_deducts
After INSERT
on book_issue
for each row
update book_det set copies = copies – 1
where bid = new.bid;
Above trigger, will be activated whenever an insertion operation
performed in a book_issue database, it will update the book_det
schema setting copies decrements by 1 of current book id(bid).
sql> insert into book_issue values(1, 100, "Java");
Query OK, 1 row affected (0.09 sec)
sql> select * from book_det;
+-----+-------------+--------+
| bid | btitle | copies |
+-----+-------------+--------+
| 1 | Java | 9|
| 2 | C++ | 5|
| 3 | MySql | 10 |
| 4 | Oracle DBMS | 5|
+-----+-------------+--------+
4 rows in set (0.00 sec)
sql> select * from book_issue;
+------+------+--------+
| bid | sid | btitle |
+------+------+--------+
| 1 | 100 | Java |
+------+------+--------+
1 row in set (0.00 sec)
As above results show that as soon as data is inserted, copies of the
book deducts from the book schema in the system.

Create

Drop statement in SQL

1)Drop Table Table_name

Ex DROP TABLE Student;

2) Drop View View_name;

Ex DROP View Student_name;

3)Drop Trigger trigger_name

Ex DROP Trigger ​stud_marks​;

You might also like