DBMS UNIT 2 SQL Commands

Download as pdf or txt
Download as pdf or txt
You are on page 1of 92

DBMS

(Database Management System)

- Pankaj Kathiriya
Content
 SQL commands
 (i) Creating and altering tables: CREATE
statement with constraints like KEY, CHECK, DEFAULT,
ALTER and DROP statement.
 (ii) Handling data using SQL: selecting data using
SELECT statement, FROM clause, WHERE clause,
HAVING clause, ORDER BY, GROUP BY,DISTINCT
and ALL predicates, Adding data with INSERT
statement, changing data with UPDATE statement,
removing data with DELETE statement.
 What is data and information ?
 Why we require database ?
 What is data warehouse ?
 What is DBMS ?
 What is database ?
 DDL (data definition language) and

 DML (data manipulation language)


 Data Manipulation Language (DML)
 INSERT - Used to create a record.
 UPDATE - Used to change certain records.
 DELETE - Used to delete certain records.
 Data Definition Language (DDL)
 CREATE - Used to create a new table, a view of a table, or other
object in database.
 ALTER - Used to modify an existing database object, such as a
table.
 DROP - Used to delete an entire table, a view of a table or other
object in the database.
 Data Control Language (DCL).
5
6
SQL (Structured Query Language)
 SQL is used to communicate with a database.
 SQL is non procedural language.
Table 2
Table 1
Table 1

.
DATABASE .
.
Table n
Tables in SQL Attribute names

Table name
Product

PName Price( $ ) Category Manufacturer

Gizmo 19.99 Gadgets GizmoWorks

Powergizmo 29.99 Gadgets GizmoWorks

SingleTouch 149.99 Photography Canon

MultiTouch 203.99 Household Hitachi

Tuples or rows
Data types
 String types
 CHAR(n) – fixed-length character data, n characters long Maximum
length = 2000 bytes
 VARCHAR2(n) – variable length character data, maximum 4000 bytes
 LONG – variable-length character data, up to 4GB. Maximum 1 per
table
 Numeric types
 NUMBER(p,q) – general purpose numeric data type
 INTEGER(p) – signed integer, p digits wide
 FLOAT(p) – floating point in scientific notation with p binary digits
precision
 Date/time type
 DATE – fixed-length date/time in dd-mm-yy form
 TIME - a time of day with decimal fractions of a second: HH-MM-SS-
F....F
Some of The Most Important SQL
Commands
 SELECT - extracts data from a database
 UPDATE - updates data in a database
 DELETE - deletes data from a database
 INSERT INTO - inserts new data into a database
 CREATE DATABASE - creates a new database
 ALTER DATABASE - modifies a database
 CREATE TABLE - creates a new table
 ALTER TABLE - modifies a table
 DROP TABLE - deletes a table
Primary key
 The PRIMARY KEY constraint uniquely identifies each
record in a database table.
 Primary keys must contain UNIQUE values.
 A primary key column cannot contain NULL values.
 Most tables should have a primary key, and each
table can have only ONE primary key.
 CREATE TABLE Persons
(
P_Id int NOT NULL PRIMARY KEY,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
Foreign key
 A FOREIGN KEY in one table points to a PRIMARY
KEY in another table.
P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Foreign Key
Primary key
O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 2
4 24562 1
 CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
);
The SQL CREATE DATABASE Statement

 The CREATE DATABASE statement is used to create


a database.
 SQL CREATE DATABASE Syntax
 CREATE DATABASE dbname;
The SQL CREATE TABLE Statement
 The CREATE TABLE statement is used to create a table in
a database.
 Tables are organized into rows and columns; and each
table must have a name.
 SQL CREATE TABLE Syntax
 CREATE TABLE table_name
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....
);
SQL CREATE TABLE Example
 CREATE TABLE Persons
