0% found this document useful (0 votes)
271 views33 pages

Structured Query Language

NOTES

Uploaded by

Nikhil Kumar Saw
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
271 views33 pages

Structured Query Language

NOTES

Uploaded by

Nikhil Kumar Saw
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 33

Structured Query Language

SQL DATABASE DATA Example;


Database: It is a place where we store Data in an organized way. Marker – Object / Entity
Color – Property / Attribute /
Data: A raw fact describing an object’s property/attribute/field. Field
We can perform four basics operations in the Database, Black – Raw Fact / Data

1. CREATE / INSERT C i.e., These operations are


2. READ / RETRIEVE R universally known as CRUD
3. UPDATE / MODIFY U operations.
4. DELETE / DROP D
DBMS: [Database Management System]

 It is the software used to manage or maintain the Database.


 It stores the Data in the form of files.
 It uses Query Language [QL] to communicate with the Database.
 Its main features are Security and Authorization.
File Name - BIODATA
Name – Pallavi Singh Raw Facts/
Properties/ Data
Attribute/ Age – 29
Fields Gender – Female
Email – pallavisingh143@gmail.com
Phone No. - +91-8179956848
Address – Ravicherela, Krishna District, Goa

Dis-Advantages
 It occupies more memory space as it stores the Data in the form of files.
 Hence, the time taken for execution is more.
RDBMS: [Relational Database Management System]

 This DBMS software stores the Data in the form of Tables.


 It uses Structured Query Language [SQL] to communicate with the Database.
 It provides Authorization and more Security than DBMS.
Advantages
 It occupies less memory space as it stores the Data in the form of Tables.
 Hence, the execution time complexity is less.
Table Name - BIODATA

Name Age Gender Address


Pallavi Singh 29 Female Goa
Nikita Rao 26 Female JSpiders
Rahul Tiwari 22 Male QSpiders
Aradhya Saw 24 Female PYSpiders
Note:
 In SQL, Identifiers are nothing but Table and Column names.
 Identifier’s names shouldn’t start with Numbers and also shouldn’t contain any
special characters (Except Underscore “_”).
 Identifier’s name should be a single word.
 Identifier’s name length shouldn’t exceed 32 characters.
Tuple: It is a collection of Homogeneous or Heterogeneous Data Types which doesn’t allow
any internal modifications.
Record: It is a collection of values about a particular object.

Relational Model
 It states that Data should be stored in the form of Tables.
 This theory was proposed by Edger Frank CODD.
 If the DBMS follows the Relational Model, we call it Relational Database
Management System [RDBMS].
i.e.; DBMS Relational Model RDBMS

To store the Data in the form of Tables we have to follow certain rules,
Rule 1: In a single cell we must store only single-valued Data.
Note: If we try to store multiple values in a single cell then there is a possibility of Data loss.
Rule 2: We can store Data in multiple Tables and we can establish a connection between
the Tables with the help of Key Attributes.
EMPLOYEE TABLE
EMP - NO ENAME DEP - NO DNAME LOC
101 A 10 X XYZ
102 B 20 Y MNO
103 C 10 X XYZ
104 D 10 X MNO

Key Attribute: DEP – NO


EMP TABLE DEPT TABLE
EMP - NO ENAME DEP - NO DEP - NO DNAME LOC
101 A 10 10 X XYZ
102 B 20 20 Y MNO
103 C 10 10 X XYZ
104 D 10 10 X XYZ

Rule 3: Data should be stored in the form of Tables including the MetaData in MetaTable.
#MetaData – The Data about the Data is known as MetaData.
#MetaTable – The Table that stores the MetaData is known as MetaTable and automatically
generates it.
EMP TABLE
METADATA
EMPNO ENAME PHOTO
SIZE – 100KB
101 A DATA PHOTO RESOLUTION – 4 X 25
102 B FORMAT - JPEG

METATABLE
SIZE RESOLUTION FORMAT
100 4 X 25 JPEG
120 4 X 50 PNG

Rule 4: The Data entered must be validated by assigning, 1. Data Types


2. Constraints

Note: Assigning Data Types is mandatory but Constraints are optional and these are
assigned to the Columns.

Data Types

 It tells which Type of Data must be stored in a particular Column.


 There are five Data Types in Oracle SQL,
1. CHAR
2. VARCHAR / VARCHAR2
3. NUMBER
4. DATE
5. LARGE OBJECT
i) CHARACTER LARGE OBJECT
ii) BINARY LARGE OBJECT
CHAR: It is used to store the characters like Alphabets, Numbers, Special Characters, and
Alpha-Numeric within the single quotes (‘’). CHAR Data Types follow Fixed Length Memory
Allocation.
Syntax: CHAR (SIZE) i.e.; reads as char of size

 Here size represents the maximum no. of characters that we have to store.
 The size value ranges from 1 to 2000.

e.g.; NAME CHAR (8) R I T A

Used Memory Unused / Wasted Memory

VARCHAR: It is the same as char; the only difference is that it uses Variable Length Memory
Allocation instead of Fixed Length Memory Allocation. Its size also ranges from 1 to 2000.
Syntax: VARCHAR (SIZE)
Note: The input Data length should always be less than or equal to the size allotted.
i.e.; NAME CHAR (8) Input is PYSPIDERS whose length is 9
9 <= 8 = false # Not accepted / Error
VARCHAR2: It is an updated version of VARCHAR with a storage capacity of 1 to 4000.
It is used automatically when the size exceeds the 2000 limit.
NUMBER: It can store only the Numbers.
Syntax: NUMBER (PRECISION, [SCALE])
Required Not Mandatory
Precision: It represents the maximum no. of digits to be allocated.
Scale: It represents the no. of decimal values within the Precision.
Note: The default Scale value is zero ‘0’.
e.g.;
1. NUMBER (5) - ± _ _ _ _ _ [Normal Syntax].
2. NUMBER (5, 0) - Same Meaning as 1.
3. NUMBER (5, 2) -±___.__
4. NUMBER (5, 7) - ± . 00 _ _ _ _ _
5. NUMBER (5, 5) -±._____
DATE: It can store only the Date.
Syntax: DATE
Oracle DATE Formats
 ‘DD – MON – YYYY’ ‘11 – APR – 2023’
 ‘DD – MON – YY’ ‘11 – APR – 23’
