Professional Documents
Culture Documents
Unit-3 ch-11,12,13,14 SQL
Unit-3 ch-11,12,13,14 SQL
Data refers to the raw facts and figures, it is unorganized, unstructured and difficult to
understand.
Information refers to the raw facts and figures, it is unorganized, unstructured and difficult to
understand.
DATABASE A collection of data is referred as database. Databases are designed to offer an
organized mechanism for storing, managing and retrieving information. They do so
through the use of tables. It is an well-organized collection of information about an
entity or organization.
Data Base A database system is basically a computer based record keeping system. It
System contains a repository of data which is needed for information processing in an
organization. It allow the user to access and manipulate the data contained in the
database in convenient and effective manner.
DBMS A database management system is basically a computer based record keeping
system. The software that takes care of database. It maintains creation, addition,
deletion, modification of files.
Relational Data It is a data model proposed by E.F. Codd for database management. In this model,
Model the data is organized into tables (i.e. rows & columns). These tables are called
relations because each row in a table represents a relationship among a set of
values.
Domain A domain is a pool of values from which the actual values appearing in a given
column are drawn.
Degree The number of attributes in a relation determines the degree of a relation.
Cardinality The number of rows in a relation is known as Cardinality.
RDBMS RDBMS stands for Relational Database Management System. RDBMS is the
basis for SQL, and for all modern database systems like MS SQL Server, IBM
DB2, Oracle, MySQL, and Microsoft Access.
Entity It is an object/thing which can be distinctly identified. It may be person or thing or
item.
Relation The table in a database is called relation where the records are stored.
Tuple The records in a relation are called tuples. It can also be called records or rows.
Attribute The column or field in a relation is called attribute.
Cardinality The number of records present in a table.
Degree/Arity The number of fields in a table.
Conventional File Processing System for Data Storage (used in old days)
➢ In a typical file processing system, permanent records are stored in various files. A no. of different
application programs are written to add and extract data from these files. But this scheme has a no. of
limitations such as :
• Data Redundancy (duplication of data)
• Data inconsistency (multiple data copies which do not match)
• Non-sharable data
• Non-standardized data
• Insecure data
• Incorrect data
➢ DBMS provides solution to all these problems by providing a centralized control of data.
1. Primary Key
➢ It is a field or combination of fields through which a record can be uniquely identified in a table.
➢ The primary key field(s) should not be null.
➢ In some tables, combination of more than one attribute provides a unique value for each row. In
such tables, group of these attributes is declared as primary key. Such a primary key that
constitutes of more than one attribute is called a Composite Primary Key.
➢ There can be only one primary key in a table.
2. Candidate Key
➢ All attribute combinations in a table that can serve as primary key are called candidate key.
➢ They behave the candidates for the primary key.
3. Alternate Key
➢ From the different group of candidate key, the user has to decide one group as primary key.The
other groups are called alternate key.
4. Unique Key
➢ The domain of the field will be unique.
➢ One value can be NULL.
➢ We can have more than one unique keys in a table.
5. Foreign Key
➢ A non key attribute of a table whose value derives from primary key of another table .
Examples of RDBMS Software
• Microsoft SQL Server
• MySQL
• Oracle
• SQLite
• IBM DB2
• Teradata
• PostgreSQL
SQL
➢ SQL is a standard language for accessing and manipulating relational databases.
➢ SQL stands for Structured Query Language
➢ SQL lets you access and manipulate databases
➢ SQL is an ANSI (American National Standards Institute) standard
➢ SQL is not case sensitive
➢ Some database systems require a semicolon at the end of each SQL statement.
Features of SQL
SQL can
➢ create new databases
➢ create new tables in a database
➢ retrieve data from a database
➢ insert records in a database
➢ update records in a database
➢ delete records from a database
Advantages of SQL
➢ Ease of use: It is easy to learn and use
➢ Large volume of data handled easily
➢ No specific code required. Only commands to be remembered
➢ Easily link to most of other high level language
➢ Portable. It is available with all type of DBMS and RDBMS
➢ Not case sensitive
➢ Powerful language
➢ Reliable
➢ Freedom of data abstraction
➢ Complete language for the database
1 Ashi
2 Santanu
4 Bhumika
When the following commands are executed in sequence, the end result produced is shown
below:
RollNo NAme
1 Ashi
2 Santanu
4 Arshi
5 Gagan
6 Sahil
MySql
It is the most popular open source RDBMS. It works on client - server architecture.
Advantages of MySQL
➢ Reliable and high performance
➢ Modifiable
➢ Multi-platform support
➢ Powerful processing capabilities
➢ Integrity checks
➢ authorization
CHAR(size) Holds a fixed length string (can contain letters, numbers, and special
characters). The fixed size is specified in parenthesis. Can store up to 255
characters
VARCHAR(size) Holds a variable length string (can contain letters, numbers, and special
characters). The maximum size is specified in parenthesis. Can store up to 255
characters. Note: If you put a greater value than 255 it will be converted to a
TEXT type
DECIMAL(M,N) It stores the number with or without the fractional part. M denotes ( number of
digits before and after the decimal +1 for decimal point) and n denotes the
digits to the right side of the decimal point.
To avoid error in case the database already exists in the system , we can write the following query :
Create database if not exists demo;
TO CLOSE DATABASE
If we want to close an already opened database, then we write :
close databases;
TO DELETE A DATABASE
To remove a database completely from the memory, we write:
Drop database demo;
2. DEFAULT CONSTRAINT
This constraint ensures that a column may be given a default value.
This prevents nulls from occurring in a row, if a row is inserted without a value for any particular field.
This constraint can be used at column/table level.
3. UNIQUE CONSTRAINT
This constraint enforces every value in a column or set of columns to be unique.
No two rows in a table can have same value for that column.
Column value may be NULL.
We can apply this constraint on more than one columns.
This constraint used at column/table level.
5. CHECK CONSTRAINT
This constraint explicitly defines a condition that each row must satisfy. A single column may have more
than one conditions and more number of check constraints are possible in a table.
This constraint used at column/table level (when compared between two columns).
The data type specifies what type of data the column can hold and size denotes the space required for it.
Constraint names to be provided as per requirement.
Example :
The corresponding values are to put within braces. If the datatype of field is char or date, the value should
be placed within single quotes(‘) otherwise value should be put as it is.
The second form specifies both the column names and the values to be inserted:
SELECT column_name(s)
FROM table_name
and
SELECT * FROM table_name
Example : To select the content of the columns name and class from table student
DISTINCT Clause
In a table, some of the columns may contain duplicate values. This is not a problem; however, sometimes
you will want to list only the different (distinct) values in a table.
The DISTINCT keyword can be used to return only distinct (different) values.
Example : To select only the distinct values from the column named "City" from the table above.
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
Example : To display the list of students who live in delhi
Example : To display the details of all the students who live in delhi and study in class 12
Example : To display the details of all the students who live either in delhi or mumbai
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern
SQL Wildcards
SQL wildcards can substitute for one or more characters when searching for data in a database.
SQL wildcards must be used with the SQL LIKE operator.
Example :
Condition Pattern
name starts with a a%
name ends with a %a
name contains a %a%
name contains ne %ne%
name is a 4 letter word ____
name is a 4 letter word and starts with n n_ _ _
name is a 4 letter word and ends with a ___a
name is a 4 letter word, starts with a and ends with n a__n
name has 2nd character as a _a%
name as 2nd last character as a %a_
SELECT *
FROM student
WHERE name NOT LIKE ‘%a%’ ;
The IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
SQL IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)
Example : Display the details of all those students who do not live in delhi and Mumbai.
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2
Example : To display the names of all those students whose percentage lies between 90 to 100
SELECT name
FROM student
WHERE percentage between 90 and 100 ;
The NOT BETWEEN Operator
Example : To display the student details whose percentage does not lie between 50 to 100
SELECT *
FROM student
WHERE percentage NOT BETWEEN 50 and 100 ;
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC / DESC
Example : Display the name and percentage of all students in descending order of their percentage.
Example : Display the name and percentage of all students who live in Delhi in descending order of
their percentage.
Example : Display the name and class of all students whose percentage field is blank.
Example : Display the name and class of all students whose grade or percentage is not blank.
Example : To display the name and percentage of all students in formatted manner as
“Studentname scores per%” , display the data in descending order of their percentage.
COLUMN ALIAS:
We can change the heading of a particular column while printing the result of select query as below :
Example : To display the name and percentage of all students, change the heading name to student
name.
or
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or
records that should be updated. If you omit the WHERE clause, all records will be updated!
UPDATE student
SET city = ‘mumbai’;
Example 2 : To change the city as ‘mumbai’ and class as 12 for all the students.
UPDATE student
SET city = ‘mumbai’ , class = 12 ;
Example 3 : To change the city of all those students to Mumbai who currently live in chennai.
UPDATE student
SET city = ‘mumbai’
where city = ‘chennai’ ;
Example 4 : To change the percentage to 90 and grade to A2 for all those students, whose
percentage or grade field is blank.
UPDATE student
SET percentage = 90 , grade = ‘A2’
where percentage is null or grade is null ;
Example 5 : To change the city field to blank for all the students who currently live in delhi.
UPDATE student
SET city = null
where city = ‘delhi’ ;
Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or
records that should be deleted. If you omit the WHERE clause, all records will be deleted!
Example 2 : To delete the record of all the students whose percentage is less than 90 from the table
student:
Example 1 : To add a new column gender in the table student, datatype character, length 10
OR
OR
OR
Example 3 : To count the number of records which do not have grade field blank
Example 2 : To find the sum of column percentage for students who live in delhi
Example : To find if any of the customers have a total order of less than 2000.
Now we want to find if the customers "Hansen" or "Jensen" have a total order of more than 1500.
We add an ordinary WHERE clause to the SQL statement:
Table : department
Deptno Deptname Minsal Maxsal
10 Sales 25000 32000
20 Finance 30000 50000
30 Admin 25000 40000
a) Display the details of all the employees who work in sales department.
select *
from employee , department
where deptname = ‘sales’
and employee.deptno = department.deptno ;
b) Display the salary, zone and grade of all the employees of Admin department;
select salary , zone , grade
from employee , department
where deptname = ‘Admin’
and employee.deptno = department.deptno ;
STRING FUNCTIONS
1. CHAR()
Returns the character equivalent for integer passed
Char(65) gives A
65-90 A—Z
97-122 a---z
Select char(70,65,67,69) gives FACE
2. LENGTH()
Returns the length of the string
Select LENGTH(‘computer’) gives 8
3. CONCAT()
It joins second string to the end of first string
Select Concat(‘subroto’,’park’)
give you subrotopark
4. INSTR()
Returns the first occurrence of a character from the string
Select instr(‘computer’,’put’) gives 4
5. LOWER()/ LCASE()
Converts the string into lower case
Select LOWER(‘COMPUTER science’)
gives computer science
6. UPPER()/ UCASE()
Converts the string into upper case
SELECT UPPER(‘COMPUTER science’)
gives COMPUTER SCIENCE
7. LEFT()
Returns the specified number of characters from left side of the string
SELECT LEFT(‘COMPUTER’,3) gives COM
8. LTRIM()
Removes the leading spaces from the string
SELECT LTRIM(‘ COMPUTER’) gives COMPUTER
9. RTRIM()
Removes the trailing spaces from the string
SELECT RTRIM(‘COMPUTER ’) gives COMPUTER
10. TRIM()
Removes the spaces from the string both leading and trailing
SELECT TRIM(‘ COMPUTER ’) gives COMPUTER
11. SUBSTR()
Returns the substring as specified. It works same as MID()
SELECT SUBSTR(‘COMPUTER’,5) gives UTER
SELECT SUBSTR(‘COMPUTER’,3,4) gives MPUT
NUMERIC FUNCTIONS
1. power()/ pow()
Returns the argument raised to the specified power.
Select Pow(2,4) gives 16
Select Pow(2,-2) gives 0.25
Select Pow(-2,3) gives -8
2. Round()
Round(x) : rounds the argument upto 0 decimal place
Round(x, d) : rounds the argument up to ‘d’ decimal places
Select Round(1.23) gives 1
Select Round(1.58) gives 2
Select Round(-1.23) gives -1
Select Round(-1.58) gives -2
Select Round(3.789,1) gives 3.8
Select Round(1.298,0) gives 1
Select Round(23.298,-1) gives 20
3. Truncate()
Truncates the argument to specified number of decimal places
Select Truncate(7.29,1) gives 7.2
Select Truncate(27.29,-1) gives 20
4. mod()
Returns remainder when one number divisible by other number
Select mod(11,4) gives 3
5.sqrt()
Calculates the square root of a number
Select sqrt(16) gives 4.0
6. sign()
Returns sign(1,-1) of a number
Select sign(11) gives 1
Select sign(-11) gives -1
Select sign(0) gives 0
DATE FUNCTIONS
1. now()
Returns the current date and time
Select now()
2. Curdate()
Returns the current system date
Select curdate()
3. Sysdate()
select sysdate()
Returns the current system date and time when the command executes
4. DATE()
Extracts date part of date or datetime expression
Select DATE(‘2010-03-31 10:20:45’) gives 2010-03-31
5. MONTH()
Extracts month part of date passed
Select MONTH(‘2010-03-31’) gives 3
6. YEAR()
Extracts year part of date or datetime expression
Select year(‘2010-03-31 10:20:45’) gives 2010
7. DAYNAME()
Returns the name of the week day
Select DAYNAME(‘2019-11-27’) gives Wednesday
8. DAYOFMONTH()
Returns the day of the month( 1-31)
Select dayofmonth(‘2010-03-31’) gives 31
9. DAYOFWEEK()
Returns the day of week( 1-7)
Select DAYOFWEEK(‘2019-11-27’) gives 3
10. DAYOFYEAR()
Returns the day of the year( 1-365)
Select DAYOFYEAR(‘2019-11-27’) gives 321