0% found this document useful (0 votes)
277 views14 pages

12 - Information Practices

The document discusses concepts related to databases and SQL. It begins with definitions of a database, database management system, and SQL. It then describes what SQL can do, such as execute queries, retrieve data, insert/update/delete records, and more. It also defines relational database management systems and basic SQL terminology like tables, rows, columns, primary keys, foreign keys, etc. The remainder of the document provides details on interacting with databases using SQL commands like CREATE, INSERT, SELECT, UPDATE, DELETE, and functions.

Uploaded by

MFOX GAMER
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
277 views14 pages

12 - Information Practices

The document discusses concepts related to databases and SQL. It begins with definitions of a database, database management system, and SQL. It then describes what SQL can do, such as execute queries, retrieve data, insert/update/delete records, and more. It also defines relational database management systems and basic SQL terminology like tables, rows, columns, primary keys, foreign keys, etc. The remainder of the document provides details on interacting with databases using SQL commands like CREATE, INSERT, SELECT, UPDATE, DELETE, and functions.

Uploaded by

MFOX GAMER
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Class : XII (2020-2021)

Subject : Informatics Practices

Chapters : MySQL Revision Tour & More on SQL

What is a Database?
A database is an organized collection of data. The data are typically organized to model
aspects of reality in a way that supports processes requiring this information. The term
"database" can both refer to the data themselves or to the database management
system. The Database management system is a software application for the interaction
between users database itself. Users don't have to be human users .In this chapter we
will learn how SQL organizes & manipulate data.
What is SQL?
 SQL stands for Structured Query Language
 SQL lets you access and manipulate databases
 SQL became a standard of the American National Standards Institute (ANSI) in
1986, and of the International Organization for Standardization (ISO) in1987

What Can SQL do?


 SQL can execute queries against a database
 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create stored procedures in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views

What is RDBMS?
RDBMS stands for Relational Database Management System.
RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM
DB2, Oracle, MySQL, and Microsoft Access. The data in RDBMS is stored in database objects
called tables.
A table is a collection of related data entries and it consists of columns and rows.

MYSQL TERMINOLOGY
Structure Query Language
A non-procedural 4GL used for querying upon relational database.

DDL: Data Definition Language


Commands that allow you to perform tasks related to data definition i.e creation, alter and deleting
the structure of tables and database. E.g :
Create Table
Drop Table
Alter Table
Create Database
Drop Database

DML: Data ManipulationLanguage.


Commands that allow you to make changes in the data of the table. E,g:
Update
Delete
Insert Into
Relational Data Model
In this model data is organized into tables i.e. rows and columns. These tables are called
relations.

Relation:
Table in Database
Domain:
Pool of values from which the actual values appear.
Tuple:
A row/record of a relation or table
Attribute:
A column/field of relation
Degree:
Number of attributes
Cardinality:
Number of tuples/rows/records
View:
Virtual table that does not really exist in its own right.
Primary Key:
A primary key is a field/attribute of the table which uniquely identify each record in a table. It
ensures that no two records have the same value in the column of the primary key field. For
example in a Student table , Rollno or Amno can be made as primary key
Candidate Key:
A Candidate Key is the one that is capable of becoming Primary key i.e., a field or
attribute that has unique value for each row in the relation. E.g In Student table , Rollno, Admno ,
Aadhar No are the candidate keys
Alternate Key:
A candidate key that is not primary key is called alternate key.
Foreign Key:
A non-key attribute, whose values are derived from the primary key of some other table.

Accessing/Opening Database in MySql :


Through USE keyword we can start any database
Syntax:
USE <database Name>;
Example: USE STUDENT;

CREATING TABLE IN MYSQL


Through Create table command we can define any table.
CREATE TABLE <tablename>
(<columnname><datatype>[(<Size>)],… ..... );
e.g
CREATE TABLE Student(SRollNo integer, Sname varchar(20));

