UNIT-2 SQL
UNIT-2 SQL
INFORMATICS PRACTICES
UNIT-2
Database Query using SQL
This pdf contains
Chapter – 5, 6 ,7
DBMS:
A database management system (DBMS) is a software package designed to define, manipulate, retrieve and
manage data in a database.
Field/ Attribute: The column of a table is known as field. Example: ID, Name etc.
Tuple : A single row of a table, which contains a single record for that relation is called a tuple.
Domain: A pool of values from which the actual values appearing in a given column are drawn.
Types of keys:
Primary key: It is used to uniquely identify the record from the table. It does not contain null values.
Unique key: It is used to uniquely identify the record from the table. It does not have null value.
Foreign key: A foreign key is a column or group of columns in a relational database table that provides a
link between data in two tables
Candidate key: The minimal set of attribute which can uniquely identify a records.
Alternate key: It is a candidate key which is currently not the primary key
Composite key: When a primary key is made of two or more columns, then such a key is called
composite key.
Database terms:
Data inconsistency: Multiple copies of same data when do not match, it is called data inconsistency.
Data isolation: Data isolation is the situation where data of one file cannot be mapped to other related file
in the absence of links or mappings.
Data Dependence: Close relationship between data stored in the file and the software programs that
update and maintain those files is called data dependence.
Data redundancy: It refers to the storage of the same data multiple times.
Database Schema: It represents database tables and structures along with their relationships.
Database instance: The data which is stored in the database at a particular moment of time.
Data dictionary: It contains metadata such as the definitions of all schema objects in the database along
with information.
Query: A Query is a type of command that retrieves data from a database stored on a server.
Database engine: It is a underlying software component that a DBMS used to create , read , update and
delete data from a database.
Referential integrity: It is a system of rules that a DBMS uses to ensure the relationships between records
in related tables are valid, and that users don’t accidentally delete or change related data.
---------------------------------------------------------------------------------------------------
Relational database : In relational data model , data is organized into tables. These tables are called
relations. Example: Two tables employee and department are shown below, these tables are related to
each other using ID field.
Q: Name the type of relationship which is created between two tables, if one table has only one matching
record in others table.
Ans: One to one
Example: Suppose you a table: Employee . Find the degree and cardinality of the table.
SQL:
SQL is Structured Query Language, which is a computer language for storing, manipulating and retrieving data
stored in a relational database.
It was developed by IBM researcher Raymond Boyce in 1970. Logo of SQL is dolphin
Features of SQL
1. Easy to use.
2. Security
3. Fast Speed
Most commonly used datatypes for Table columns
Datatype Use
Int/ number It is used to store integer values ( positive and negative).
Ex: 25, 46, -87, -74
CHAR used for columns which will store char values (single character).
Ex: B, X, S
DATE used for columns which will store date values in format.
DD-MM-YYYY , MM-DD-YYYY ,YYYY-MM-DD
TEXT used for columns which will store text which is generally long in length.
Memo It is used to store more than 2000 characters
Boolean It is used to store Tue or False value.
DATETIME It is used to store date and time values.
YYYYMMDD HH:MM:SS
DATE It is used to store date and time values.
YYYYMMDD
SQL Commands
1. DDL: Data Definition Language
Command Description
DML commands are used for manipulating the data stored in the table and not the table itself.
Command Description
Data control language are the commands to grant and take back authority from any database user.
Command Description
grant grant permission of right
revoke take back permission.
Data query language is used to fetch data from tables based on conditions that we can easily apply.
Command Description
select retrieve records from one or more table
----------------------------------------------------------------------------------------------------
SQL Queries:--
Creating database
Delete database:
Syntax: Drop Database name
Example: Drop Student
Using Database
Ex1: Create table student with fields Roll_no, name , dob, fees.
----------------------------------------------------------------------------------------------------------------------------
Syntax:
Output:
Syntax:
Output:
ID NAME FEES ADDRESS
21 2000
----------------------------------------------------------------------------------------------------------------------
3. ALTER : This command is used for altering the table structure, such as,
to add a column to existing table
to rename any existing column
to change datatype of any column or to modify its size.
to drop a column from the table.
OUTPUT:
ID NAME AGE FEES ADDRESS
OUTPUT:
ID NAME AGE FEES LOCATION
ALTER Command: Drop a Column
Syntax- ALTER TABLE table_name DROP(column_name);
example - ALTER TABLE student DROP( address);
OUTPUT:
ID NAME AGE FEES
-----------------------------------------------------------------------------------------------------------------------
4. SELECT command:
This command is used to retrieve data from the database.
Syntax:-
a. Updating Column
Output:
ID NAME FEES ADDRESS
21 vishal 2000 Delhi
22 Naman 3000 Pune
23 vikas 4000 mumbai
Output:
ID NAME FEES ADDRESS
21 abhi 2000 Delhi
22 Naman 3000 Pune
23 vikas 4000 mumbai
Output:
TRUNCATE command
TRUNCATE command removes all the records from a table. But this command will not destroy the table's
structure.
Syntax:- TRUNCATE TABLE table_name.
6. DELETE command
DELETE command is used to delete data from a table.
7. DISTINCT keyword
The distinct keyword is used with SELECT statement to retrieve unique values from the
table. Distinct removes all the duplicate records while retrieving records from any table .
Syntax
SELECT DISTINCT column-name FROM table-name;
Lets take a sample table student:
ID NAME FEES ADDRESS
21 arun 6000 Meerut
22 Naman 3000 Pune
23 Vika 4000 Mumbai
24 santu 6000 pune
SELECT DISTINCT FEES FROM Student
The above query will return only unique salary from Student table.
FEES
6000
3000
4000
AND operator
AND operator is used to set multiple conditions with the WHERE clause.
SELECT * FROM Emp WHERE salary < 10000 AND age > 25
The above query will return records where salary is less than 10000 and age greater than 25.
OR operator
OR operator is used to combine multiple conditions with the WHERE clause.
SELECT * FROM Emp WHERE salary < 10000 OR age > 25
The above query will return records where salary is less than 10000 OR age greater than 25.
SQL – Constraints
Following are some of the most commonly used constraints available in SQL.
NOT NULL Constraint − Ensures that a column cannot have NULL value.
DEFAULT Constraint − Provides a default value for a column when none is specified.
UNIQUE Constraint − Ensures that all values in a column are different.
PRIMARY Key − Uniquely identifies each row/record in a database table.
FOREIGN Key − Uniquely identifies a row/record in any of the given database table.
CHECK Constraint − This constraint ensures that all the values in a column satisfies certain conditions.
INDEX − Used to create and retrieve data from the database very quickly.
SET NotNull :
i. Which key can be chosen as the primary key of the above table ?
Ans. SID OR Phone
v. Which key can be chosen as the unique key of the above table
Ans. Phone
vi. Name two fields that have text data type in the above table.
Ans: NAME , AREA
vii. Name two fields that have NUMBER data type in the above table.
Ans: SALARY, PHONE
-- - - - - - - - - - - - - --- - - - - - - - - -
II .Display the name and age of all the employees from the table.
Ans: SELECT NAME, AGE from EMPLOYEE ;
III . Display all the names of the employees whose age is greater than 20.
Ans: SELECT NAME from EMPLOYEE where ( AGE > 20) ;
Chapter-6 MySQL functions
Functions: A function is a special type of predefined command set that performs some operation and
returns a single value.
Math functions:
These functions are the functions which accept and return mathematic values.
1. POWER( ) / Pow : This function returns a number m raised to the nth power.
Syntax: POWER( m, n)
2. MOD( ) : This function returns the modulus of the given two numbers.
Syntax: MOD (m , n )
3. ROUND( ): This function returns a number rounded off as per given specifications.
Syntax: ROUND(m , n )
Text Functions:
1. UPPER/ UCASE : This function converts the given string into upper case.
Syntax: UPPER (str)
2. LOWER/ LCASE : This function converts the given string into lower case.
Syntax: LOWER (str)
Q: Display 4 characters extracted from 3 rd left character onwards from string ‘ABCDEFG’.
Ans: Select SUBRSTR(‘ABCDEFG’ , 3 , 4 )
Output: CDEF
Q: Write a query to extract institute code from the string ‘USS/23/67/09’. The first 3
characters tell the institute code.
Ans: Select LEFT ( ‘USS/23/67/409’ , 3 ) ;
Output: USS.
Q: Write a query to extract institute code from the string ‘USS/23/67/09’. The last 3 characters tell
the institute code.
Ans:Select RIGHT ( ‘USS/23/67/409’ , 3 ) ;
Output: 409 .
7. LTRIM : this function removes spaces from the left of the given string.
Syntax: LTRIM (str)
Q: Write a query to remove leading spaces of string ‘ Hello ‘.
Ans: Select LTRIM (‘ Hello ‘ );
Output: Hello
8. RTRIM : this function removes spaces from the right of the given string.
Syntax: RTRIM (str)
10. INSTR : This function searches for given second string into the given first string.
Syntax: INSTR (str1, str2)
Q: Write a query to extract date from a given datetime value ’ 2020-11-09 12:10: 03’.
Ans: Select DATE ( ‘2020-11-09 12:10: 03’ )
Output: 2020-11-09
3. MONTH( ) : this function returns the month from the date passed.
Aggregate functions:
1. Sum( ): This function is used to add all values in the given column .
2. Avg( ): This function is used to find the average of selected values.
3. Max( ): This function is used to find the maximum value from given values .
4. Min( ):This function is used to find the minimum value from given values .
5. Count( ): This function is used to count the given values in columns..
Example based on aggregate functions:-
Q: Find the output of the given queries using table employee:-
Table: Employee
Example:
2. Having:
This conditional clause returns rows where aggregate function results matched with given
conditions only.
3. Order by: ORDER BY returns sorted items in ascending and descending order .
………………………………………………………