0% found this document useful (0 votes)
4 views20 pages

14SQL

The document provides a comprehensive overview of SQL (Structured Query Language), detailing its definition, features, architecture, and various commands categorized into DDL, DML, DCL, DQL, and TCL. It explains the syntax and usage of commands such as CREATE, ALTER, INSERT, UPDATE, DELETE, and SELECT, along with data types supported by SQL. Additionally, it covers the use of logical operators, conditions, and sorting data with the ORDER BY clause.

Uploaded by

jamuna7771987
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)
4 views20 pages

14SQL

The document provides a comprehensive overview of SQL (Structured Query Language), detailing its definition, features, architecture, and various commands categorized into DDL, DML, DCL, DQL, and TCL. It explains the syntax and usage of commands such as CREATE, ALTER, INSERT, UPDATE, DELETE, and SELECT, along with data types supported by SQL. Additionally, it covers the use of logical operators, conditions, and sorting data with the ORDER BY clause.

Uploaded by

jamuna7771987
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/ 20

CHAPTER 14 SQL

• SQL- Structured Query Language


• SQL is a language of DBMS.
• It includes database creation, deletion, storing, manipulation & retrieving data stored in
relational Database.
• SQL is a standard language for Database.
• IBM developed codd’s ideas & developed SQL in 1986 & it was standardized by ANSI.

Definition:
SQL is a query language for managing data in relational data base.

Features or characteristics of SQL:


1. It’s very easy to learn & use.
2. Large volume of data base can be handled quite easily.
3. It’s non procedural language. It means it’s enough to give a command to perform any
activity.
4. We can add user permissions on data base or tables.
5. It’s used to create new data base, new tables in the data base.
6. We can execute queries against data base and can retrieve data from the data base.
7. We can insert, delete or update records in a data base.

SQL architecture:

The SQL architecture has following components:


1. SQL query: It is component to accept database language for storing, retrieving &
modifying data.
2. Query language processor: It is a component of DBMS to manage the storage of data in a
table of rows & columns. While storing data, 2 operations are performed namely parsing
& optimization.
3. DBMS engine: A DBMS component that accepts user logical request(queries) to convert
them into physical representation in the database.
It performs additional operations like:
i. File management: A component to provide GUI to the user to organize physical data.
ii. Transaction management: A component of DBMS used for maintaining ACID
properties on DBMS.
4. Physical database: A component that implements database on secondary storage based on
logical data models(network, relational, etc.,)

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.

The commands in SQL are grouped into following:

SQL

1. DDL 2. DML 3. DCL 4. DQL 5. TCL

1a. CREATE 2a. INSERT 3a. GRANT 4a. SELECT 5a. COMMIT

5b. ROLL
1b. ALTER 2b. UPDATE 3b. REVOKE
BACK

1c. DROP 2c. DELETE

1. DDL (Data definition language):


• A language which creates & maintains physical data structure is called DDL.
• It permits data base tables to be created or deleted.
i)CREATE: It creates a new table in the data base.
ii)ALTER: It modifies an existing table.
iii)DROP: Deletes an entire table from the data base.

2. DML(Data Manipulation Language)


• These SQL commands are used for storing, updating & dropping the structure of data
base.
i)INSERT: It adds new rows of data to a table.
ii)UPDATE: Modify the existing rows in a table.
iii)DELETE: Deletes the entire row from the existing table.

3. DQL( Data Query Language)


• The SELECT command comes under DQL which is used for retrieving the data.
i) SELECT: Retrieving data from a table in the data base.

4. DCL( Data Control Language)


• These commands are used for providing securities to data base.
i) GRANT: Gives privilege to users.
ii) REVOKE: Takes back privileges granted from users.

SJPUC Page 2
CHAPTER 14 SQL

5. TCL (Transaction Control Language)


• It includes commands to control the transactions in a database system.
i) COMMIT: Makes all the changes made by statements issued permanent.
ii) ROLLBACK: Undoes all the changes since the beginning of a transaction.