SQL Constraint:
A Constraint is a condition or check applicable on a field or set of fields. Different types of
constraint that can be applied to columns in a table are:
NOT NULL
UNIQUE
DEFAULT
CHECK
PRIMARY KEY
FOREIGN KEY
e.g
CREATE TABLE student (Srollno integer NOT NULL, …);
CREATE TABLE student (Srollno integer UNIQUE, …);
CREATE TABLE student (Srollno integer NOT NULL, Sclass integer, Sname varchar(30),
Sclass DEFAULT 12);
CREATE TABLE student (Srollno integer CHECK (Srollno>0), Sclass integer, Sname
varchar(30));
CREATE TABLE student (Srollno integer NOT NULL PRIMARY KEY, Sclass integer,
Sname varchar(30));
CREATE TABLE teacher (Tid integer NOT NULL, FOREIGN KEY (Studentid )
REFRENCES student (Sid));

Viewing structure of table:


DESCRIBE/DESC <tablename>;
DESCRIBE student;

INSERTING DATA INTO TABLE


The rows are added to relations using INSERT command.
INSERT INTO <tablename>[<columnname>]
VALUES (<value>, <value>…);
e.g
INSERT INTO student (Sid, Sname) VALUES (100,’ABC’);

SELECT COMMAND:
It lets us make queries on the database. It is used to display records from the table.
SELECT * FROM table name WHERE condition;
SELECT * FROM student WHERE Sid=100;

Eliminating Redundant/Duplicate Data from a particular column only during display


DISTINCT keyword eliminates redundant data
SELECT DISTINCT Sid FROM Student;

Selecting from all the rows-ALL Keyword


SELECT ALL Sid FROM Student;

Using column aliases:


SELECT <column name> AS [columnalias][,…]
FROM <tablename>;
SELECT rollno, name AS “studentname”
FROM student;

Condition based on a range:


Keyword BETWEEN used for specifying range in the condition of the query.
e.g
SELECT rollno, name FROM student WHERE rollno BETWEEN 10 AND 20;

Condition based on a list( Using IN operator):


Keyword IN used for selecting values from a list of values.
e.g
SELECT rollno, name FROM student WHERE rollno IN (10, 20, 60);

Condition based on a pattern matches:


Keyword LIKE used for making character comparison using strings
1. percent(%) matches any substring
2. underscore(_) matches any character
e.g
SELECT Rollno, name FROM student WHERE name LIKE ‘%ri’;

Modifying data in tables:


Existing data in tables can be changed with UPDATE command.
e.g
UPDATE student SET Sclass=11 WHERE Sname=’Ram’;
Deleting data/records from tables:
Tuples/records in a table can be deleted using DELETE command.
e.g
DELETE FROM student WHERE Srollno>10;

MySQL Functions:

A function is a special type of predefined command set that performs some operation and
returns a single value.
Functions in MySQL are classified into two types:
 Single Row Functions
 Multiple Row Functions (Aggregate Functions)

Single Row Functions:
These functions operate o a single value to return a single value. They are further categorized into :

1. String functions : (Lower / LCASE( ), Upper/UCASE( ), Concate( ), Instr( ), Length( ),


RTrim( ), LTrim( ), Substr( ))
2. Numeric function :(Round( ), Truncate( ), Mod( ), Sign( ))
3. Date functions: (Curdate( ), Date( ), Month( ), year( ), DayName( ), DayofMonth(),
DayofWeek( ), DayofYear( ), Now( ), SysDate())

Multiple Row Functions or Aggregate functions


Aggregate functions are functions that can work on multiple rows of a database. They are used
in a similar way to functions in spreadsheets (Microsoft Excel).
These functions will return a value when they are run on a row. They will look at the values
in a row and then perform the function on the values. Aggregate functions are used to implement
calculations based upon a particular column. These functions always return a single value.
Let us discuss some of the commonly used aggregate functions on the basis of the table Student
given below:
Table: Student
RollNo Name Gender Marks DOB Stream
1 Raj Kumar M 93 17-Nov-2000 Science
2 Deep Singh M 98 22-Aug-1996 Commerce
3 Ankit Sharma M 76 02-Feb-2000 Science
4 Radhika Gupta F 78 03-Dec-1999 Humanities
5 Payal Goel F 82 21-April-1998 Vocational
6 Diksha Sharma F 80 17-Dec-1999 Humanities
7 Gurpreet Kaur F NULL 04-Jan-2000 Science
8 Akshay Dureja M 90 05-May-1997 Commerce
9 Shreya Anand F 70 08-Oct-1999 Vocational
10 Prateek Mittal M 75 25-Dec-2000 Science

Functions Description:

a) SUM ( ) : Returns the total sum of a numeric column.


