Database Management System
Database Management System
Database Management System
Less storage: Theoretically, all occurrences of data items need to be stored only once, thereby eliminating the storage of redundant data. System developers and database designers often use data normalization to minimize data redundancy.
Vendor independence. Portability across computer systems. SQL standards. Relational foundation. High-level, English-like structure. Interactive, ad hoc queries. Programmatic database access. Multiple views of data. Complete database language. Dynamic data definition. Client/server architecture. Enterprise application support. Extensibility and object technology. Internet database access. Industry infrastructure.
The Data Definition Language (DDL): This component of the SQL language is used to create and modify tables and other objects in the database. The main commands are: CREATE TABLE tablename to create a table in the database. DROP TABLE tablename to remove a table from the database. ALTER TABLE tablename to add or remove columns from a table in the database. The Data Manipulation Language (DML): This component of the SQL language is used to manipulate data within a table. The main commands are: INSERT to insert rows of data into a table. UPDATE to change rows of data in a table. DELETE to remove rows of data from a table. The Data Control Language (DCL): This component of the SQL language is used to create privileges to allow users access to, and manipulation of, the database. The main commands are: GRANT to grant a privilege to a user. REVOKE to revoke (remove) a privilege from a user. The Data Query Language (DQL): This component of the SQL language is used to view the changes that have been made on the table in the database. The main commands are: SELECT to select rows of data from a table.
Exp 2: To implement DDL, DML, DCL, and DQL statements in SQL server 2005.
1. DDL (Data Definition Language) 2. DML (Data Manipulation Language) 3. DCL (Data Control Language) 4. DQL (Data Query Language) 1. DDL (Data Definition Language):- It is a set of SQL commands used to
create, modify and delete database structures but not data. They are normally used by the DBA not by user to a limited extent, a database designer or application developer. These statements are immediate i.e. they are not susceptible to ROLLBACK commands. It should also be noted that if several DML statements for example UPDATES are executed then issuing any DDL command would COMMIT all the updates as every DDL command implicitly issues a COMMIT command to the database. Anybody using DDL must have the CREATE object privilege and a table space area in which to create objects. For example: - CREATE, ALTER, DROP, TRUNCATE, COMMENT etc. THE CREATE TABLE COMMAND: - The CREATE TABLE command defines each column of the table uniquely. Each column has a minimum of three attributes, a name, data type and size (i.e. column width). Syntax :- create table<table name>(<column Name 1><data type>(<size>), <columnname2><data type>(<size>)) Example:create table student ( name varchar(23), roll_no number(12), class varchar2(12), address varchar(23) );
ISHA AGGARWAL (80805107023)
THE INSERTION OF DATA INTO TABLE: - The INSERT command in SQL is used to add records to an existing table. Returning to the personal_info example from the previous section, let's imagine that our HR department needs to add a new employee to their database.
Syntax: - INSERT INTO <table name > (<columnname1>,<columnname2>) VALUES (<expression1>, <expression 2>) OR INSERT INTO <tablename>VALUES (<expression1 >,<expression2> )
UPDATING THE CONTENTS OF THE TABLE: - The update command is used to change or modify data values in a table. The verb UPDATE in SQL is used to either all the rows from a table or a select set of rows from a table.
Syntax:-UPDATE < Table name> SET <column name1>=<expression1>, <columnname2>=<expression2> WHERE <condition>
DROP COMMAND: - By using the DROP TABLE statement with the table name we can destroy a specific table.
using the ALTER TABLE command. ALTER TABLE allows changing the structure of an existing table. With ALTER TABLE it is possible to add or delete columns, create or destroy indexes, changes the data type of existing columns, or rename columns or the table itself.
Syntax: - ALTER TABLE <Table name>ADD(<New column Name><data type> (<size>),<new column name><data type>(<size>))
table.
Example: - delete from citylist where name = 'Argos' and state = 'Indiana';
GRANT COMMAND: - GRANT is a command used to provide access or privileges on the database objects to the users.
REVOKE COMMAND: - Use the REVOKE statement to remove privileges from a specific user or role, or from all users, to perform actions on database objects. You can also use the REVOKE statement to revoke a role from a user, from PUBLIC, or from another role.
ISHA AGGARWAL (80805107023)
4. DQL (Data Query Language) :- The language used to query data which is a
content management system used to create, manage, deliver, and archive all types of content from text documents and spreadsheets to digital images, HTML, and XML components. DQL (Data Query Language) is a query language which allows you to do very complex queries involving: Example: SELECT
Syntax: - select * from <table name> Or select <column name> from <table name>
Solutions:
create table client_master ( client_no int primary key, name char(30), address varchar(30), city varchar(30), pincode int, state char(30) ); select * from client_master;
insert into client_master values(1,'ram','ashok vihar','delhi',1200,'delhi'); insert into client_master values(2,'sham','vasant vihar','ludhiana',1209,'punjab'); insert into client_master values(3,'amy','ghumar mandi','patiala',1304,'punjab'); insert into client_master values(4,'mary','preet vihar','sirhind',1809,'punjab'); insert into client_master values(5,'sita','karol bagh','delhi',1289,'delhi');
10
create table productMaster ( product_no int primary key, description varchar(30), price int, quantity int ); select * from productMaster;
insert into productMaster values(1001,'bottle',50,2); insert into productMaster values(1002,'pencil box',100,6); insert into productMaster values(1003,'note book',10,3); insert into productMaster values(1004,'pen',70,8); insert into productMaster values(1005,'eraser',35,100); insert into productMaster values(1006,'bag',500,7); select * from productMaster;
11
Output:
Output:
Query 3: Retrieve the list of names and adddress of all the clients who are located in
ISHA AGGARWAL (80805107023)
12
Output:
Output:
Query 5: Change the price of first product in the productMaster table to 2000. Solution:
ISHA AGGARWAL (80805107023)
13
Output:
Output:
Query 7: Destroy the client_master table along with its data. Solution:
drop table client_master; select * from client_master;
Output:
14
Output:
15
Solutions:
Query 1: Create the following tables: student_info s_rollno s_name course_no course_info course_id course_name Solution:
create table student_info ( s_rollno int primary key, s_name char(20), course_no int references course_info(course_id) on delete cascade ); select * from student_info;
Output:
16
Output:
Output:
Solution:
insert into course_info values(1,'CSE'); insert into course_info values(2,'ECE'); insert into course_info values(3,'MECH'); insert into course_info values(4,'CIVIL'); insert into course_info values(5,'EE'); insert into course_info values(6,'IT'); select * from course_info;
Output:
ISHA AGGARWAL (80805107023)
17
Output:
Output:
18
Output:
Output:
19
Output:
Query 8: Increase the size of column course_name. Solution: Output: Query 9: Implement the concept of foreign key. Solution: Output:
20
1. PRIMARY KEY: - The primary key of a relational table uniquely identifies each
record in the table. It can either be a normal attribute that is guaranteed to be unique or it can be generated by the DBMS. Primary keys may consist of a single attribute or multiple attributes in combination.
Syntax: - CREATE TABLE table_name (column1 datatype null/not null, column2 datatype null/not null, ... CONSTRAINT constraint_name PRIMARY KEY (column1, ..));
supplier_name varchar2(50) not null, contact_name varchar2(50), CONSTRAINT supplier_pk PRIMARY KEY (supplier_id) );
21
2. FOREIGN KEY: - A foreign key means that values in one table must also
appear in another table. The referenced table is called the parent table while the table with the foreign key is called the child table. The foreign key in the child table will generally reference a primary key in the parent table. A foreign key can be defined in either a CREATE TABLE statement or an ALTER TABLE statement
Syntax: - CREATE TABLE table_name (column1 datatype null/not null, column2 datatype null/not null, ... CONSTRAINT fk_column FOREIGN KEY (column1, column2, ... column_n) REFERENCES parent_table (column1, column2, ... column_n) );
supplier_name varchar2(50) not null, contact_name varchar2(50), CONSTRAINT supplier_pk PRIMARY KEY (supplier_id) );
table.
ISHA AGGARWAL (80805107023)
22
Syntax: - CREATE TABLE table_name (column1 datatype null/not null, CONSTRAINT constraint_name CHECK (column_name condition) ); Example: - CREATE TABLE suppliers ( supplier_id numeric(4), supplier_name varchar2(50), CONSTRAINT check_supplier_id CHECK (supplier_id BETWEEN 100 and 9999));
4. NOT NULL: - The NOT NULL constraint enforces a field to always contain a
value. This means that you cannot insert a new record, or update a record without adding a value to this field. The NOT NULL column constraint ensures that a table column cannot beeft empty.
Database Management System Exercise 3:1. Create the following tables: student_info
sid(primary key) sname course_no(foreign key)
23
city
Course__Info
course_id (primary key) cname
2. Insert records in Course__Info with course_id=10,20,30,40. 3. Insert records in student_info with course_no=10,20,50. 4. Make the city column values unique, NULL can be entered into city column. 5. Drop the constraint foreign key from student_info table. 6. Show all the student ids in descending order. 7. Display all the records of course_info table according to the increasing values of course_id. 8. Drop the constraint primary key from student info. 9. Delete all the data from the sname column and also delete all the data from student_info table. 10. Make the sid column as primary key and course_no column as foreign key using alter table command.
ISHA AGGARWAL (80805107023)
24
Solutions:
Query 1:- Create the following tables: student_info sid(primary key) sname course_no(foreign key) city
Solution:
create table "student_info" ( sid int primary key, sname char(20), "course no" int references "course__Info"("course id") on delete cascade, city char(20) ); select * from "student_info";
Output:
Solution:
create table "Course__Info" ( "course id" int primary key, cname char(20) );
25
Output:
Output:
Output:
Msg 547, Level 16, State 0, Line 3 The INSERT statement conflicted with the FOREIGN KEY constraint "FK__student_i__cours__60083D91". The conflict occurred in database "master", table "PC-1-500\student.course_info", column 'course id'. The statement has been terminated.
Query 4:- Make the city column values unique, NULL can be entered into city column.
ISHA AGGARWAL (80805107023)
26
Output:
Query 5:- Drop the constraint foreign key from student_info table. Solution:
create table "student_info" ( sid int primary key, sname char(20), courseno int, constraint fkey foreign key (courseno) references "course__Info"("course id"), city char(20) unique ); alter table "student_info" drop constraint fkey; insert into "student_info" values(1,'ajay',10,'noida'); insert into "student_info"(sid,sname,courseno) values(2,'vijay',20); insert into "student_info" values(3,'pronoy',50,'amritsar'); select * from "student_info";
Output:
27
Query 6:- Show all the student ids in descending order. Solution:
select * from student_info order by sid desc;
Output:
Query 7:- Display all the records of course_info table according to the increasing values of course_id. Solution:
select * from course__Info order by "course id";
Output:
Query 8:- Drop the constraint primary key from student info. Solution:
create table "student_info" ( sid int, sname char(20),
28
Output:
Query 9:- Delete all the data from the sname column and also delete all the data from student_info table. Solution:
delete from student_info; select * from student_info;
Output:
Query 10:- Make the sid column as primary key and course_no column as foreign key using alter table command. Solution: Output:
29
Exp 4: To explore select statement using where clause with various operators and order by clause.
SQL Operators: SQL operators are found in just every SQL query. Operators are the
mathematical and equality symbols used to compare, evaluate, or calculate values. When SQL come across these operators, they help tell SQL how to evaluate an expression or conditional statement in the WHERE clause of SQL commands. There are various types of operators: 1. 2. 3. 4. 5. Arithmetic operators. Logical operators. Comparison operators. Range searching operators. Pattern matching operators.
Arithmetic operators:- These are mathematical operators used to perform addition(+), subtraction(-), multiplication(*), division(/). We can use SQL like a calculator to get a feel for how these operators work. Logical operators:- These operators provide you with a way to specify exactly what you want SQL to go and fetch, and you may be as specific as youd like. AND, OR and NOT are the logical operators. Comparison operators: - These operators are used to compare various set of values. > (greater than), < (less than), = (equals to), <> or != (not equals to), <= (less than equals to), >= (greater than equals to), is NULL, is NT NULL.
ISHA AGGARWAL (80805107023)
30
Range searching operators:- These operators are used to specify the range of values. BETWEEN and NOT BETWEEN keywords are used to specify range. Pattern matching operators:- These operators are used to find some specified string pattern in the given string. LIKE, NOT LIKE, IN, NOT IN are the operators used along with some predicates like %,_,[] to find the desired string pattern.
Order by clause:-
SQL allows data to be viewed in a sorted order. The rows retrieved from the table will be sorted in either ascending or descending order depending on the condition specified in the SELECT statement. Syntax: - select * from <tablename> order by<columnname1>, <columnname2> <[sort order]>; Example: - select * from master order by name;
city
1. List the names of all clients having a as the second letter in their names.
2. List all the clients who stay in city whose first letter and second letter should lie
between a tos and a to n and last letter should be a. 3. List all the clients who stay in Bangalore or Chandigarh. 4. List all the clients of Bangalore whose names start with either a or b or c.
ISHA AGGARWAL (80805107023)
31
7. List all products whose price should not be between 5000 and 10,000 and having name consist of 3 characters. The products should be arranged in decreasing order according to the price. 8. Display the following data. Price per day Price per month Annual price
Solutions:-
create table"client_master" ( cid int, cname char(90), city char(10), ); insert into client_master values(1,'sarab','patiala'); insert into client_master values(2,'aman','bangalore'); insert into client_master values(3,'nidhi','delhi'); insert into client_master values(4,'shivangi','chandigarh'); insert into client_master values(5,'isha','kerala'); insert into client_master values(6,'siddharth','assam'); select * from client_master;
32
create table product_master (pcode int, pname char(20), price int, ); insert into product_master values(001,'oil',1000); insert into product_master values(002,'copy',500); insert into product_master values(003,'pen',100); insert into product_master values(004,'heater',5000); insert into product_master values(005,'fan',3000); insert into product_master values(006,'pencil',50); select * from product_master;
Query 1:- List the names of all clients having a as the second letter in their names. Solution:
select cname from client_master where cname like '_a%';
33
Query 2:- List all the clients who stay in city whose first letter and second letter should lie between a tos and a to n and last letter should be a.
Solution:
select * from client_master where city like '[a-s][a-n]%a';
Output:
Query 3:- List all the clients who stay in Bangalore or Chandigarh. Solution:
select * from client_master where city like 'bangalore' or city like 'chandigarh';
Output:
Query 4:- List all the clients of Bangalore whose names start with either a or b or c. Solution:
ISHA AGGARWAL (80805107023)
34
Output:
Query 5:- List the names of all the products with price having any one of the following values 1000, 2000, 5000, 6000, 4000. Solution:
select pname from product_master where price in(1000,2000,100,3000,500);
Output:
Query 6:- Display the names of all the products whose price is not 1000. Solution:
select pname from product_master where price!=1000 ;
Output:
Query 7:- List all products whose price should not be between 5000 and 10,000 and
ISHA AGGARWAL (80805107023)
35
select * from product_master where price not in (5000-10000) and pname like '___' order by price desc;
Output:
Annual price
Solution:
select price/30 "price per day", price "price per month", price*12 "annual price" from product_master;
Output:
36
Group functions: - Functions that act on a set of values are known as group functions. A group function returns a single result row for a group of queried rows. We can use following functions: AVG- To calculate average. MIN- To find minimum value. MAX- To find maximum value. COUNT- To count total number of records. SUM- To find the sum of vlues on a row or column. Scalar functions:- These functions act on only one vaue at a time. A single row function return one result for every row of a queried table or view. We can use following funtions: ABS- To find absolute value. POWER(m,n)- To find the power of a number, where m is raised to the power of n. ROUND(m,n)-To find the round of value of a decimal value, where m is the value and n is the precison value. SQRT- To find the square root of a number. String functions:- These functions act on string values. We can use the following functions: LOWER- To convert the given sring into lowercase. UPPER- To convert the given string into uppercase. ASCII- To find the ascii code of a given character. SUBSTRING(string, start_position, length)- To find the substring from a given string. Exercise 4:- Create a table and find the result for all the functions.
ISHA AGGARWAL (80805107023)
37
Solutions:create table product_master ( product_no int primary key, description varchar(30), price varchar(20), quantity int ); insert insert insert insert insert insert into into into into into into product_master product_master product_master product_master product_master product_master values(1,'abc',500,2); values(2,'abc',300,2); values(3,'abc',400,2); values(4,'abc',700,2); values(5,'tools,Rs 400/-,2); values(6,'bags',Rs 500/-,3);
Output:
Group functions: -
1. AVG
Solution:
select avg(quantity) from product_master;
Output:
2. MIN
ISHA AGGARWAL (80805107023)
38
Output:
3. MAX
Solution:
select max(product_no) from product_master;
Output:
4. COUNT
Solution:
select count(*) from product_master;
Output:
5. SUM
Solution:
select sum(quantity) from product_master;
Output:
39
Output:
2. POWER (m,n)
Solution:
select power(10,2);
Output:
3. ROUND (m,n)
Solution:
select round(10.127,2);
Output:
4. SQRT
Solution:
ISHA AGGARWAL (80805107023)
40
Output:
String functions:-
1. LOWER Solution:
select lower('HELLO HOW ARE YOU?');
Output:
2. UPPER Solution:
select upper(description) from product_master;
41
3. ASCII Solution:
select ASCII('a');
Output:
Output:
42
mandatory SELECT clause and FROM clause. The SELECT clause can have a list of columns, expressions, functions, and so on. The FROM clause tells us which table(s) to look in for the required information. With the help of joins we can retrieve data from more than one table and relate various tables with each other. Rows in one table can be joined to rows in another table according to common values existing in corresponding columns. There are various types of joins: Cross join Inner join Left outer join Right outer join Full outer join
Query 1:Solution:
ISHA AGGARWAL (80805107023)
43
create table customer ( c_id int primary key, c_name varchar(30), loan_id int references loan_(l_id) on delete cascade );
44
create table loan_ ( l_id int primary key, l_type varchar(30) ); insert into loan_ values(101,'car'); insert into loan_ values(102,'home'); insert into loan_ values(103,'education'); select * from loan_;
create table bank ( b_id int primary key, loaction varchar(30), c_id int references customer(c_id) on delete cascade ); insert insert insert insert into into into into bank bank bank bank values(1,'patiala',1); values(2,'sirhind',2); values(3,'amritsar',3); values(4,'ludhiana',1);
45
46