Data types supported by SQL:


• We assign each field(column) a data type that indicates the kind of value the field will
contain.
• All the values in a given field must be of same data type.

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)

2. CHAR : Its used to store character type data in a column


syntax: CHAR(size)
where: size is the maximum no of characters in a column.
CHAR can hold at most 255 characters.
Ex: name CHAR(25)
course CHAR(4)
Values of CHAR type must be enclosed in single quotes.

3. VARCHAR/ VARCHAR 2: This data type is used to store alphanumeric data.


syntax: VARCHAR(size)/ VARCHAR2(size)
Ex: address VARCHAR2(50)
name VARCHAR(10)
The difference between VARCHAR & VARCHAR2 data type is the way these two columns
treat the values that are smaller in length to the maximum length established for the column.
• If the field is declared as VARCHAR, it will add blank characters to fill up the fixed
length column.
• If the field is declared as VARCHAR2, no blank characters will be added.

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

Functions of Data Definition Language:


i.DDL defines the physical characteristics of each record. That means it specifies field
name, data type, length and also relationships among those records.
ii.DDL describes the schema and sub-schema.
iii.DDL indicates keys of the record.
iv.DDL specifies associative related records or fields DDL provides data security measures.
v.DDL provides logical and physical data independence.

1a. CREATE TABLE COMMAND:


• It is used to create a new table.
• Creating a new table involves naming a table & defining its columns & column’s data
type.
Syntax:
CREATE TABLE TABLE_NAME
(
column_name1 data type,
column_name2 data type,
-----------------
column_name-n data type
);
• In the above syntax, CREATE TABLE is the keyword, followed by table name.
• All the column names along with data types must be enclosed within small parenthesis.
• Column definitions are separated by commas
• Each table must have at least 1 column.
• All the SQL commands must end with semi colon (;)

Example:
CREATE TABLE STUDENT
(
Regno number(6),
Name char(25),
Combination char(5),
DOB date,
Fees number(5),
Total number(3),
City char(20)
);

Viewing table info:


• DESCRIBE/DESC: It displays name of the columns, their data types & size along with
constraints.
Ex: describe student;

SJPUC Page 4
CHAPTER 14 SQL

1b. ALTER TABLE COMMAND:


An existing table can be modified or changed by using the ALTER TABLE command.
The following tasks can be performed using ALTER TABLE command.
i.Changing the column name.
ii.Adding a new column.
iii.Changing the data type of the column.
iv.Deleting a particular column.

i. Syntax for adding a new column to an existing table :


ALTER TABLE table_name
ADD column1 data type, column2 data type,------ ;
Example:
ALTER TABLE student
ADD address VARCHAR2(50);

ii. Syntax to modify / change the data type of a particular column:


ALTER TABLE table_name
MODIFY column1 data type, column2 data type,------;
Example:
ALTER TABLE student
MODIFY address VARCHAR2(100);

iii. Syntax for deleting a particular column:


ALTER TABLE table_name
DROP column1 data type, column2 data type,------;
Example:
ALTER TABLE student
DROP address VARCHAR2(50);

1c. DROP TABLE COMMAND:


• An existing table can be deleted from the database by using DROP TABLE command.
• This table will delete the entire table student along with its contents from data base.
Syntax:DROP TABLE table_name;
Example:DROP TABLE student;

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’);

2b. UPDATE COMMAND:


• UPDATE command is used to modify or update an already existing records in a table.
• All the rows in a table which satisfies the condition will be updated with the new values.

Syntax:
UPDATE table_name
SET column1=value1
[, column2= value2, .…. , columnN=valueN]
[WHERE condition];

Example 1: To change the fees of the student:


UPDATE Student
SET Fees=15000;

Example 2: To reduce the fees of all the students by 500:


UPDATE Student
SET Fees = Fees-500;

Example 3:
change the fees to 18000/- only for those students whose combination is ‘PCMCs’:
UPDATE Student
SET Fees = 18000
WHERE Combination = ‘PCMCs’;