For example:;
Select sum(marks) From student;

It displays the sum of all the marks in the table student.


Output: 742
b) AVG ( ) : is used to find the average value of any column. It accepts only one column
name.

For example:;
Select avg(marks) From student;

It displays the average of all the marks in the table student.


Output: 82.44

c) MAX ( ) : Returns the largest/highest value among the given set of values of any column.
NULL values are ignored.

For example:;
Select max(marks) From student where gender=’M’;

It displays the highest the marks in the table student for only Male students.
Output: 98

d) MIN ( ) : Returns the lowest/ smallest value among the given set of values of any column.
NULL values are ignored.

For example:;
Select min(marks) From student where stream = “Science”;

It displays the lowest the marks in the table student for only science students.
Output: 75

e) COUNT ( ) : is used to count the number of values in a column. It takes one argument,
which can be any column name. Count() function returns the number of non NULL values
in that column. If we use Count(*) , then it will count the total number of records in the
table.

For example:
Select count(marks) From student;

It displays the number values in marks column in the table student which are not null.
Output: 9

Select count(*) From student;

It displays the number of records in the table student


Output: 10
Important Points:

1. You cannot use an aggregate function in a WHERE clause.


2. We can use two or more aggregate expressions in a SELECT statement as shown below:
SELECT MIN (marks), MAX (marks) FROM Student;

SUMMARIZATION of Aggregate Functions with an example:


SORTING IN SQL : ORDER BY clause:
ORDER BY clause is used to sort data in ascending or descending order based on one or more
columns.
Syntax:
SELECT <column name> [, <column name>, …]
FROM <table name>
[WHERE <condition>]
[ORDER BY <column name>];
e.g

SELECT *
FROM student WHERE marks>50
ORDER BY name;

Order By clause sorts the records in ascending order by default. Therefore , in order to sort the
records in descending order , DESC keyword is to be used.
e.g
SELECT *
FROM student WHERE marks>50
ORDER BY name DESC;

Ordering Data on Multiple Columns

To order or sort the result set on multiple columns, you can specify multiple column names in
ORDER by clause along with the desired sort order .
For example:
Select * from student
Order by section asc, marks desc

Explanation: First sort field is section in ascending order and for all records of same section , the
sort field is marks with descending order. It means all the students of same section will be
displayed with highest marks first.

The SQL GROUP BY Statement


The GROUP BY statement group 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.

Grouping Result by using Group By: The GROUP BY clause is used in a select statement in
conjunction with aggregate functions to group the result based on DISTINCT or ALL values in a
column. Grouping can be done by column name, or with aggregate functions in which case the
aggregate produces a value for each group. Consider the following table:
Table: Student
RollNo Name Gender Marks DOB Stream
1 Raj Kumar M 93 17-Nov-2000 Science
2 Deep Singh M 98 22-Aug-1996 Commerce
3 Ankit Sharma M 76 02-Feb-2000 Science
4 Radhika Gupta F 78 03-Dec-1999 Humanities
5 Payal Goel F 82 21-April-1998 Vocational
6 Diksha Sharma F 80 17-Dec-1999 Humanities
7 Gurpreet Kaur F NULL 04-Jan-2000 Science
8 Akshay Dureja M 90 05-May-1997 Commerce
9 Shreya Anand F 70 08-Oct-1999 Vocational
10 Prateek Mittal M 75 25-Dec-2000 Science

For example:
1. To display the total number of students in each stream.

Query:
Select Stream, count(*) From Student Group By Stream
Output: Stream Count(*)
Science 4
Commerce 2
Humanities 2
Vocational 2

2. To display total number of students gender wise.


Query:
Select Gender, count(*) From Student Group By Gender

Output: Gender Count(*)


Male 5
Female 5

HAVING Clause
The HAVING clause is used in combination with the GROUP BY clause. The purpose of using
HAVING clause with GROUP BY is to allow aggregate functions to be used along with the
specified condition. This is because the aggregate functions are not allowed to be used with
WHERE clause. Thus, if any aggregate function is to be used after the FROM clause in a SELECT
command, then instead of using WHERE clause, HAVING clause should be used.
Syntax:
SELECT <column1>,<column2>,<aggregate function>...
FROM <tablename>
GROUP BY <column name>
HAVING <condition>

