14SQL
14SQL
Definition:
SQL is a query language for managing data in relational data base.
SQL architecture:
SJPUC Page 1
CHAPTER 14 SQL
SQL commands:
1. SQL consists of a set of commands.
2. These commands are instructions used to communicate with the data base to perform
specific tasks such as creating tables, adding data to the tables, modifying the data,
accessing the data, deleting the data, setting permission for users & so on.
SQL
1a. CREATE 2a. INSERT 3a. GRANT 4a. SELECT 5a. COMMIT
5b. ROLL
1b. ALTER 2b. UPDATE 3b. REVOKE
BACK
SJPUC Page 2
CHAPTER 14 SQL
1. NUMBER: It’s used to store a numeric value in a field. It may be integer or a real value.
Syntax: NUMBER(n, d)
Where:- n: no of digits
d: no of digits to the right of the decimal points.
Number allows 0, +ve or –ve number
Ex: marks NUMBER(3)
per NUMBER(3, 2)
4. DATE: This data type is used to store the dates in the column. The standard format used is
DD-MM-YY
Syntax: DATE
Ex: dob DATE
doa DATE
5. TIME: This data type is used to store the time in the column. The standard format used is
HH-MM-SS
Syntax: TIME
Ex: dob TIME
doa TIME
SJPUC Page 3
CHAPTER 14 SQL
Example:
CREATE TABLE STUDENT
(
Regno number(6),
Name char(25),
Combination char(5),
DOB date,
Fees number(5),
Total number(3),
City char(20)
);
SJPUC Page 4
CHAPTER 14 SQL
2. DML commands:
2a. INSERT COMMAND:
INSERT INTO command performs the following operations:
• It is used to create new row in a table.
• Loads the value passed into all the columns specified.
Syntax:
INSERT INTO table_name
[(column1,column2,….,column_n)]
VALUES (val1, val2…, val_n);
SJPUC Page 5
CHAPTER 14 SQL
Example:
INSERT INTO student
(Regno, Name, Combination, DOB, Fees,Total, city)
VALUES (001,'Raj','PCMCs', '10-nov-98', 50000, 567, ‘mysore’);
Syntax:
UPDATE table_name
SET column1=value1
[, column2= value2, .…. , columnN=valueN]
[WHERE condition];
Example 3:
change the fees to 18000/- only for those students whose combination is ‘PCMCs’:
UPDATE Student
SET Fees = 18000
WHERE Combination = ‘PCMCs’;
Syntax:
DELETE FROM table_name
[WHERE condition];
Example 1:
DELETE FROM Student;
SJPUC Page 6
CHAPTER 14 SQL
3. DQL commands:
3a. SELECT COMMAND:
SELECT command is used for data retrieval. It can perform selection (σ) & projection(∏)
operations.
Syntax:
SELECT column-list
FROM table
[WHERE condition(s)]
[GROUP BY column-list]
[HAVING condition(s)]
[ORDER BY column-name(s)];
Example:
SELECT * FROM Student;
Note:
Asterisk (*) is used immediately after SELECT command which means all the columns &
rows from the table has to be selected.
Syntax:
SELECT column_name
FROM table_name;
Example:
SELECT Regno,Name
FROM Student;
SJPUC Page 7
CHAPTER 14 SQL
• The above query will list out all the combinations in the table by eliminating the duplicate
values.
Example 1: select all the columns from student table whose total is >=500
SELECT *
FROM Student
WHERE total >= 500;
Example 2: display regno, name & marks from a student table whose total is >=500
SELECT regno,name,Total
FROM Student
WHERE Total >= 500;
Example 1: To list all the students who are not in PCME combination
SELECT *
FROM Student
WHERE Combination <> 'PCME';
Example 2: display regno, name & total from a student table whose total is >400
SELECT regno,name,Total
FROM Student
WHERE Total > 400;
Example 3: select all the columns from student table whose total is >=400 & not in PCMB
combination
SELECT *
FROM Student
WHERE total >=400 AND Combination <> 'PCMB';
SJPUC Page 8
CHAPTER 14 SQL
Example 4: To list all the columns having combination of PCMCs or PCMB combination
SELECT *
FROM Student
WHERE Combination = 'PCMCs' OR Combination = 'PCMB';
Example 5: To list all the columns who are not in science combination
SELECT *
FROM Student
WHERE Combination <> 'PCMCs' AND Combination <> 'PCMB' AND Combination <>
'PCME';
Example 1: To display a list of students with combination PCMB, PCMCs & PCME
SELECT *
FROM Student
WHERE Combination IN ('PCME','PCMB','PCMCs');
Example 2: display regno, name, combination & total from a student table & list all the
students who are not in science combination.
SELECT Regno,Name,Combination,Total
FROM Student
WHERE Combination NOT IN ('PCME','PCMB','PCMCs');
Example 1: display regno, name & total from a student table & list all the students who have
paid the fees between 10000 & 12000
SELECT regno, name, Total FROM Student
WHERE Fees BETWEEN 10000 AND 12000;
Example 2: display regno, name, combination & total from a student table & list all the
students who have not secured the marks between & 400 & 500.
SELECT Regno,Name,Combination,Total
FROM Student
WHERE Total NOT BETWEEN 400 AND 500;
SJPUC Page 9
CHAPTER 14 SQL
Example 1: retrieve all the columns from student & list details of all the students whose
combination contains NULL value.
SELECT *
FROM Student
WHERE Combination IS NULL;
Example 2: display regno, name & list the details of all the students whose fees doesn’t
contain NULL value.
SELECT Regno,Name
FROM Student
WHERE Fees IS NOT NULL;
ORDER BY clause:
• It is used to sort the data either in ascending or descending order based on one or more
columns.
Syntax:
SELECT column_name
FROM table_name
[WHERE condition(s)]
ORDER BY column-name(s) [ASC|DESC];
Example 1: display regno, name from student table & list the students in alphabetical order by their
names.
SELECT Regno,Name
FROM Student
ORDER BY Name;
Example 2: display regno, name,city from student table & list the students in alphabetical
order of their city.
SELECT Regno,Name,city
FROM Student
ORDER BY city;
Example 3: retrieve all the columns from student table & display in alphabetical order of their
city & name.
SELECT *
FROM Student
ORDER BY city,Name;
Example 4: display regno, name, total from student table & list the students who have secured
marks >=400 in alphabetical order of their names.
SELECT Regno,Name,total
FROM Student
WHERE total >= 400
ORDER BY Name;
SJPUC Page 10
CHAPTER 14 SQL
SQL Functions:
There are many in built functions included in the SQL & can be classified as aggregate
functions & scalar functions.
1. Aggregate Functions:
• Functions that act on a set of values are called aggregate functions or column functions.
• It takes an entire column of data as its arguments & produces a single data item that
summarises the column.
a) Count() function:
• This function is used to count the number of values in the column.
• COUNT(*) is used to count the number of rows in a table including null values & duplicate
values.
Example 2: find the no. of students studying in college c3 in the exam table.
SELECT COUNT(*) FROM exam WHERE cc='C3';
Example 3: find the no. of colleges after eliminating the duplicate values
SELECT COUNT (DISTINCT cc) FROM exam;
Example 4: find the no. of students studying in college c2 where the total marks is >300 in the
exam table.
SELECT COUNT(*)
FROM exam
WHERE cc='C2' AND total>300;
Example 5: count the no. of cities from where the students have come
SELECT COUNT(DISTINCT city) FROM exam;
b) AVG() function:
• This function is used to find the average values in the column.
SJPUC Page 11
CHAPTER 14 SQL
Example 4: find the name of all the students whose cs marks is greater than the average
marks of cs
SELECT name
FROM exam
WHERE cs>(SELECT AVG(cs) FROM exam);
c) SUM() function:
• This function is used to find the sum of values in the column.
Example 2: find the total cs marks of all the students studying in c1 college
SELECT SUM(cs) FROM exam WHERE cc='C1';
d) MAX() function:
• This function is used to find the maximum value in the column.
e) MIN() function:
• This function is used to find the minimum value in the column.
Example 1: find the name of all the students who has secured lowest total
SELECT name
FROM exam
WHERE total=(SELECT MIN(total) FROM exam);
Example 2: find the name & reg no of all the students who has secured highest total
SELECT name, regno
FROM exam
WHERE total=(SELECT MAX(total) FROM exam);
2. Scalar Functions:
• Functions that acts only on one value at a time are called scalar functions.
• We further classify scalar principle using the type of data with which they are designed to
work.
• The available scalar functions are:
a) Numeric functions.
b) Character or text functions.
c) Date functions.
d) Conversion functions.
SJPUC Page 12
CHAPTER 14 SQL
a) Numeric functions:
• These are the functions that accept numeric input & return numeric values.
i.SQRT(x): It returns the square root value of x.
Example: SQRT(4) = 2
ii.CEIL(x): It returns the integer value that is greater than or equal to number x.
Example: CEIL(2.83) = 3
iii.FLOOR(x): It returns the integer value that is less than or equal to number x.
Example: FLOOR(2.83) = 2
iv.TRUNC(x,y): It truncates the value of x up to y decimal places.
Example: TRUNC(125.456,1) = 125.4
TRUNC(125.456,2) = 125.45
b) Character functions:
• It is also called text functions.
• These functions are used to manipulate strings.
• These are functions that accept character input and can return both character and number
values as output.
1. LOWER(string_value):
All the letters in 'string_value' is converted to lowercase.
Example: LOWER(‘GOOD’)=good
2. UPPER(string_value):
All the letters in 'string_value' is converted to uppercase.
Example: UPPER(‘good’)= GOOD
3. INITCAP (string_value)
All the letters in 'string_value' is converted to mixed case. i.e. the starting character of
each string will be in capital letter.
Example:
INITCAP(‘good morning’) = Good Morning
4. LTRIM (string_value, trim_text)
All occurrences of 'trim_text' is removed from the left of 'string_value'.
Example:
LTRIM(‘good morning’, ‘good’) = morning
5. RTRIM (string_value, trim_text)
All occurrences of 'trim_text' is removed from the right of 'string_value'.
Example:
RTRIM(‘good morning’, ‘morning’) = good
6. TRIM (trim_text FROM string_value)
All occurrences of 'trim_text' from the left and right of 'string_value‘ is removed.
'trim_text' can also be only one character long .
Example:
TRIM(‘o’ FROM ‘good morning’) = gd mrning
7. LENGTH (string_value)
Number of characters in 'string_value‘ is returned.
Example:
LENGTH(‘good morning’) = 12
SJPUC Page 13
CHAPTER 14 SQL
8. SUBSTR (string_value, m, n)
It returns 'n' number of characters from 'string_value' starting from the 'm‘ position.
Example:
SUBSTR(‘good morning’,6,7) = morning
SUBSTR(‘good morning’,6,4) = morn
c) Date functions:
• These functions take values that are of DATE datatype.
• They accept date as input & return values of datatype DATE.
i. ADD_MONTHS (date, n)
Returns a date value after adding ‘n’ months to the date ‘x’.
Example:
ADD_MONTHS ('14-Feb-18', 9) = 14-Nov-18
SJPUC Page 14
CHAPTER 14 SQL
v. SYSDATE
Returns the system’s current date and time.
d) Conversion functions:
• These are functions that help us to convert a value in one form to another form.
a) TO_CHAR (x [,y])
Converts Numeric and Date values to a character string value. It cannot be used for
calculations since it is a string value.
Example:
TO_CHAR (SYSDATE, 'Day, Month YYYY') = WEDNESDAY, MARCH 2014
b) NVL (x, y)
If 'x' is NULL, replace it with 'y'. 'x' and 'y‘ must be of the same data type.
Example:
NVL (null, 1) = 1
GROUP BY clause:
• It tells SQL to group the rows based on distinct values that exist for specified columns i.e.
it creates a data set containing several set of records grouped together based on condition
Syntax:
SELECT column_name
FROM table_name
[WHERE condition(s)]
GROUP BY row1, row2, … , rowN;
Example 2: find the no of students, sum, avg, max & min marks in cs from each city.
SELECT city,COUNT(cs), SUM(CS), AVG(CS), MAX(CS), MIN(CS)
FROM exam
GROUP BY city;
HAVING clause:
• It operates on group of rows. It is always used in association with GROUP BY clause.
• The difference between HAVING & WHERE clause is that WHERE clause cannot be used
with group of rows but HAVING clause can be used.
Syntax:
SELECT column_name
FROM table_name
GROUP BY row1, row2, … , rowN
HAVING column_list;
SJPUC Page 15
CHAPTER 14 SQL
Example : display all the city names which have more than 2 students.
SELECT city, COUNT(*)
FROM exam
GROUP BY city
HAVING COUNT(*) > 2;
TCL commands:
COMMIT & ROLLBACK are the two TCL commands.
i. COMMIT Command:
• It is a transactional command used to save changes invoked by a transaction to the database.
• It makes all the changes made by a statement issued permanent.
Syntax:
COMMIT;
DCL commands:
GRANT & REVOKE are the two DCL commands.
i. GRANT Command:
• It is used to provide access privileges on the data base objects to the users.
Syntax:
GRANT previlage_name
ON object_name
TO {User_name |PUBLIC| Role_name};
[WITH GRANT OPTION]
2. Object_name:
It is the name of the database object like table, stored procedure or sequence.
3. User_name:
It is the name of the user to whom an access right is being granted.
SJPUC Page 16
CHAPTER 14 SQL
4. Public:
It is used to grant access rights to all the users.
5. Roles:
It is the set of privileges grouped together
i.CONNECT:
Privileges granted to the role CONNECT are: CREATE TABLE, CREATE VIEW,
CREATE SEQUENCE, CREATE SESSION, etc.,
ii.RESOURCE:
Privileges granted to the role RESOURCE are: CREATE TABLE, CREATE
PROCEDURE, CREATE SEQUENCE, CREATE TRIGGER, etc.,
iii.DBA: All system privileges
1. Privileges:
privilege name is the access right provided to a user on a database object. Some of the access
rights are ALL,EXECUTE,SELECT.
There are two types of privileges:
i. System privileges: This allows the user to create, alter, or drop database objects.
ii. Object privileges: This allows the user to select, insert, update or delete data from
database objects.
2. Object_name:
It is the name of the database object like table, stored procedure or sequence.
3. User_name:
It is the name of the user to whom an access right is being denied.
4. Public:
It is used to remove access rights from all the users.
5. Roles:
It is the set of privileges grouped together
i.CONNECT:
Privileges granted to the role CONNECT are: CREATE TABLE, CREATE VIEW,
CREATE SEQUENCE, CREATE SESSION, etc.,
SJPUC Page 17
CHAPTER 14 SQL
ii.RESOURCE:
Privileges granted to the role RESOURCE are: CREATE TABLE, CREATE
PROCEDURE, CREATE SEQUENCE, CREATE TRIGGER, etc.,
iii.DBA: All system privileges
SQL constraints:
• Constraints are the rules enforced on the data column in a table.
• They are used to limit the type of data that can go into a table.
• This ensures the accuracy & reliability of the data in the database.
SQL allows 2 types of constraints:
i.Column-level constraints:
ii.Table-level constraints:
Column-level constraints:
• These constraints are defined along with the column definition while creating a table.
• These constraints can be applied only to individual column.
Table-level constraints:
• These constraints are defined after all the table column definition while creating a table.
• These constraints can be applied on one or more columns or on the entire table.
UNIQUE constraint:
• This constraint ensures that no two rows have the same value in the specified column.
UNIQUE constraint example:
CREATE TABLE product
(
Pid CHAR(4) NOT NULL UNIQUE ,
Description VARCHAR(20) NOT NULL,
Company_name VARCHAR(20),
SJPUC Page 18
CHAPTER 14 SQL
DOM DATE,
Price NUMBER(10,2)
);
DEFAULT constraint:
• A default value can be specified using default constraint.
• It provides a default value to a column when the INSERT INTO command doesn’t
provide a specific value.
SJPUC Page 19
CHAPTER 14 SQL
CHECK constraint:
• It is used to establish a true or false condition that is applied to a data base in a column.
• If a value doesn’t meet the condition, it cannot be placed in the table.
Table-level constraint:
• When a constraint is applied to a group of columns, it is called table-level constraints.
• They can be defined at the end of the table.
Example:
CREATE TABLE bangalore_students
AS SELECT regno,name,city,
FROM STUDENT
WHERE (city=‘bangalore’);
*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
SJPUC Page 20