Example 4: change the DOB of the student whose Regno is 003:


UPDATE Student
SET DOB = '23-feb-2003'
WHERE Regno = 003;

2c. DELETE COMMAND:


• DELETE command is used to delete the existing records from table.

Syntax:
DELETE FROM table_name
[WHERE condition];

Example 1:
DELETE FROM Student;

Example 2: Delete the record whose Regno is 006


DELETE FROM Student WHERE Regno = 006;

SJPUC Page 6
CHAPTER 14 SQL

Example 3: Delete the record whose combination is ‘PCME’


DELETE FROM Student
WHERE combination = ‘PCME’;

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)];

i. Selecting all the rows & columns from a table :


Syntax:
SELECT * FROM table_name;

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.

ii. Selecting a set of columns in a table:

Select Regno & Name from the Student table:

Syntax:
SELECT column_name
FROM table_name;

Example:
SELECT Regno,Name
FROM Student;

iii. Removing duplicate data with DISTINCT keyword:


• Some of the columns in a table may contain duplicate values.
• If we want to display only the distinct values then we make use of DISTINCT command.
Syntax:
SELECT DISTINCT column_name
FROM table_name;
Example:
SELECT DISTINCT Combination
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.

iv. Extracting specific rows using WHERE clause:


SQL compares each record from the table specified in the WHERE clause.
• WHERE clause is used to extract only those records that fulfils a specified condition &
displays only the columns specified in the SELECT clause.
• We can make use of logical operators such as < , > , >= , <=,<>(not equal to)
Syntax:
SELECT column_name
FROM table_name
WHERE condition(s);

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;

1. WHERE clause using logical operators:


• WHERE clause uses one or more logical conditions.
• The logical operators used in SQL are AND, OR, NOT, IN, BETWEEN, IS NULL, ALL,
ANY, EXIST, LIKE, etc.,
• We can use all the comparison operators in the logical condition expression.
• The result of the condition may be true or false.

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';

2. WHERE clause using IN operators:


• IN operator is used to compare a value with the list of values.
• IN operator checks the condition specified by the list of values.
• It selects a record which matches with any value given in the list.

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');

3. WHERE clause using BETWEEN operators:


• It specifies a range of values that the column value must lie for the condition to become true.
• The range includes both upper values & lower values.

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;

4. WHERE clause using NULL operators:


• For retrieving the rows where some of the columns have been defined as NULL values.
• There is a special comparison operator called IS NULL.
• By using IS NULL in the WHERE clause one can find NULL value in the column.

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 1: find the no. of students in the exam table.


SELECT COUNT(*) FROM exam;

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.

Example 1: find the average marks of cs students in the exam table.


SELECT AVG(cs) FROM exam;

Example 2: find the average marks of student studying in c2 college


SELECT AVG(total) FROM exam WHERE cc='C2';

Example 3: find the average marks of students in the exam table.


SELECT AVG(phy+che+mat+cs)
FROM exam;
(OR)
SELECT AVG(total)
FROM exam;

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 1: find the total marks of all the students in physics.


SELECT SUM(phy) FROM exam;

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.

Example 1: display max marks of cs


SELECT MAX(cs) FROM exam;

Example 2: display max marks of phy,che,maths,cs & total


SELECT MAX(phy), MAX(che) , MAX(mat) , MAX(cs) , MAX(total) FROM exam;

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

9. LPAD (string_value, n, pad_value)