For Example: To display total marks stream wise for only those streams in which highest
marks are less than 85.
Query:
Select Stream, SUM(Marks)
From Student
Group By stream
Having Max(Marks)<85;

Output;
Stream SUM(Marks)
Science 151
Commerce 0
Humanities 168
Vocational 152
AGGREGATE FUNCTIONS & CONDITIONS ON GROUPS (HAVING
CLAUSE)
You may use any condition on group, if required. HAVING clause is used to apply a condition on
a group.
Examples : 1. Select Job, Sum(Pay) From Employee
Group by Job
Having Sum(Pay)>=8000;

2 Select Job, Avg(Pay) From Employee


Group by Job
Having Avg(Pay)>=7000;

3. Select Job, Min(Pay), Max(Pay), Avg(Pay) From Employee


Group By Job
Having Sum(Pay)>=8000;

WHERE Vs HAVING
WHERE clause works in respect of the whole table but HAVING clause works on GROUP By
only. If WHERE and HAVING both are used, then WHERE will be executed first.

MIND MAP
Class : XII (2020-2021)
Subject: Informatics Practices
ASSIGNMENT
Note: Assignment is to be done in IP register.

Q 1) Expand and explain the following terms:


a) SQL
b) DDL
c) DML
Q 2) Enlist any two advantages of SQL.
Q 3) Categorise the following as DDL and DML:
Insert into, Alter, Create table, Update, delete, drop
Q 4) Ravi created a database ‘Games’ a month back. He is not sure whether
database is still existing or not. Write the command which can help him.
Q 5) How would you calculate 13*7/2 in MYSQL?
Q 6) Is select a DDL or DML? Justify.
Q 7) Which operator is used to make complex conditions in SQL?
Q 8) Write a command to increase the size of empname column to 50 characters
in an emp table.

Q 9) Ashu wrote the following query which is not giving the correct output. Find
the possible reason
Select * from emp where city =”Delhi” and city=”Bangalore”;

Q 10) What is the use of wildcard characters?


Q 11) Which operator is used for pattern searching?
Q 12) Ms. Shalu is using a table 'customer' with custno, name, address and phone.
She needs to display name of the customers, whose name ends with letter 'S'.
She wrote the following command, which did not give the result.
Select * from customer where name="S%";
Write the correct query.

Q 13) A student created a table Sports in MySQL:


Table: Sports
S_Id Name

SW01 NULL

SB02 Football

SB03 Hockey

SW04 Swimming

Q 14) What will be the output of the following queries:


a) SELECT Name FROM Sports WHERE Name like ‘_o%’;
b) SELECT * FROM Sports WHERE Name IS NOT NULL;

Q 15) A School table is created with fields: School_id, Category, Zone, Strength.
What is wrong with the following statement?
Delete Zone from School;
Q 16) Raman wants to change the Name of the TV Show “Comedy Nights” with
“ Comedy Nights with Kapil”. He is confused which command to use. Help
him write the correct SQL.
Q 17) Sohan needs to display name of customers, who have "o" as the third
character in their name. He wrote the following query.
Select name from customer Where name like
“**o%";
But the query is not producing the result. Identify the problem.

Q 18) Write SQL query to add a column totalprice with datatype numeric and size
10, 2 in a table product.

Q 19) Differentiate between


a) update and alter table command.
b) order by and group by clause

Q 20) Is there any Difference between Count() and Count(*) function. Justify by
the help of example.

Q 21) Differentiate between the following commands


Delete from emp;
Drop table emp;

Q 22) Pooja created a table 'Result' in SQL with fields as


Fields datatype
Studname Varchar(10)
Marks int
Result char(1)
She was unable to insert the marks as 75.50 in the table .Identify the problem and
write the command to make necessary changes in the table?

Lab Exercise:
Q1. Consider the table Emp and insert the following records:

Q2. Ms. Shalini wants to keep the record of her students. She needs to create a
table Student having following structure. Write the command to create the
following table and answer the question based on it:

TABLE : Student
Fields Data Type Size
Roll_No INTEGER 4
Name VARCHAR 20
Stipend INTEGER 7
Stream VARCHAR 15
Grade CHAR 1
i. Insert 15 records with relevant information, in the table student
ii. Display all the records of the table Student.
iii. Delete the Student Whose Roll no is 100.
iv. Change the Stream of Student to 'Computer' Whose Roll no. is 536.
v. View structure of the table created by you.
vi. Drop the column Grade from the table Student.
vii. Display the list of streams available.(Value should not be repeated)
Q3. Create the following table item.