LARGE OBJECTS: It is used to store Data up to 4 GB.
 LARGE OBJECTS are of two types,
1st) CHARACTER LARGE OBJECTS: It is used to store characters with up to 4 GB
of memory.
Syntax: CLOB
2nd) BINARY LARGE OBJECTS: It is used to store Binary values of Images, Audio,
Videos, Pdfs, etc. up to 4 GB.
Syntax: BLOB

Constraints (CONDITIONS)
 These are the conditions given to the columns for validation.
 Constraints are of five types,
1. UNIQUE
2. NOT NULL
3. CHECK
4. PRIMARY KEY
5. FOREIGN KEY
UNIQUE: It doesn’t accept duplicated or repeated values.
Syntax: UNIQUE
NOT NULL: It doesn’t accept null. It is used where entering Data is mandatory.
Syntax: NOT NULL
Note:
 NULL is a keyword that represents an empty cell.
 NULL doesn’t represent zero ‘0’ or space ‘ ’.
 We can’t perform any arithmetic operations on NULL, because the output will always
be NULL itself.
e.g.; NULL * 2 = NULL

NULL +5= NULL

 We can’t identify an empty cell by equating it with the NULL Keyword, because the
output will always be false. So, to identify NULL cells we use Identity Operator.

e.g.; NULL = = False


CHECK: It is an additional condition given for validation.
Syntax: CHECK (CONDITION)
e.g.;
Age Number (2) CHECK (20<Age<40) Ph_No NUMBER (10) CHECK (Length
(Ph_No) = 10)
25 True True 9123123123 True True
19 True False 9123456 True False

PRIMARY KEY: It is used to Identify a record uniquely from the tables.


Syntax: PRIMARY KEY
Characteristics of PRIMARY KEY
 It doesn’t accept duplicate values.
 It doesn’t accept the NULL values.
 So, it has the properties of both UNIQUE and NOT NULL.
 We can have only one PRIMARY KEY in a table.
 We can have UNIQUE and NOT NULL Constraints together for any no. of
times in a table because PRIMARY KEY is not equal to UNIQUE and NOT
NULL
 If we use UNIQUE, NOT NULL, and PRIMARY KEY all together for a single
column then an error will arise.
 We can use UNIQUE, NOT NULL, and PRIMARY KEY as,
UNIQUE + PRIMARY KEY
NOT NULL + PRIMARY KEY
UNIQUE + NOT NULL
FOREIGN KEY: It is used to establish a Connection / Reference between the tables.
Syntax: FOREIGN KEY
Characteristics of FOREIGN KEY
 It accepts duplicate values.
 It also accepts the NULL values.
 It doesn’t have the properties of UNIQUE and NOT NULL.
 We can have more than one FOREIGN KEY in a table.
 FOREIGN KEY is also known as Referential Integrity Constraints (RIC).
 For a column to be a FOREIGN KEY it must be a PRIMARY KEY in its table.
 The columns which have the Key Constraints are also known as KEY
ATTRIBUTE
e.g.; BNAME as FOREIGN KEY is KEY ATTRIBUTE here.
BRANCH
STUDENT SID SNAME DOJ PERCENT BNAME
BNAME HOD BLOCK VARCHAR VARCHAR DATE NUMBER VARCHAR
VARCHAR VARCHAR CHAR (1) (5) [PK] (15) [NN] (4, 2) [NN] (10) [FK]
(10) [PK] (15) [NN] [U, NN] A1234 RITA 14-FEB-2023 75.50 EEE
EEE ABC A
B1235 VIJAY 15-FEB-2023 83.75 CIVIL
CIVIL MNO B

Overview of SQL Statements or Languages


 Data Definition Language [DDL]
 Data Manipulation Language [DML]
 Transaction Control Language [TCL]
 Data Control Language [DCL]
 Data Query Language [DQL]

Data Definition Language [DDL]

 It deals with the structure of the Table or Object present in the Database.
 It has five Statements,
1. CREATE
2. RENAME
3. TRUNCATE
4. ALTER
5. DROP

CREATE: It is used to create the Table or Object in the Database.

Syntax: CREATE TABLE TABLE_NAME


(
COLUMN_NAME1 DATATYPE [CONSTRAINTS],
COLUMN_NAME2 DATATYPE [CONSTRAINTS],
------------------------------------
------------------------------------
COLUMN_NAMEn DATATYPE [CONSTRAINTS]
);

e.g.; CREATE TABLE BRANCH


(
BNAME VARCHAR (10) PRIMARY KEY,
HOD VARCHAR (15) NOT NULL,
BLOCK CHAR (1)
);
Syntax: While Creating a FOREIGN KEY

CREATE TABLE TABLE_NAME


(
COLUMN_NAME1 DATATYPE [CONSTRAINTS],
COLUMN_NAME2 DATATYPE [CONSTRAINTS],
------------------------------------
COLUMN_NAMEn DATATYPE [CONSTRAINTS],
CONSTRAINT CONSTRAINT_ID FOREIGN KEY (COL_NAME)
REFERENCES PARENT_TABLE_NAME (COL_NAME)
);

e.g.; CREATE TABLE STUDENT


(
SID VARCHAR (5) PRIMARY KEY,
SNAME VARCHAR (15) NOT NULL,
DOJ DATE,
PER NUMBER (4, 2) NOT NULL,
STREAM VARCHAR (10),
CONSTRAINT SD_FK FOREIGN KEY (STREAM) REFERENCES BRANCH
(BNAME)
);

RENAME: It is used to modify the Table Name.


Syntax: RENAME TABLE_NAME TO NEW_TABLE_NAME;
e.g.; RENAME STUDENT TO S1;
TRUNCATE: It is used to delete the Data from the Table Permanently.
Working of TRUNCATE
 It copies the structure of the Table and deletes the entire table.
 We can’t perform TRUNCATE on the Parent Table.