It returns 'string_value' left-padded with 'pad_value' . The length of the whole string will
be of 'n' characters.
Example:
LPAD(‘good’, 6 , ‘*’) = **good
LPAD(‘good’, 8 , ‘#’) = ####good

10. RPAD (string_value, n, pad_value)


It returns 'string_value' right-padded with 'pad_value‘. The length of the whole string will
be of 'n' characters.
Example:
RPAD(‘good’, 6 , ‘*’) = good**
RPAD(‘good’, 8 , ‘#’) = good####

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

ii. MONTHS_BETWEEN (x1, x2)


Returns the number of months between dates x1 and x2.
Example:
MONTHS_BETWEEN ('16-Sep-14', '16Dec-14') = 3

iii. NEXT_DAY (x, week_day)


Returns the next date of the ‘week_day’
Example:
NEXT_DAY ('20-Mar-14', 'Thursday') =
21-Mar-14

iv. LAST_DAY (x)


It is used to determine the number of days in a month from the date 'x' specified.
Example:
LAST_DAY ('01-Jun-14') = 30-Jun-14

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 1: find the no of students studying in each college


SELECT cc, COUNT(cc)
FROM exam
GROUP BY cc;

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;

ii. ROLLBACK Command:


• It undoes all the changes since the beginning of a transaction or since a save point.
Syntax:
ROLLBACK;

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]

Example: GRANT select


ON employee
TO user1 ;
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: System privileges & object 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 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

6. With GRANT option:


It allows the users to grant access rights to the other users.

Example: GRANT select, update


ON depositors
TO user1,user2;
ii. REVOKE Command:
• It removes user access privileges/rights from the database.
Syntax:
REVOKE previlage_name
ON object_name
FROM {User_name |PUBLIC| Role_name};
Example: REVOKE select, update
ON depositors
FROM user1,user2;

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.

Syntax for constraint:


CREATE TABLE table_name
(
Col1 datatype [col constraint],
Column-level constraints
Col2 datatype [col constraint],
------------------------------------
[table constraint][col1, col2,...] Table-level constraints
);
Some of the commonly used constraints are:
NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, DEFAULT, CHECK.

NOT NULL constraint:


• By default, a column can hold null values.
• When a column is defined as NOT NULL, then the column becomes a mandatory column.
• It implies that the value must be entered into the column if the row is to be inserted for the
storage in the 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)
);

PRIMARY KEY constraint:


• A primary key is a field which uniquely identifies each row in a database table.
• A primary key column in a table has special attributes.
i. This column should not contain any null value i.e. the column cannot be left blank.
ii. The data in this column must be unique.

PRIMARY KEY constraint example:


CREATE TABLE product
(
Pid CHAR(4) PRIMARY KEY ,
Description VARCHAR(20) NOT NULL,
Company_name VARCHAR(20),
DOM DATE,
Price NUMBER(10,2)
);

FOREIGN KEY constraint:


• It is used to link two tables together.
• It is a column whose values matches with a primary key in a different table.
• The table in which foreign key is defined is called foreign table.
• The table that defines primary key & is referenced by foreign key is called primary table
or master table.

FOREIGN KEY constraint example:


CREATE TABLE product
(
Pid CHAR(4) PRIMARY KEY , Master table
Description VARCHAR(20) NOT NULL, Or
Company_name VARCHAR(20) REFERENCES Company(id),
DOM DATE,
Price NUMBER(10,2)
);
CREATE TABLE company
(
id CHAR(7) PRIMARY KEY , Foreign Table
Cprofile VARCHAR(200),
);

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

DEFAULT constraint example:


CREATE TABLE product
(
Pid CHAR(4) PRIMARY KEY ,
Description VARCHAR(20) NOT NULL,
Company_name VARCHAR(20),
DOM DATE,
Price NUMBER(10,2) DEFAULT 1000.00
);

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.

CHECK constraint example:


CREATE TABLE product
(
Pid CHAR(4) CHECK(Pid LIKE ‘%P’),
Description VARCHAR(20) NOT NULL,
Company_name VARCHAR(20),
DOM DATE,
Price NUMBER(10,2) CHECK(Price>100)
);

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.

Creating a table from an existing table.


One can create a new table from an existing table.
Syntax:
CREATE TABLE new_table_name
AS SELECT new_col1, new_col2…,
FROM old_table_name
WHERE condition;

Example:
CREATE TABLE bangalore_students
AS SELECT regno,name,city,
FROM STUDENT
WHERE (city=‘bangalore’);

*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*

SJPUC Page 20

You might also like