Column name Data type Size

Itemno Integer 3

Iname Varchar 15

Price Decimal 10,2

Quantity Integer 3

Insert the following information: Table: Item

Itemno Iname Price Quantity

101 Soap 50 100

102 Powder 100 50

103 Face cream 150 25

104 Pen 50 200

105 Soap box 20 100


Write queries based upon item table given in Q. no 3.
a) Add a new column Total in the table. Select appropriate datatype.
b) Find the total (total=price * quantity).
c) Display all items information.
d) Display item name and price value.
e) Display price of Item ‘Soap’.
f) Display the information of all items whose name starts with letter 's'.
g) Display the information in ascending order of item name.
h) Display item name and price in descending order based upon price.
i) Display item name whose price is in the range 50 to 100.
j) Increase price value by 100.
k) Remove powder information.

l) Remove total column.


m) Remove the table item along with structure.
Write outputs based upon item table given in Q. no 3.

a) select sum(price) from item;

b) select avg(price) from item;

c) select min(price) from item;

d) select max(price) from item;

e) select count(price) from item;

f) select distinct price from item;

g) select count(distinct price) from item;

h) select iname,price*quantity from item;


Q4) Create the table Students having following structure:
Column name Data type Size

Admno Integer 3

Name Varchar 20

Average Integer 3

Sex Char 1

Scode Integer 4

Insert the following information: Students

Admno Name Average Sex Scode

501 Savita Gupta 98 M 111

502 Kavita Murti 73 F 333


704 Rashika Mathur 85 F 111
723 Rahul Bansal 60 M 444

800 Sahil Chopra 78 M 333

921 Rohit Saini 85 M 222

955 Anjali Mukherjee 64 F 444

983 Smriti Aggarwal 80 F 222


Write queries based upon item table given in q. no 5.

i. Display all information about students.


ii. Display information of Sahil Chopra.

iii. Display number of students in the table.

iv. Display number of students in each sex.

v. Display students' information in ascending order of name.

vi. Display students' information in descending order of average marks.

vii. Display students' name starting with letter "S".

viii. Display students' information, whose name ends with "ee".

x. Display students' information, whose average marks are in between 80 to


90.

xi. Display students' info. who are either getting average marks of more than 80
or having scode 333 .

xii. Display students' name and average marks, whose scode is 444 and 111.

xvi. Display maximum, minimum and sum of average marks in each scode.

xvii. Count number of female students.


Q5. Create the following table Stream.

Column name Data type Size


Scode Integer 3
Sname Varchar 20
Place Varchar 10

Insert the following information in Stream


Scode Sname Place

111 Science SBlock

222 Commerce CBlock

333 Humanities HBlock

444 Vocational ABlock

Write queries based upon the above tables-Students (given in Q4) and Stream:

a) To display Admno, Name, Sex and Average from Student's table and Stream
name (Sname) and place from Stream table with respect to Scode.

b) Add the following information into the


student table.
800 Deepika Gupta 83 F 222

c) Display information of all students belonging to Vocational Stream.

d) Give the output of the following SQL queries.

I. Select sum(Average) From students Where sex='M';

II. select distinct Scode From students;

e) Give an Increment of 2 marks to the student having Scode as 444.

f) Remove column place.

g) Remove the table stream.

Q6. Give the output of the following SQL queries:

CARNAME COLOR CHARGES DEALER

INDIGO BLACK 800000 AUTOWORLD


WAGON-R SILVER NULL CARWORLD
ECO SPORTS RED 1000000 KARTIKEY
ALTO BLACK 350000 GURUKRIPA

a) SELECT COUNT(DISTINCT color) FROM CARDEN;


b) SELECT MAX(Charges),MIN(Charges) FROM CARDEN;
c) SELECT COUNT(*) FROM CARDEN;
d) SELECT CarName FROM CARDEN WHERE Charges>500000;
e) SELECT CarName FROM CARDEN WHERE COLOR LIKE ‘%K’;
f) SELECT COLOR FROM CARDEN WHERE CARNAME LIKE ‘I%’;

You might also like