(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
Example:
 Create customer record table:
 Attributes:
 Customer ID, Customer Name, Gender, Contact no, Address.
SQL Constraints
 SQL constraints are used to specify rules for the data in a
table.
 Constraints can be specified when the table is created
(inside the CREATE TABLE statement) or after the table is
created (inside the ALTER TABLE statement).
 SQL CREATE TABLE + CONSTRAINT Syntax
 CREATE TABLE table_name
(
column_name1 data_type(size) constraint_name,
column_name2 data_type(size) constraint_name,
column_name3 data_type(size) constraint_name,
....
);
 ALTER TABLE table_name MODIFY attribute_name
data_type(size) constraint_name;
In SQL, we have the following
constraints:
 NOT NULL
 UNIQUE
 PRIMARY KEY
 FOREIGN KEY
 CHECK
 DEFAULT
NOT NULL
 NOT NULL - Indicates that a column cannot store
NULL value
 CREATE TABLE PersonsNotNull
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
NULL
P_Id LastName FirstName Address City
1 Hansen Ola Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Stavanger

NOT NULL
P_Id LastName FirstName Address City
1 Hansen Ola US Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari UK Stavanger
UNIQUE
 UNIQUE - Ensures that each row for a column must
have a unique value.
 UNIQUE KEY allows NULL value.
 Example:
 CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
PRIMARY KEY
 PRIMARY KEY - A combination of a NOT NULL and
UNIQUE. Ensures that a column (or combination of two or
more columns) have a unique identity which helps to find a
particular record in a table more easily and quickly.
 Example :
 CREATE TABLE Persons
(
P_Id int PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
FOREIGN KEY
 FOREIGN KEY - Ensure the referential integrity of
the data in one table to match values in another
table.
 Example :
 CREATE TABLE Orders
(
O_Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int FOREIGN KEY REFERENCES Persons(P_Id)
);
P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Foreign Key
Primary key
O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 2
4 24562 1
CHECK
 CHECK - Ensures that the value in a column meets a
specific condition.
 The CHECK constraint is used to limit the value
range that can be placed in a column.
 Example :
 CREATE TABLE Persons
(
P_Id int NOT NULL CHECK (P_Id>0),
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
 Create table of employee where age must be
greater than 18.
 Emp_id
 Emp_name
 Emp_age
 Address
DEFAULT
 DEFAULT - Specifies a default value for a column.
 The DEFAULT constraint is used to insert a default value
into a column.
 The default value will be added to all new records, if
no other value is specified.
 Example :
 CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT ‘predefine_value'
);
 Create table with Default constraints allow default
value of salary as 15,000.
Alter Table
 The ALTER TABLE statement is used to add, delete,
or modify attributes in an existing table.
 SQL ALTER TABLE Syntax
 To add a column in a table, use the following
syntax:
 ALTER TABLE table_name ADD column_name datatype;

 Example:
 ALTER TABLE customer ADD city varchar(50);
 To add multiple attribute/column.
 ALTER TABLE table_name ADD (column_1 data type,
column_2 data type, ... column_n data type);

 Example:
 ALTER TABLE supplier ADD (supplier_name varchar(50),
city varchar(45));
 To delete a column in a table, use the following
syntax (some database systems don't allow deleting
column)
 ALTER TABLE table_name DROP COLUMN
column_name;

 Example:
 Alter table Person drop column city;
 Use to modify a column in an existing table, the
SQL ALTER TABLE syntax is:
 ALTER TABLE table_name MODIFY column_name
column_type;

 Example:
 ALTER TABLE supplier MODIFY supplier_name
varchar(100) NOT NULL;
 ALTER TABLE table_name MODIFY (column_1 data
type, column_2 data type, ... column_n data type);
RENAME COLUMN IN TABLE
 RENAME COLUMN IN TABLE
 To rename a column in an existing table, the SQL
ALTER TABLE syntax is:
 ALTERTABLE table_name RENAME COLUMN old_name
TO new_name;
 Exampe:
 ALTER TABLE supplier RENAME COLUMN
supplier_name TO sname;
RENAME TABLE
 RENAME TABLE
 To rename a table, the SQL ALTER TABLE syntax is:
 ALTERTABLE table_name RENAME TO
new_table_name;
 Example:
 ALTER TABLE supplier RENAME TO vendor;
Drop or Delete table
 The DROP TABLE statement is used to delete a
table.
 Syntax:
 DROP TABLE table_name;
 Example:
 Drop table employee;
Truncate Table
 The TRUNCATE TABLE Statement
 What if we only want to delete the data inside the
table, and not the table itself.
 Then, use the TRUNCATE TABLE statement:
 Syntax:
 TRUNCATE TABLE table_name;

 Example
truncate table employee;
Handling data using SQL
 INSERT, UPDATE and DELETE statement
 Selection of data
 Select statement
 SELECT clause
 FROM clause
 WHERE clause
 HAVING clause
 ORDER BY, GROUP BY, DISTINCT
Insertion data in table
 The INSERT INTO statement is used to insert new
records in a existing table.
 Syntax:
INSERT INTO table_name
VALUES (value1,value2,value3,...);
 Syntax:
INSERT INTO table_name (col_1,col_2,…)
VALUES(value1,value2, …)
Note:
If data type is character or variable – ‘data’
If data type is number or integer – number
 Default constraint
Create table student(
s_name varchar(20),
s_batch varchar(10) DEFAULT ‘B1’,
s_add varchar(30)
);
 To insert the record:
Insert into student(s_name,s_add) values(‘studentA’,’Andheri’);
 Create table customer and insert 4 to 5 records:
 Customer_id

 Customer_name

 Cust_contact_number

 Customer_address

 Customer_city

 Pin_code
Date/Timestamp
create table employee(
e_id int,
e_name varchar(30),
e_add varchar(100),
e_joindate date
);
--------insert record---------
insert into employee values(1,'abc','malad',sysdate);
insert into employee values(2,'john','virar','03-DEC-2015');
Timestamp
alter table employee modify e_joindate timestamp;
insert into employee values(5,'abc','malad',sysdate);
insert into employee values
(4,'def','andheri','25-DEC-2015 10.56.41.000000 PM');
insert into employee values(4,'def','andheri','25-DEC-
2015 10-56-41-00 AM');
create table abc(col1 int,sdate date);
insert into abc values(1,sysdate);

insert into abc values(2,'10-JAN-2015');

alter table abc modify sdate timestamp;

INSERT INTO abc VALUES


(4,TO_DATE('22/April/2011 8:30:00AM','DD/MON/YY HH:MI:SSAM'));
View the record in table
 Select Statement is basic statement used to retrieve
all or some columns of data from table.
 Syntax:
 For all record of the one table
Select * from table_name;
 Select statement is also used to view the tables
available in the database:
 Select * from tab;
FROM Clause
 FROM clause : produces a tabular structure.
 retrieves data from one table, from many tables.

 Syntax:
 Select column_name FROM Table_name;

 Selectcolumn_name1, column_name2 FROM


Table_name1, Table_name2;
 For single table:
 Select e_no from Employee;
 For multiple table:
 Select e_no,dept_name from Employee, Departmrnt;
Where Clause
 The SQL WHERE clause is used to specify a
condition while fetching the data from single table
or joining with multiple tables.
 The WHERE clause is not only used in SELECT
statement, but it is also used in UPDATE, DELETE
statement
 SQL WHERE Syntax
 SELECTcolumn_name, column_name
FROM table_name
WHERE column_name operator value;
Operator Description
= Equal
<> Not equal. Note: In some versions of SQL this operator
may be written as !=
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN To specify multiple possible values for a column
Operator “=“
 SELECT
ID, NAME, SALARY FROM CUSTOMERS WHERE
NAME = 'Hardik';
 Consider the CUSTOMERS table having the
following records:
Operator “>”
 SELECT
ID, NAME, SALARY FROM CUSTOMERS WHERE
SALARY > 2000;
Operator “LIKE”
Statement Description
WHERE SALARY LIKE '200%' Finds any values that start with 200

WHERE SALARY LIKE '%200%' Finds any values that have 200 in any position

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

WHERE SALARY LIKE '_2%3' Finds any values that have a 2 in the second position and
end with a 3
WHERE SALARY LIKE '2___3' Finds any values in a five-digit number that start with 2
and end with 3
 SELECT* FROM CUSTOMERS WHERE SALARY LIKE
'200%';
Operator “BETWEEN”
ProductID ProductName Price
SELECT * FROM Products
1 Chais 18
WHERE Price BETWEEN 10 AND 20;
2 Chang 19
SELECT * FROM Products
3 Aniseed Syrup 10 WHERE Price NOT BETWEEN 10 AND 20;

4 Chef Anton's Cajun 22


Seasoning

5 Chef Anton's 21.35


Gumbo Mix
Operator “IN”
 The IN operator allows you to specify multiple values
in a WHERE clause.
CustomerID CustomerName ContactName City

1 Alfreds Futterkiste Maria Anders Berlin

2 Ana Trujillo Ana Trujillo México D.F.


Emparedados y
helados

3 Antonio Moreno Antonio Moreno México D.F.


Taquería
4 Around the Horn Thomas Hardy London
SELECT * FROM Customers
WHERE
City IN ('Paris','London');

4 Around the Horn Thomas Hardy London


 The SQL AND and OR operators are used to
combine multiple conditions to narrow data in an
SQL statement. These two operators are called
conjunctive operators.
 The AND Operator:
 Syntax:
 SELECT column1, column2, columnN FROM table_name
WHERE [condition1] AND [condition2]...AND
[conditionN];
 SELECT
ID, NAME, SALARY FROM CUSTOMERS WHERE
SALARY > 2000 AND age < 25;
 The OR Operator:
 Syntax:
 SELECT
column1, column2, columnN FROM table_name
WHERE [condition1] OR [condition2]...OR [conditionN];
 SELECT
ID, NAME, SALARY FROM CUSTOMERS WHERE
SALARY > 2000 OR age < 25;
Group by Clause
 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;
If you want to know the total amount of salary on each
customer, then GROUP BY query would be as follows:

SELECT NAME, SUM(SALARY)


FROM CUSTOMERS
GROUP BY NAME;
Now, let us have following table where CUSTOMERS table
has the following records with duplicate names:

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


HAVING clause
 The HAVING clause enables you to specify
conditions that filter which group results appear in
the final results.
 The WHERE clause places conditions on the selected
columns, whereas the HAVING clause places
conditions on groups created by the GROUP BY
clause.
Syntax:

 HAVING clause must follow the GROUP BY clause in a


query and must also precede the ORDER BY clause if
used.
 The following is the syntax of the SELECT statement,
including the HAVING clause:
SELECT column1, column2
FROM table1, table2
WHERE [ conditions ]
GROUP BY column1, column2
HAVING [ conditions ]
ORDER BY column1, column2;
display record for which similar age count would be more than or equal to 2:
SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM CUSTOMERS
GROUP BY age
HAVING COUNT(age) >= 2;
ORDER BY clause
 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];
sort the result in ascending order by NAME and SALARY:

SELECT * FROM CUSTOMERS ORDER BY NAME;


 sort the result in descending order by NAME:

SELECT * FROM CUSTOMERS ORDER BY NAME DESC;


DISTINCT
 The SQL DISTINCT keyword is used in conjunction
with SELECT statement to eliminate all the duplicate
records and fetching only unique records.
 Syntax:
SELECT DISTINCT column1, column2,.....columnN
FROM table_name
WHERE [condition];
SELECT query returns duplicate salary records:
SELECT SALARY FROM CUSTOMERS ORDER BY SALARY;
 Now, let us use DISTINCT keyword with the above
SELECT query and see the result:

SELECT DISTINCT SALARY


FROM CUSTOMERS
ORDER BY SALARY;
 You can rename a table or a column temporarily by
giving another name known as alias.
 The use of table aliases means to rename a table in
a particular SQL statement.
 The renaming is a temporary change and the actual
table name does not change in the database.
 Syntax:
SELECT column_name AS alias_name FROM
table_name WHERE [condition];
Customer
Order

Table alias:
SELECT C.ID, C.NAME, C.AGE, O.AMOUNT
FROM CUSTOMERS C, ORDERS O
WHERE C.ID = O.CUSTOMER_ID;
Column alias:
SELECT ID AS CUSTOMER_ID, NAME AS CUSTOMER_NAME
FROM CUSTOMERS
WHERE SALARY IS NOT NULL;
select e.eno, d.eno
from emp1 e,dept1 d
where e.eno=d.eno;

select e.eno as eno_of_emp1,d.eno as


eno_of_dept1
from emp1 e,dept1 d
where e.eno=d.eno;
Update record
 The SQL UPDATE Query is used to modify the existing records
in a table.
 You can 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,...;

UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
UPDATE CUSTOMERS
SET ADDRESS = 'Pune'
WHERE ID = 6;

UPDATE CUSTOMERS
SET ADDRESS = 'Pune', SALARY = 1000.00;
 Update table customer:
 Cust_contact
number
 Customer_address

 Pin_code
Update customers
Set cust_contactno=12345678
Where Cust_id=10;

Update customers
Set cust_address=‘Borivali’
Where Cust_id=10;
 If interest is to be paid only to accounts with
balance of 1000 or more.

Update account
Set balance=balance * 1.05
where balance>=1000;

 Increase the salary of the manager department by


5000.
Delete Record
 Delete statement is use to a one or more record
from a table.
 Syntax:
 To delete one record.
DELETE FROM table_name WHERE Condition;
 To delete all record

DELETE FROM TABLE_NAME;


TRUNCATE TABLE TABLE_NAME;
Ex.
Delete from person where p_id=1;
 Delete all employee records whose salary is
greater than 30,000.
 Ans: ?
 Deletion with TWO condition:
Delete from product where Qty>=12 AND
category=‘Cloths’;

You might also like