e.g.; TRUNCATE TABLE STUDENT;
Output: TABLE TRUNCATED
Note:
 SELECT * FROM TAB; [Displays all the Table present]
 SELECT * FROM TABLE_NAME; [Displays Data present in the Table]
 DESC TABLE_NAME [Displays the Structure of the table (#No Semicolon)]
 CL SCR [Clear the Screen]
 SET LINES SIZE PAGES SIZE [Modify the Dimensions of the Page]
 ED [Used to Invoke the Editor]
Steps to use an Editor
Step 1: As soon as we Invoke the Editor, the Controller will copy the last Query and paste it
in the Notepad.
Step 2: Do all the respective changes of the Query within the Notepad and Save it.
Step 3: Close the Notepad after Saving the file, the Modified Query will be present in the
SQL Application.
Step 4: To execute the Modifies Query we use ‘/’. [Semicolon must not be used inside Editor
(Notepad) or even at Query in SQL Application]

Important Point:
SELECT COLUMN_NAME, A.CONSTRAINT_NAME, CONSTRAINT_TYPE, SEARCH_CONDITION

FROM USER_CONSTRAINTS A, USER_CONS_COLUMNS B

WHERE A.CONSTRAINT_NAME = B.CONSTRAINT_NAME AND A.TABLE_NAME = 'TABLE_NAME';

ALTER: It is used to Modify / Alter the Structure of the Table in five ways,

1st) To ADD a Column


Syntax: ALTER TABLE TABLE_NAME
ADD COLUMN_NAME DATATYPE [CONSTRAINT];
e.g.; ALTER TABLE S1
ADD PH_NO NUMBER (10) UNIQUE NOT NULL CHECK (LENGTH
= 10);
e.g.; To ADD Multiple Columns at a Time.
ALTER TABLE S1
ADD (EMAIL VARCHAR (20), DOB DATE NOT NULL);

2nd) To DROP a Column

Syntax: ALTER TABLE TABLE_NAME


DROP COLUMN COLUMN_NAME;

3rd) To RENAME a Column

Syntax: ALTER TABLE TABLE_NAME


RENAME COLUMN COLUMN_NAME TO NEW_COLUMN_NAME;

4th) To MODIFY the Datatype

Syntax: ALTER TABLE TABLE_NAME


MODIFY COLUMN_NAME NEW_DATATYPE;
Note:

 We can’t modify the column’s Data Type, which has CHECK Constraints.
e.g.; Query: ALERT TABLE STUDENT
MODIFY PH_NO VARCHAR (10);
Error: Cannot Modify Column Data Type with current Constraint.

 We can’t modify the column’s Data Type, which is FOREIGN KEY Constraints.
e.g.; Query: ALERT TABLE STUDENT
MODIFY STREAM CHAR (10);
Error: Column Type incompatible with Reference Column type.
 We can’t modify the Data Type of the column if the Column is PRIMARY KEY and is
referenced to another table.
e.g.; Query: ALERT TABLE BRANCH
MODIFY BNAME CHAR (10);
Error: Column Type incompatible with Reference Column type.

 We can modify the column’s Data Type in the rest of the cases.

Modification of the Structure of the Table is not easy when the Table has data
within it.

5th) To MODIFY the Constraint


 We can only MODIFY the Constraint NULL to NOT NULL or Vice –
Versa.
 Either we can ADD or DROP the UNIQUE, CHECK, PRIMARY KEY
, and FOREIGN KEY.
Syntax: ALTER TABLE TABLE_NAME
MODIFY COLUMN_NAME EXISTING_DATATYPE NULL/NOT NULL;

e.g.; ALTER TABLE TABLE_NAME


MODIFY BNAME VARCHAR (8) NOT NULL;

e.g.; ALTER TABLE TABLE_NAME


MODIFY BLOCK CHAR (1) NULL;

6th) To ADD the Constraint

Syntax: ALTER TABLE TABLE_NAME


ADD CONSTRAINT CONSTRAINT_ID CONSTRAINT_NAME
(COL_NAME 1, COL_NAME 2, COL_NAME 3, ……………., COL_NAME n);

e.g.; ALTER TABLE BRANCH


ADD CONSTRAINT B_UNI UNIQUE (BLOCK, HOD);

e.g.; ALTER TABLE BRANCH


ADD CONSTRAINT BLK_CH CHECK (BLOCK = UPPER(BLOCK));

Syntax: For PRIMARY KEY


ALTER TABLE TABLE_NAME
ADD CONSTRAINT CONSTRAINT_ID PRIMARY KEY (COL_NAME);

e.g.; ALTER TABLE BRANCH


ADD CONSTRAINT B1_PK PRIMARY KEY (BNAME);

Syntax: For FOREIGN KEY


ALTER TABLE TABLE_NAME
ADD CONSTRAINT CONSTRAINT_ID FOREIGN KEY (COL_NAME)
REFERENCES PARENT_TABLE_NAME (COL_NAME);

e.g.; ALTER TABLE STUDENT


ADD CONSTRAINT S1_FK FOREIGN KEY (BNAME) REFERENCES
BRANCH (BNAME);
7th) To DROP the Constraint
Syntax: ALTER TABLE TABLE_NAME
DROP CONSTRAINT CONSTRAINT_ID;

e.g.; ALTER TABLE STUDENT


DROP CONSTRAINT S1_FK;

e.g.; ALTER TABLE STUDENT


DROP CONSTRAINT BLK_CH;

DROP: It is used to delete the Table from the Database.


Syntax: DROP TABLE TABLE_NAME;

FLASHBACK: It is used to recover the Table from the Recycle Bin back to the Database
where it was present previously.
Syntax: FLASHBACK TABLE TABLE_NAME
TO BEFORE DROP;

PURGE: It is used to Delete the Table from the Recycle Bin completely.
Syntax: PURGE TABLE TABLE_NAME;

Note: We use the following command to display the table in the Recycle Bin.

