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

chap 4 dbms

Uploaded by

pavan
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

chap 4 dbms

Uploaded by

pavan
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 9

Unit-4

Structured Query Language (SQL)

SQL users the terms tables as relation, rows as tuples and columns as attribute. The main
SQL command for data definition is CREATE statement.

An SQL Schema is identified by a Schema name, and includes an authorization identifier


and elements can be defined later. Create schema called company, owned by ' jsmith '.
Create schema company authorization jsmith;

The CREATE TABLE command is used to specify a new relation by giving it a name
and specifying its attributes and initial constraints.
Syntax: CREATE TABLE tablename ( Columnnam1 datatype,
Columnnam2 datatype,
:
:
Columnname n datatype ,
primary key (

ex:-
CREATE TABLE Employee(
Fname varchar(20) NOT NULL,
Minit varchar(10),
Lname varchar(15),
Ssn number PRIMARY KEY,
Bdate date,
Address varchar(40) ,
Super_ssn number,
Dno number,
FOREIGN KEY (Super_ssn) REFERENCES Employee (ssn) );

Data types in SQL :-

There are 6 basic data types available for attributes. They are:

1. Numeric.
2. Character string.
3. Bit String.
4. Boolean.
5. Date & Time.
6. Time stamp

1. Numeric:- It includes integer numbers of various sizes [integer, int ] and floating numbers of
various precision(real). Formatted number can be declared by Decimal (i,j) or numeric (i,j)
i= precision is the total number of decimal digits.
j=scale is the number of digit after decimal point.

2. Character String:- It is either fixed length char(n) or varying length varchar(n) , where n is the
maximum number of characters.

3. Bit String:- It is either fixed or varying length.


Bit(n)=fixed.
Bit varying (n)=varying
Ex:- B'10101'

4. Boolean:- It has 2 values of True or False.


5. Date:- It has ten position and its components are year, month and day in the form dd-mmm-yyyy.
Ex:-16-May-1997

Time:- It has at least eight positions and components are hour, minute and second in the form of
hh:mm:ss.
Ex:-09:12:47

6. Timestamp:- It includes the date and time fields, plus a 6 positions of secondsa and an optional
with TIME ZONE qualifier. Ex: ‘2020-09-05 09:12:57 648302’ .

Specifying constraints in SQL.

1. NOT NULL: Ensures that a column cannot have NULL value. By default, a column can hold
NULL values. If you do not want a column to have a NULL value, then you need to define such
constraint on this column specifying that NULL is now not allowed for that column.

2. DEFAULT value:- Provides a default value for a column when none is specified. The DEFAULT
constraint provides a default value to a column when the INSERT INTO statement does not provide
a specific value.

3. Check:- The CHECK constraint ensures that all values in a column satisfy certain conditions.
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 into the table.

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

5. Foreign key:- A foreign key is a key used to link two tables together. This is sometimes called a
referencing key. The relationship between 2 tables matches the Primary Key in one of the tables
with a Foreign Key in the second table. If a table has a primary key defined on any field(s), then
you can not have two records having the same value of that field(s).

6. Unique:- Ensures that all values in a column are different. The UNIQUE Constraint prevents two
records from having identical values in a particular column.

Ex:- CREATE TABLE employee(


Fname varchar(10) NOT NULL,
lname varchar(10),
Ssn number(10) PRIMARY KEY,
DOB date,
Salary decimal(10,2) DEFAULT 20000,
Super_ssn Number(10),
Contactno Number(12) UNIQUE,
Dno Number(10) CHECK (DNO>0 AND DNO<5),
FOREIGN KEY (Super_Ssn) REFERENCES employee(Ssn) );

DROP COMMAND
It can be used to drop named schema elements such as tables, constraints.
There are two types
1. CASCADE
2. RESTRICT

1. CASCADE:-It removes the complete database schema and all its tables constraints and other
elements.
Ex: DROP SCHEMA Company CASCADE;
2. RESTRICT:- It removes the Schema only if it has no elements in it.
Ex: Drop Schema company restrict;

If the base table is no longer needed the table and its definition can be deleted by drop table
command.
Syntax:- DROP TABLE TABLENAME;
EX:- DROP TABLE DEPARTMENT;

1. CASCADE: It table is no longer needed in company database then it is dropped by CASCADE


option .
Ex:-DROP TABLE TABLENAME CASCADE;
Syntax:- DROP TABLE DEPENDENT CASCADE;

2. RESTRICT:-The table is removed only it is not referenced in any constraints.


Syntax: DROP TABLE TABLENAME RESTRICT;
Ex:- DROP TABLE DEPENDENT RESTRICT;

ALTER COMMAND

It is used to add , delete, modify columns in an existing table.

1. To add a Column to a Table.


Syntax: alter table table_name add column column name datatype;
Ex:- Alter table employee Add column number(10);

2. To drop a Column in a table.


Syntax:-Alter table table name DROP column column name;
Ex:- Alter table employee drop column address;

3. To change the datatype of a column in a table .


Syntax:-Alter table tablename alter column columnname datatype;
Ex:- Alter table employee alter column salary dec(5,2);

4. To rename a column in a table.


Syntax:-Alter table tablename rename COLUMN "column 1" TO "column 2";
Ex:- Alter table employee rename COLUMN " amount" TO "salary";

Basic Queries in SQL


Select<attribute list>
From<table name>
Where<condition>

Where.
<attribute list> list of attribute names whose values to be retrieved by the query.
< table list > list of tables.
<condition> Boolean expression that identifies the tuples.

Simple Queries.

1. Retrieve the birth date and address of employees whose name is John B Smith.
Select bdate,address
From employee
Where fname='john' and minit='b' and lname='smith';
2. Retrieve the name and address of all employees who work for the 'research' department.
Select fname,lname,address
From employee,department
Where dname='research' and mgr_ssn=ssn;

3. For every project located in Bangalore list the project number, controlling department
number and the department manager last name ,address, birthdate

Select pno,Dnumber,lname,address,bdate
From employee,department,project
Where plocation='bangalore' and mgr_ssn=ssn and dnum=dnumber;

AMBIGOUS ATTRIBUTE NAMES , ALIASING


Aliasing are used to temporarily rename a table or a column heading Alias is done by
prefixing to the attribute name separating the two by period (dot). There prevent ambiguity in the
table or attribute name.

Syntax:-
Select Aliasname.Columnname
from Tablename alias_name;

Ex:- Select Fname,address


From employee, Department
Where Department. Dnum=10 and Department. Dnum=employee.Dnum;

4. For each employee retrive the employee's first and last name and first an last name of his or
her immediate supervisor?

Select e.fname, e.lname, s.fname, s.lname


From employee as e, employee as s
Where e.Super_ssn=s.ssn;

Unspecifies Where Clause

The where clause is used to extract the filter records a missing where clause indicates no
condition on tuple selection and all tuples are selected for the Query result.

5. Select all employee's Ssn.


Select ssn
From employee;

6. Select all employees ssn and all combination of department dname in the database.
Select Ssn, dname
From employee, department;

7. Retrieve all the attribute values of employee's who work in the department dnumber 5.
Select *
From employee
Where Dno=5;

8. Retrive all the attribute values of employee who work in department name is research.

Select *
From employee, department
Where dname='research' and dnum=dno;
TABLES AS SETS IN SQL

Table is a multiset to eliminate duplicate tuples in a query we use distinct in select clause it result
only distinct tuples should remain in the result

9. Retrive the salary of every employee.


Select ALL salary
From employee;

10. Retreive distinct salary values of employee.


Select distinct salary
From employee

Pattern Matching
LIKE-It is used for string pattern matching % - replaces on arbitary number of 0 or more
charecters –(under score)-- replaces a single charecter.

11. Retrieve all employees whose address is in Bangalore.


Select Fname,lname
From employee
Where address like ' % Bang% ';

12. Find all the employee's who born during 1990's .


Select fname,lname
From employee
Where bdate like '---------9-';

Arithmetic operators
It can be used for numeric values of a attribute.

The operators are +,-,*,/.

13. Show the resulting salaries if every employee working on the 'xyz' project is given a 10%
rise
Select fname,lname,1.1*salary
From employee,works on,project
Where ssn=essn and pno=pnumber and pname='xyz';

Between operator
It is an interval values between the two date time values.
Syntax: SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

14. Retrieve all employee in department 5 whose salary is between $30,000 and $40,000 .
Select *
From employee
Where (salary between 30,000 and 40,000) and dno=5;

In operator
It allows to specify multiple values in a where clause
Syntax: Select <attribute name>
From <table list>
Where column name in (value1,value2...........);
15. Retrieve the ssn of all employee who work on project number 1,2,3
Select distinct essn
From works_on
Where pno in (1,2,3);

Order by
It allow the user to order the tuples in the result of a query the default order is ascending
descending result in a descending order of values.

Syntax : SELECT column1, column2, ...


FROM table_name
ORDER BY column1 ASC|DESC, column2 ASC|DESC, ... ;

16. Retrieve a list of employee and project they are working on order by department
descendingly & ordered alphabetically by lastname, firstname?

Select dname,pname,lname,pname
From department,employee,project
Where dnum=dnumber and mgr_ssn=ssn
Order by dname desc, fname asc, lname asc;

Aggregate functions in SQL


A number of built in functions are count,sum,max,min,avg

Count( ) - It returns the number of tuples or values as specified in a query.


Sum( ) - It returns the sum or total values of specified relation.
Max( ) -Returns the maximum values of relation.
Min( ) -Returns the minimum values of relation.
Avg( ) -Returns the average values of relation.
All these functions are used in select and having clause

Syntax:
SELECT sum(column_name), max(column_name) , min(column_name),avg(column_name)
FROM table_name
WHERE condition;

17. Find the sum of salaries of all emoployees. The maximum salary,the minimum salary,the
average salary.
Select Sum(salary),max(salary),min(salary),avg(salary)
From employee;

18. Retrieve the number of employees in research department.


Select count(*)
From employee,department
Where dname='research' and dno=dnum;

19. Retrieve the total number of employees in the company database.


Select count(*)
From employee;

20. Count the number of distinct salary values in database.


Select count(distinct salary)
From employee;
Group by clause
It is used in conjunction with the aggregate functions to the group the result set one or more
columns. It specify the grouping attributes that appear in the select clause.
Syntax:- Select column-name,agg function(column-name)
From table name
Where condition
Group by column-name;

21 .Retrieve the department number,the number of employees and there average salary.
Select dno,count(*),avg(salary)
From employee
Group by dno;

22.For each project retrieve the project number the project name and the number of
employee who work on the project.
Select pnumber,pname,count(*)
From project,works_on
Where pnumber=pno
Group by pnumber, pname;

Having Clause
It enables the condition to filter which group result appear in the result of query.the having
was added to query because where could not used with aggregate function.
Syntax:- Select column-name, agg function(column-name)
From table name
Where condition
Group by column-name
Having grouping condition;

23. For each project on which more than 2 employees work, Retrieve the project number
pname, number of employees who work on project.
Select pnumber, pname, count(*)
From project,works_on
Where pnumber=pno
group by pnumber=pname
Having count(*)>2;

24.For each project retrieve the project number project name and number of employee from
department 5 who works on the project.
Select pnumber, pname, count(*)
From project,works_on,employee
Where pnumber=pno, and essn=ssn and dno=5
Group by pnumber, pname;

Summary of SQL queries


SQL consist of six clauses first two Select and From are mandatory and remaining are
optional.
Select <attribute and function list>
From<table list>
where<condition>
Order by<attribute list>
Group by <grouping attribute>
Having<grouping condition>;
Where,
Select – Retrieve the list of attribute or functions.
From – Tables involved in queries.
Where - condition for relation of tuples.
Order by - specifies on order for displaying the result in query.
Group by – specifies grouping attribute.
Having – specifies a condition on the group being selected.

INSERT,DELETE,UPDATE STATEMENTS IN SQL

Insert command: It is used to add a single tuple to a relation we must specify the relation name and
a list of values. The values should be listed in the same order in which corresponding attributes
specified .

Syntax:-
1) Insert into tablename values ('att1','att2'............'attn');
2) Insert into tablename ('att1','att2'............'attn') values('val1','val2'.........'valn');
3) Insert into tablename values('&att1','&att2'............'&attn');
enter the value for &att1:
:
:
:
enter the value for &att n:

eg:- 1) Insert int oemployee values ('aaa',001);


2) Insert into employee (name,ssn) values ('aaa',001);
3) Insert into employee values ('&name','&ssn');
enter the value of name:aaa
enter the value for sn:001
1 row created.

Delete command
It removes tuple from a relation if Where clause is specified select the tuple to be deleted. If
not complete / all tuples are deleted.
Syntax:- Delet from tablename
Where<condition>

Delete from employee;


complete all tuple in a table is deleted.

Delete from employee


Where lname='smith';

Delete from employee


Where dno=5;

Update command
It is used to modify attribute values of one or more selected tuples. In where clause selects
the tuples to be modified from a relation. In Set clause specifies the attribute to be modified and
there new values.

Syntax:- Update<tablename>
Set<column_name>
Where<condition>;

ex:- Change the project_location and deptnum where dno=5.


Update project
Set plocation='bang',dnum=5
Where pno=5;
View in SQL

1. A view is a single table that is derived from base tables.


2. A view does not exist in physical form.
3. It is virtual table only definition of view is stored but not content.

Specifications of views
create view command is specified to view it is given a view name list of attribute and a
query to specify the contents of the view .

Syntax:- Create view viewname


as query from existing table;

ex: create view v1


as select fname,ssn
from emoployee
where dno=5;

view created;

select * from v1;

Drop view command is used to dispose view if we do not need anymore

Syntax: Drop view viewname;

ex:- drop view v1;

Advantages:-
1. It provides additional level of security on base tuples.
2. View hide data complexibility
3. View can be created by joining attributes of 2 or more tables.
4. View permits data to be presented in different perspective that of a base table.

You might also like