Syntax: SHOW RECYCLEBIN;

T1 T1

DROP PURGE

BIN$ABC BIN$ABC

DATABASE RECYCLE BIN TRASH

FLASHBACK

Data Manipulation Language [DML]

 It is used to manipulate the table by Inserting, Updating, or Deleting the records from
the table.
 It has three Statements,
 INSERT
 UPDATE
 DELETE

INSERT: It is used to Insert the Records into the table.

Syntax: For Single Record

INSERT INTO TABLE_NAME (COL1, COL2, ……..., COLn) VALUES (VAL1,


VAL2, ……..., VALn);
e.g.; INSERT INTO BRANCH (BNAME, HOD, BLOCK) VALUES('ECE', 'RITA', 'A');

Syntax: For Multiple Record

INSERT ALL  
INTO TABLE_NAME (COL1, COL2, ……..., COLn) VALUES (VAL1,
VAL2, ……..., VALn)
INTO TABLE_NAME (COL1, COL2, ……..., COLn) VALUES (VAL1,
VAL2, ……..., VALn)
INTO TABLE_NAME (COL1, COL2, ……..., COLn) VALUES (VAL1,
VAL2, ……..., VALn)
SELECT * FROM DUAL;  
e.g.; INSERT ALL
INTO BRANCH (BNAME, HOD, BLOCK) VALUES('ECE', 'RITA', 'A')
INTO BRANCH (BNAME, HOD, BLOCK) VALUES('CSE', 'MONICA', 'B')
INTO BRANCH (BNAME, HOD, BLOCK) VALUES('MECH', 'AKSHAYA', 'C')
INTO BRANCH (BNAME, HOD, BLOCK) VALUES('MCA', 'QUEEN', 'D')
SELECT 1 FROM DUAL;
Note:

 Whenever we use INSERT ALL then the SELECT statement is Mandatory.


 SELECT can’t be used alone, it must be given a value followed by “FROM
TABLE_NAME”.
 The TABLE_NAME given must have a Single Record because it doesn’t have an
effect on the data that is inserted.
 If ever the Table has More than One Record, then each record will be inserted for the
no. of Rows in the Table.

UPDATE: It is used to update the value present in the row or record.

Syntax: UPDATE TABLE_NAME


SET COL1 = VAL1, COL2 = VAL2, ……... , COLn = VALn
[WHERE <CONDITION>]

e.g.; UPDATE STUDENT


SET DOJ = ’25-JAN-23’, BNAME = ‘ECE’, DOB = ‘1-JAN-22’
WHERE SID = ‘D1234’;
Note:
e.g.; UPDATE STUDENT
SET SNAME = ‘ABC’, SNAME = ‘PQR’
WHERE SID = ‘A1234’ OR SID = ‘B1234’;
Error: Duplicate Column Name
i.e.; We can’t have the same Column name in a single SET command.

DELETE: It is used to Delete the particular Row or Record.

Syntax: DELETE FROM TABLE_NAME


[WHERE <CONDITION>]
Note: Whenever we want to delete a value from a particular cell, we must update it with
NULL.
e.g.; DELETE FROM BRANCH
WHERE BNAME = ‘CSE’;
i.e.; Here the whole row will be deleted. So, if we want to delete a particular cell we use,
e.g.; UPDATE STUDENT
SET BNAME = NULL
WHERE SID = ‘A1234’;

Transaction Control Language [TCL]

 It is used to Control the Transactions that are done in the Table.


 Here the transactions are nothing but INSERT, UPDATE, and DELETE.
 It has three Statements,
1. COMMIT
2. ROLLBACK
3. SAVEPOINT.

COMMIT: It is used to save the Transactions into the Database.

Syntax: COMMIT;
INSERT INSERT
e.g.;
UPDATE UPDATE
INSERT INSERT
COMMIT
INSERT
DELETE

Worksheet Database
ROLBACK: It is used to undo the Transactions after COMMIT or the previously saved
Transactions.
Syntax: ROLLBACK;
e.g.;
INSERT INSERT
UPDATE UPDATE
INSERT INSERT
COMMIT
INSERT
UPDATE
DELETE
ROLLBACK

Worksheet Database
SAVEPOINT: It is used to mark the Positions or Restoration points.
Syntax: SAVEPOINT SAVEPOINT_NAME;

 ROLLBACK TO S2 – DELETE Transaction is Removed.


 ROLLBACK TO S1 – Both DELETE & UPDATE Transaction are Removed.
 ROLLBACK – Removes all Transactions till COMMIT.
e.g.; INSERT INSERT
UPDATE UPDATE
COMMIT
INSERT
SAVEPOINT S1
UPDATE
SAVEPOINT S2
DELETE
ROLLBACK TO S2
ROLLBACK TO S1
ROLLBACK

Worksheet Database

Data Control Language [DCL]


 It is used to Control the Data-Flow from one user to another user.
 It has two Statements,
1. GRANT
2. REVOKE.
GRANT: It gives permission or access to the Table for another user in the Database.
Syntax: GRANT <SQL Statements>
ON TABLE_NAME
TO USER_NAME;

REVOKE: It is used to take back the given Permission.

Syntax: REVOKE <SQL Statements>


ON TABLE_NAME
FROM USER_NAME;

e.g.; On SCOTT User Database


1st) SQL> SHOW USER;
USER is "SCOTT"
2nd) SQL> GRANT SELECT, INSERT
2 ON DEPT
3 TO HR;
Grant succeeded.
On HR User Database
3rd) SQL> SHOE USER;
USER is “HR”
4th) SQL> SELECT * FROM DEPT;
ERROR: table or view does not exist.
5th) SQL> SELECT * FROM SCOTT. DEPT;
[Table is Displayed]
6th) SQL> INSERT INTO SCOTT.DEPT VALUES (60, 'HIRING', 'HYDERABAD');
1 row created.
On SCOTT User Database
7th) SQL> SELECT * FROM DEPT;
[Table is Displayed] But the Data isn’t Inserted as it was to be in HR User.
On HR User Database
8th) SQL> COMMIT;
Commit complete.
On SCOTT User Database
9th) SQL> SELECT * FROM DEPT;
[Table is Displayed] Data is Successfully Inserted.
On HR User Database (If we try to do any Transactions other than INSERT)
10th) SQL> UPDATE SCOTT.DEPT
2 SET DNAME = 'TRAINING';
ERROR: insufficient privileges.
On SCOTT User Database
11th) SQL> REVOKE SELECT, INSERT
2 ON DEPT
3 FROM HR;
Revoke succeeded.
On HR User Database (If we try to do INSERT or SELECT on DEPT Table)
12th) SQL> SELECT * FROM SCOTT.DEPT;
ERROR: table or view does not exist

Data Query Language [DQL]

 It is used to retrieve the Data from the Database.


 It has four Statements,
1. SELECT
2. PROJECTION
3. SELECTION
4. JOINS
SELECT: It is a Keyword that is responsible for creating the result Table.
PROJECTION: It is the process of retrieving Data by selecting Columns.
SELECTION: It is the process of retrieving Data by selecting both Rows and Columns.
JOINS: It is the process of retrieving Data from Multiple tables Simultaneously.

PROJECTION
Syntax: SELECT * / [DISTINCT] COLUMN_NAME / EXPRESSION [ALIAS]
FROM TABLE_NAME;
Order of Execution
 FROM – First the from Statement will execute.
 SELECT – It will execute after from Statement.
Working Principle
1st) The FROM Clause will be executed first after then the controller will fetch the Table from
the Database and put it under execution.
2nd) To the FROM Clause we can pass TABLE_NAME as an Argument.
3rd) After the execution of the FROM Clause, the SELECT Clause will be executed.
4th) To the SELECT Clause we can pass three Arguments, “ * ” Asterisk, COLUMN_NAME,
EXPRESSION.
th
5 ) The job of the SELECT Clause is to create the result table.
6th) “ * ” Asterisk represents Select the records present in all the Columns.
7th) Along with the “ * ” Asterisk, we can’t give any COLUMN_NAME or EXPRESSION as an
argument to the SELECT Clause.

ST (Student Table)
SID SNAME PER BNAME
1 NIKHIL 84 MCA
2 SATYA 32 BCOM
3 SUBBU 70 MECH
4 GOKUL 84 MCA
5 SRUJANA 65 MECH
6 MANJU 70 MCA

Question-1) Write a Query to Display Student Name [SNAME] and Branch Name
[BNAME] present in the Student Table [ST].

ST (Table under Execution) o/p of FROM Clause


Answers)
SID SNAME PER BNAME
ST 1 NIKHIL 84 MCA
FROM 2 SATYA 32 BCOM
3 SUBBU 70 MECH
4 GOKUL 84 MCA
SNAME BNAME 5 SRUJANA 65 MECH
NIKHIL MCA 6 MANJU 70 MCA
SATYA BCOM
SUBBU MECH
GOKUL MCA
SRUJANA MECH SELECT
MANJU MCA
SELECT SNAME,BNAME
FROM ST;
Question-2) Write a Query to Display the Details of All the Students.
O/P of SELECT Clause
Answers) SELECT * FROM ST;

Question-3) Write a Query to Display the Student Name [SNAME], Percentage [PER],
Student ID [SID], and Branch Name [BNAME].
Answers) SELECT SNAME, PER, SID, BNAME
FROM ST;

Question-4) Write a Query to Display Student ID [SID] along with Branch Name [BNAME].
Answers) SELECT SID, BNAME
FROM ST;

DISTINCT
 It is used to delete Repeated Data.
 DISTINCT must be the first Argument in the SELECT Clause.
 We can pass more than one Column name.
 It removes the combination of Duplicate values.

Question-5) Write a Query to Display DISTINCT Branch Name [BNAME].


Answers) SELECT DISTINCT BNAME
FROM ST;

BNAME RESULT

MCA BNAME
BCOM MCA
MECH BCOM
MCA MECH
MECH
MCA

Question-6) Write a Query to Display DISTINCT Percentage [PER] and Branch Name
[BNAME].
Answers) SELECT DISTINCT PER, BNAME
FROM ST;
RESULT
PER BNAME
84 MCA PER BNAME
32 BCOM 84 MCA
70 MECH 32 BCOM
84 MCA 70 MECH
65 MECH 65 MECH
70 MCA 70 MCA

EXPRESSION
 It is a Mathematical Statement that gives Results.
 It is always the combination of Operators and Operands (Literals).
 An Expression must contain two Operands and a single Operator.

Literals: They are the actual values given to perform a Task. Literals are of three types,

1. Character Literal: ‘NAME’ ex.; ‘Nikhil”


2. Number Literal: NUMBER ex.; 1, 84, 100, 6200854647, etc.
3. Date Literal: ‘DATE’ ex.; ’22-APR-23’ , ’22-apr-23’
 Here Character and Date Literals Must be within the Single Quotes (' ‘).
 Character Literals are Case Sensitive.

ALIAS

 It is an Alternate Name given to a Column or Expression.


 We can give Alias Name with or without using the “AS’ keyword.
 Alias Name must be a single word, if it is of two or more words we can use ( _ )
Underscore or write it within (“ “) Double Quotes.

Note:

 If we ever have to Display a Column or Expression along with ( * ) Asterisk then we


have to give the Table_Name as Reference.
e.g.; To Display the Annual Salary of Employees In the EMP Table with All the
Details.
SELECT EMP.*, SAL * 12 “ANNUAL SALARY”
FROM EMP;

 If we ever use ( * ) Asterisk alone without the Table_Name then the Controller will
expect the FROM keyword as soon as we give ( * ) Asterisk.
Important Point
For Single Line Comment we use: - - (Double Dash)
For Multiple Line Comments we use: /* …………………...
………………...……
*/

Question-1) Write a Query to Display Employee Name (ENAME) with Annual Salary for all
Employees.
Answers) SELECT ENAME, SAL * 12 “ANNUAL SALARY”
FROM EMP;

Question-2) Write a Query to Display Employee Name (ENAME), Job, Salary (SAL) with
rs.100 Bonus.

Answers) SELECT ENAME, JOB, SAL + 100


FROM EMP;

Question-3) Write a Query to Display Employee Name (ENAME), Job, and Annual Salary
with 30 % Hike.

Answers) SELECT ENAME, JOB, SAL * 12 + SAL * 12 * 30 / 100 “Annual Salary


with a 30% Hike”
FROM EMP;

Question-4) Write a Query to Display Employee Name (ENAME), Job as Designation

Answers) SELECT ENAME, JOB AS DESIGNATION


FROM EMP;

Question-5) Write a Query to Display Employee Name (ENAME), Annual Salary with 15 %
Deduction.

Answers) SELECT ENAME, SAL* 12 – SAL * 12 * 15 / 100


FROM EMP;

Question-6) Write a Query to Display Salary (SAL), Half Term Salary, and Annual Salary

Answers) SELECT SAL, SAL * 6, SAL * 12


FROM EMP;

SELECTION

It is the process of retrieving the Data by selecting both Rows and Columns.

1st) WHERE

 It is used to filter the records by the given conditions.


 We can single or multiple conditions.
 The WHERE clause executes in Row-by-Row manner.

Syntax: SELECT * / [DISTINCT] COLUMN_NAME / EXPRESSION [ALIAS]


FROM TABLE_NAME
WHERE <RECORD_FILTER_CONDITION>

Order of Execution

 FROM will be Executed First.


 WHERE will be executed next after FROM in Row-by-Row manner.
 SELECT will be executed next after WHERE in Row-by-Row manner.

Question-1) Write a Query to Display Employee Name (ENAME) who are working in
Department no. - 20.

Answers) SELECT ENAME


FROM EMP
WHERE DEPTNO = 20;

EMP Table EMP Table with DEPTNO = 20

WHERE

Result Table

SE
L
EC
T
O
/P

Question-2) Write a Query to Display Employee Name (ENAME) and Job who are working
as Manager.

Answers) SELECT ENAME, JOB


FROM EMP
WHERE JOB = ‘MANAGER’;

Question-3) Write a Query to Display Employee Name (ENAME) and HIREDATE who
were hired after 25th-Apr-1982.

Answers) SELECT ENAME, HIREDATE


FROM EMP
WHERE HIREDATE > ‘25-APR-82’;

Question-4) Write a Query to Display Employee Name (ENAME) and HIREDATE who
were Hired before 1982.

Answers) SELECT ENAME, HIREDATE


FROM EMP
WHERE HIREDATE < ‘01-JAN-1982’;

Question-5) Write a Query to Display Employee Name (ENAME) who were working as
Clerk.
Answers) SELECT ENAME
FROM EMP
WHERE JOB = ‘CLERK’;
Question-6) Write a Query to Display Employee Name (ENAME) and Salary who were
working as Salesman.
Answers) SELECT ENAME, SAL
FROM EMP
WHERE JOB = ‘SALESMAN’;

Question-7) Write a Query to Display the Details of the Employees who were working
as Salesman.
Answers) SELECT *
FROM EMP
WHERE JOB = ‘SALESMAN’;

Question-8) Write a Query to Display the Details of the Employees who were name is
JONES.
Answers) SELECT *
FROM EMP
WHERE ENAME = ‘JONES’;

Question-9) Write a Query to Display the Details of the Employees who were Hired
after 1st-Jan-1981.
Answers) SELECT *
FROM EMP
WHERE HIREDATE = ‘01-JAN-1981’;

Question-10) Write a Query to Display the Employee Name (ENAME), SAL, and Annual
Salary if Annual Salary is more than 12,000.
Answers) SELECT ENAME, SAL, SAL * 12 “Annual Salary”
FROM EMP
WHERE SAL * 12 > 12000;

Question-11) Write a Query to Display the Details of the Employees who were name is
JONES.
Answers) SELECT *
FROM EMP
WHERE ENAME = ‘JONES’;

Question-12) Write a Query to Display the Details of the Employees who were having
Commission more than Salary.
Answers) SELECT *
FROM EMP
WHERE COMM > SAL;

Question-13) Write a Query to Display the Details of the Employees who were earning
more than 2,000 per month.
Answers) SELECT *
FROM EMP
WHERE SAL > 2000;

Question-14) Write a Query to Display the Employee Name (ENAME) and SAL who’s
Commission is 1,400.

Answers) SELECT ENAME, SAL


FROM EMP
WHERE COMM =1400;

2nd) OPERATORS

 These are the special characters or keywords which is used to perform a


specific task.
 In SQL Operators are of seven types,
1. Arithmetic Operators (+, -, /, *)
2. Relational Operators (=, ! = (OR) < >, >, >=, <, <=)
3. Concatenation Operators (||)
4. Logical Operators (AND, OR, NOT)
5. Special Operators (IN, NOT IN, BETWEEN, NOT
BETWEEN, IS, IS NOT, LIKE, NOT LIKE)
6. Set Operators (UNION, UNION ALL, INTERSECT,
MINUS)
7. Sub Query Operators (ALL, ANY, EXISTS, NOT
EXISTS)

Concatenation Operators

 It is used to join two values.


 Here the values can be of any Datatypes.

Syntax: VALUE1 || VALUE2

e.g.; SELECT ‘MR. ‘ || ENAME


FROM EMP;

Question-1) Write a Query to Display Employee Name (ENAME) with suffix “HELLO”.

Answers) SELECT ENAME || ‘ HELLO’


FROM EMP;

Question-2) Write a Query to Display Employee Name (ENAME) along with Job in the
given format “(ENAME) is working as (JOB)”

Answers) SELECT ENAME || ‘ is working as ‘ || JOB


FROM EMP;
Question-3) Write a Query to Display First_Name and Last_Name together.

Answers) SELECT First_Name || ‘ ‘ || Last_Name Full_Name


FROM A;
Logical Operators

 These operators are used to perform on conditions.


 We can perform logical operations only on Boolean Data.
 Since we don’t have Boolean values in SQL, we always apply these Logical
Operations on Conditions.
 Logical Operators are of three types,
1. AND
2. OR
3. NOT

 AND: It is used to select the Record if all the Conditions are True.

Syntax: Condition1 AND Condition2

Truth Table
Condition 1 Condition 2 Result

True True True

True False False

False True/False False

Question-1) Write a Query to Display Employee Name (ENAME) if he is working as


CLERK in Department no. 30.

Answers) SELECT ENAME


FROM EMP
WHERE DEPTNO = 30 AND JOB = ‘CLERK’;
EMP Table EMP Table with DEPTNO = 30 and JOB = CLERK

WHERE
SELECT O/P

Result Table

Question-2) Write a Query to Display Employee Name (ENAME) earning Salary more
than 1000 and working as a CLERK.

Answers) SELECT ENAME


FROM EMP
WHERE SAL > 1000 AND JOB = ‘CLERK’;

Question-3) Write a Query to Display Employee’s Details who are not working in
Department no. 10 and Department no. 20.

Answers) SELECT ENAME


FROM EMP
WHERE DEPTNO != 10 AND DEPTNO != 20;

Question-4) Write a Query to Display Employee Name (ENAME) who are Hired after the
Year 81 in Department no. 10.

Answers) SELECT ENAME


FROM EMP
WHERE DEPTNO = 10 AND HIREDATE > ’31-DEC-81’;

Question-5) Write a Query to Display Employee Name (ENAME), SAL, and Annual Salary
who’s SAL > 1500 and Annual Salary > 15000.

Answers) SELECT ENAME, SAL, SAL * 12 “Annual Salary”


FROM EMP
WHERE SAL > 1500 AND SAL * 12 > 15000;

Question-6) Write a Query to Display Employee’s Details Hired in the Year 1981.

Answers) SELECT *
FROM EMP
WHERE HIREDATE >= ’01-JAN-81’ AND HIREDATE <= ’31-DEC-81’;

Question-7) Write a Query to Display Employee Name (ENAME) and Salary whose SAL is
in range of 1000 and 3000.

Answers) SELECT ENAME, SAL


FROM EMP
WHERE SAL >= 1000 AND SAL <= 3000;

 OR: It select the records if any one of the conditions is satisfied or


True.
Syntax: SELECT COLUMN_NAME
FROM TABLE_NAME
WHERE [CONDITION 1 OR CONDITION 2];
Truth Table
Condition 1 Condition 2 Result

True True / False True

False True True

False False False


Question-1) Write a Query to Display the Name of the Employee who were Working in
either DEPTNO – 10 or 30.
Answers) SELECT ENAME
FROM EMP
WHERE DEPTNO = 10 OR DEPTNO = 30;

EMP Table EMP Table with DEPTNO = 10 and DEPTN0 = 30

Result Table

WHERE
SELECT O/P

Question-2) Write a Query to Display the Name of the Employee who were Working as a
CLERK or MANAGER.

Answers) SELECT ENAME


FROM EMP
WHERE JOB = ‘CLERK’ OR JOB = ‘MANAGER’;

Question-3) Write a Query to Display the DEPTNO, EMPNO, and JOB if the Employee
reports to 7902 and 7839.

Answers) SELECT DEPTNO, EMPNO, JOB


FROM EMP
WHERE MGR = 7902 OR MGR = 7839;

Question-4) Write a Query to Display the Details of the Employee who were working in
DEPTNO = 20 or working as SALESMAN.

Answers) SELECT *
FROM EMP
WHERE DEPTNO = 20 OR JOB = ‘SALESMAN’;

Question-5) Write a Query to Display the ENAME, DEPTNO, and JOB of the Employee
who is working in DEPTNO = 10 or 20 as a CLERK.

Answers) SELECT ENAME, DEPTNO, JOB


FROM EMP
WHERE (DEPTNO = 10 OR DEPTNO = 20) AND JOB = ‘CLERK’;
Question-6) Write a Query to Display the Details of the Employee who were working as
a CLERK or MANAGER in DEPTNO =20 or 30.

Answers) SELECT *
FROM EMP
WHERE (JOB = ‘CLERK’ OR JOB = ‘MANAGER’) AND (DEPTNO =
20 OR DEPTNO = 30);
Question-7) Write a Query to Display the Details of the Employee who were not working
as MANAGER and also not working in DEPTNO =20 or 30.

Answers) SELECT *
FROM EMP
WHERE JOB != ‘MANAGER’ AND (DEPTNO = 20 OR DEPTNO =30);

Question-8) Write a Query to Display the Details of the Employee who are not hired in
Year – 81 and working in either DEPTNO =10 or 30.

Answers) SELECT *
FROM EMP
WHERE (HIREDATE < ’01-JAN-81’ OR HIREDATE > ’31-DEC-81’)
AND (DEPTNO = 10 OR DEPTNO = 30);

 NOT: It selects the Records if the Condition is False.


Syntax: SELECT COLUMN_NAME
FROM TABLE_NAME
WHERE NOT [CONDITION];
Truth Table
CONDITION RESULT
TRUE FALSE
FALSE TRUE

Question-1) Write a Query to Display the Employee Name (ENAME) who isn’t working in
DEPTNO - 20.

Answers) SELECT ENAME


FROM EMP
WHERE NOT (DEPTNO = 30);

ASSIGNMENT ON LOGICAL OPERATORS:

1.WAQTD DETAILS OF THE EMPLOYEES WORKING AS CLERK AND EARNING LESS


THAN 1500.
2.WAQTD NAME AND HIREDATE OF THE EMPLOYEES WORKING AS MANAGER IN
DEPT 30.

3.WAQTD DETAILS OF THE EMP ALONG WITH ANNUAL SALARY IF THEY ARE
WORKING IN DEPT 30 AS SALESMAN AND THEIR ANNUAL SALARY HAS TO BE
GREATER THAN 14000.

4.WAQTD ALL THE DETAILS OF THE EMP WORKING IN DEPT 30 OR AS ANALYST.

5.WAQTD NAMES OF THE EMPMLOYEES WHOS SALARY IS LESS THAN 1100 AND
THEIR DESIGNATION IS CLERK.
6.WAQTD NAME AND SAL, ANNUAL SAL AND DEPTNO IF DEPTNO IS 20 EARNING
MORE THAN 1100 AND ANNUAL SALARY EXCEEDS 12000.

7.WAQTD EMPNO AND NAMES OF THE EMPLOYEES WORKING AS MANAGER IN


DEPT 20.

8.WAQTD DETAILS OF EMPLOYEES WORKING IN DEPT 20 OR 30.

9.WAQTD DETAILS OF EMPLOYEES WORKING AS ANALYST IN DEPT 10.


10.WAQTD DETAILS OF EMPLOYEE WORKING AS PRESIDENT WITH SALARY OF
RUPEES 4000.

11.WAQTD NAMES AND DEPTNO, JOB OF EMPS WORKING AS CLERK IN DEPT 10


OR 20.

12.WAQTD DETAILS OF EMPLOYEES WORKING AS CLERK OR MANAGER IN


DEPTNO 10.

13.WAQTD NAMES OF EMPLOYEES WORKING IN DEPT 10, 20, 30, 40.


14.WAQTD DETAILS OF EMPLOYEES WITH EMPNO 7902,7839.

15.WAQTD DETAILS OF EMPLOYEES WORKING AS MANAGER OR SALESMAN OR


CLERK.

16.WAQTD NAMES OF EMPLOYEES HIRED AFTER 81 AND BEFORE 87.


17.WAQTD DETAILS OF EMPLOYEES EARNING MORE THAN 1250 BUT LESS THAN
3000.

18.WAQTD NAMES OF EMPLOYEES HIRED AFTER 81 INTO DEPT 10 OR 30.

19.WAQTD NAMES OF EMPLOYEES ALONG WITH ANNUAL SALARY FOR THE


EMPLOYEES WORKING AS MANAGER OR CLERK INTO DEPT 10 OR 30.*

20.WAQTD ALL THE DETAILS ALONG WITH ANNUAL SALARY IF SAL IS BETWEEN
1000 AND 4000 ANNUAL SALARY MORE THAN 15000.
Special Operators

 IN: It is a Multivalued Operator which accepts multiple values at the


RHS.
It selects the record if the value at the LHS is present in the Collection
of values.
Syntax: COLUMN_NAME/EXPRESSION IN (VAL1, VAL2,...…, VALn)

Question-1) Write a Query to Display the name of the Employee who are working as a
CLERK, SALESMAN or as an ANALYSLT.

Answers) SELECT ENAME


FROM EMP
WHERE JOB IN (‘CLERK’, ‘SALESMAN’, ‘ANALYST’);

Question-2) Write a Query to Display the Details of the Employee who are working as a
SALESMAN or as an ANALYSLT in DEPTNO – 20 or 30.

Answers) SELECT *
FROM EMP
WHERE JOB IN (‘SALESMAN’, ‘ANALYST’) AND DEPTNO (20, 30);

Question-3) Write a Query to Display the Details of the Employee who’s is either KING,
BLAKE OR SMITH and working in DEPTNO – 10 or 30.
Answers) SELECT *
FROM EMP
WHERE ENAME IN (‘KING’, ‘BLAKE’, ‘SMITH’) AND DEPTNO (10, 30);

 NOT IN: It is Exactly opposite to IN operator.


It will select the Record if the value at the LHS is not present in the
collection of values.
Syntax: COLUMN_NAME/EXPRESSION NOT IN (VAL1, VAL2,...…,
VALn)

Question-1) Write a Query to Display the Details of the Employee who are not working
in DEPTNO – 10 or 30.
Answers) SELECT *
FROM EMP
WHERE DEPTNO NOT IN (10, 30);

Question-2) Write a Query to Display the Details of the Employee along with Annual
Salary if Employee doesn’t work as PRESIDENT or as SALESMAN AND
Annual Salary more than 14000.

Answers) SELECT EMP.*, SAL*12 “Annual Salary”


FROM EMP
WHERE JOB NOT IN (‘PRESIDENT’, ‘SALESMAN’) AND SAL*12 > 14000;

 BETWEEN: This operator is used whenever we have range of values.


It will select t6he record if the value is in the given range.
Syntax: COLUMN_NAME/EXPRESSION BETWEEN
LOWER_RANGE AND HIGHER_RANGE
e.g.; SAL BETWEEN 1000 AND 3000
SAL >= 1000 AND SAL <= 3000
Question-1) Write a Query to Display the Name and Salary of the Employee who are
earning in range of 1000 and 3000.

Answers) SELECT ENAME, SAL


FROM EMP
WHERE SAL BETWEEN 1000 AND 3000;

Question-2) Write a Query to Display the Details of the Employee who are hired in year 81
in DEPTNO – 20 or 30.

Answers) SELECT *
FROM EMP
WHERE HIREDATE BETWEEN (’01-JAN-81’ AND ’31-DEC-81’) AND
DEPTNO IN (20, 30);

Question-3) Write a Query to Display the Details of the Employee who are earning more
than 1000 but less than 3000.

Answers) SELECT *
FROM EMP
WHERE SAL BETWEEN 1001 AND 2999;

Question-4) Write a Query to Display the Details of the Employee who are hired after year
81 but before year 87 and having Annual Salary in range of 10000 to 15000.

Answers) SELECT *
FROM EMP
WHERE HIREDATE BETWEEN (’01-JAN-81’ AND ’31-DEC-86’) AND
SAL*12 BETWEEN 10000 AND 15000;
 NOT BETWEEN: It is opposite of between.
It selects the record if it is not between the given range.

Syntax: COLUMN_NAME / EXPRESSION NOT BETWEEN


LOWER_RANGE AND HIGER_RANGE

e.g.; SAL NOT BETWEEN 1000 AND 3000


SAL < 1000 AND SAL > 3000

You might also like