BASICS OF SQL
What is SQL?
SQL stands for Structured Query Language.
SQL is a standard database language for
accessing and manipulating.
What SQL can do?
SQL can query against database like creating a table,
inserting records into table, updating records in
table, deleting records from table, creating stored
procedures, views and triggers etc.
SQL Commands
DDL: Data Definition Language
DDL or Data Definition Language actually consists of the SQL
commands that can be used to define the database schema. It
simply deals with descriptions of the database schema and is used
to create and modify the structure of database objects in
database.
Below are the Schema change statements.
DDL Commands,
Create: is used to create the database or its objects (like table, database,
views, stored procedures and triggers).
Drop: is used to delete objects from the database.
Alter: is used to alter the structure of the database.
Truncate: is used to remove all records from a table, including all spaces
allocated for the records are removed.
DML: Data Modification Language
The SQL commands that deals with the manipulation of
data present in database belong to DML or Data
Manipulation Language and this includes most of the
SQL statements.
DML commands,
Select: is used to retrieve data from the database.
Insert: is used to insert data into a table.
Update: is used to update existing content in the
table.
Delete: is used to delete record(s) from the table.
DCL: Data Control Language
DCL includes commands such as GRANT and
REVOKE which mainly deals with the rights,
permissions and other controls of the database
system.
DCL commands,
Grant: gives user’s access privileges to database.
GRANT PRIVILEGE ON DB_OBJECT TO USER
GRANT CONNECT,CREATE SESSION, RESOURCE TO RAGHAV;
Revoke: withdraw user’s access privileges given by
using the GRANT command.
REVOKE PRIVILEGE ON DB_OBJECT FROM USER
REVOKE CONNECT,CREATE SESSION,RESOURCE FROM RAGHAV;
TCL: Transaction Control Language
TCL commands deals with the transaction
within the database.
TCL commands,
Commit: Commits a Transaction.
COMMIT;
SET AUTO COMMIT ON;
Rollback: Rollbacks a transaction in case of any
error occurs.
ROLLBACK TO SAVEPOINT_NAME;
Savepoint: Sets a save point within a transaction.
SAVEPOINT SAVEPOINT_NAME;
Basic Data types in SQL
Data Type Description
CHARACTER(n) Character string. Fixed-length n
VARCHAR2(n) or Character string. Variable length. Maximum length n
VARCHAR(n)
NUMBER ,NUMERIC Exact numerical, precision p, scale s. (Same as DECIMAL)
NUMBER( p, s),
NUMERIC( p, s)
INTEGER Integer numerical (no decimal). Precision 10
FLOAT Approximate numerical, mantissa precision 16
DECIMAL(p, s) Exact numerical, precision p, scale s. Example: decimal(5,2) is a
number that has 3 digits before the decimal and 2 digits after
the decimal
DATE,TIMESTAMP Stores year, month, and day values (DD-MON-YY)
Specifying Basic constraints in SQL
The following constraints are commonly used in SQL:
NOT NULL - Ensures that a column cannot have a NULL value
UNIQUE - Ensures that all values in a column are different
PRIMARY KEY - A combination of a NOT NULL and UNIQUE.
Uniquely identifies each row in a table
FOREIGN KEY - A foreign key is a column or a set of columns
in one table that references the primary key columns in
another table.
CHECK - Ensures that all values in a column satisfies a specific
condition
DEFAULT - Sets a default value for a column when no value is
specified
Create & Drop In SQL
Syntax for Creating table:
create table <table_name>
(column 1 datatype 1,
column 2 datatype 2,
column 3 datatype 3
: :
column n datatype n);
Syntax for Dropping table from database:
drop table <table_name>;
CREATE TABLE STUDENT(
ROLLNO NUMBER UNIQUE,
USN VARCHAR2(10) PRIMARY KEY,
NAME VARCHAR2(10),
DEPT VARCHAR2(5) NOT NULL,
AGE NUMBER CHECK AGE>19,
ADDRESS VARCHAR2(10) DEFAULT ‘KLE’
);
ROLLNO USN NAME DEPT AGE ADDRESS
DML - Insert, select, delete, update
Insert:
insert into <table_name> values(value-1,value-2,…value-n);
Delete:
delete from <table_name> where <condition>
Select:
Select <column_name>
From <table_name>
Where <condition>
Group by <column_name>
Having < condition >
Order by ASC or DESC <column_name>
Update:
Update <Table_name> Set <column_name>=<value> Where
<Condition>
ALTER COMMAND
Adding a new column to an existing table:
ALTER TABLE <TABLE_NAME> ADD <COLUMN_NAME> <DATA_TYPE>
Adding multiple columns to an existing table:
ALTER TABLE <TABLE_NAME> ADD( <COLUMN_NAME1>
<DATA_TYPE1>, <COLUMN_NAME2> <DATA_TYPE2>,….);
Dropping an existing column from a table:
ALTER TABLE <TABLE_NAME> DROP COLUMN <COLUMN_NAME>
Renaming an existing column in a table:
ALTER TABLE <TABLE_NAME> RENAME COLUMN <OLD_COLUMN>
TO <NEW_COLUMN>
Modifying the data type of an existing column in a table:
ALTER TABLE <TABLE_NAME> MODIFY <COLUMN_NAME>
<DATA_TYPE>
ALTER COMMAND
ADDING PRIMARY KEY CONSTRAINTS USING ALTER:
ALTER TABLE <TABLE_NAME> ADD PRIMARY KEY
(<COLUMN_NAME>)
ADDING FOREIGN KEY CONSTRAINTS USING ALTER:
ALTER TABLE <CHILD TABLE_NAME> ADD FOREIGN KEY
(<CHILD COLUMN_NAME>) REFERENCES
<PARENT TABLE_NAME> (<PARENT COLUMN_NAME >)
SQL Logical Operators
Operator Description
AND Logical AND compares between two Booleans as expression and returns true
when both expressions are true...
OR Logical OR compares between two Booleans as expression and returns true
when one of the expression is true...
NOT Not takes a single Boolean as an argument and changes its value from false to
true or from true to false....
EXAMPLES
SELECT * SELECT *
FROM STUDENT FROM STUDENT
WHERE SEM=4 AND DEPARTMENT=‘CS’; WHERE SEM=4 OR DEPARTMENT=‘CS’;
SELECT *
FROM STUDENT
WHERE NOT SEM=4;
Special operators :
Operator Description
IN The IN operator checks a value within a set of values separated by commas and
retrieve the rows from the table which are matching.... NOT IN is opposite of IN
BETWEEN The SQL BETWEEN operator tests an expression against a range. The range consists
of a beginning, followed by an AND keyword and an end expression....
ANY ANY compares a value to each value in a list or results from a query and evaluates
to true if the result of an inner query contains at least one row....
ALL ALL is used to select all records of a SELECT STATEMENT. It compares a value to
every value in a list or results from a query. The ALL must be preceded by the
comparison operators and evaluates to TRUE if the query returns no rows....
SOME SOME compare a value to each value in a list or results from a query and evaluate
to true if the result of an inner query contains at least one row...
EXISTS The EXISTS checks the existence of a result of a sub query. The EXISTS sub query
tests whether a sub query fetches at least one row. When no data is returned then
this operator returns 'FALSE'... NOT EXISTS is opposite of EXISTS
EXAMPLES OF SPECIAL OPERATORS
LIKE Operator
SET OPERATIONS IN SQL
SQL supports few Set operations which can be performed on the
table data. These are used to get meaningful results from data
stored in the table, under different special conditions.
UNION
UNION ALL
INTERSECT
MINUS
NOTE: YELLOW IS RESULT
UNION
It is used to combine the results of two or more SELECT
statements. However it will eliminate duplicate rows from its
result set.
In case of union, number of columns and data type must be
same in both the tables, on which UNION operation is being
applied.
SELECT USN FROM TABLE1 UNION SELECT USN FROM TABLE2
ROLLNO USN SEM ROLLNO USN SEM
1 2KL16CS001 2 1 2KL16EE001 2
2 2KL16CS002 4 2 2KL16EE001 4
RESULT-----> 2KL16CS001, 2KL16CS002,2KL16EE001
UNION ALL
It is used to combine the results of two or more SELECT
statements.
This operation is similar to Union. But it also shows the
duplicate rows.
SELECT USN FROM TABLE1 UNION ALL SELECT USN FROM TABLE2
ROLLNO USN SEM ROLLNO USN SEM
1 2KL16CS001 2 1 2KL16EE001 2
2 2KL16CS001 4 2 2KL16EE002 4
RESULT-----> 2KL16CS001 2KL16CS001 2KL16EE001 2KL16EE002
INTERSECT
Intersect operation is used to combine two SELECT
statements, But it only returns the records which are common
from both SELECT statements.
In case of Intersect the number of columns and data type
must be same.
NOTE: MySQL does not support INTERSECT operator.
SELECT USN FROM TABLE1 INTERSECT SELECT USN FROM TABLE2
ROLLNO USN SEM ROLLNO USN SEM
1 2KL16CS001 2 1 2KL16CS001 2
2 2KL16CS002 4 2 2KL16EE001 4
RESULT----> 2KL16CS001
MINUS
The Minus operation combines results of two SELECT
statements and return only those in the final result,
which belongs to the first set of the result.
SELECT USN FROM TABLE1 MINUS SELECT USN FROM TABLE2;
ROLLNO USN SEM ROLLNO USN SEM
1 2KL16CS001 2 1 2KL16CS001 2
2 2KL16CS002 4 2 2KL16EE001 4
RESULT--->2KL16CS002
Displaying Tables
AGGREGATE FUNCTIONS
An aggregate function allows you to perform a calculation
on a set of values to return a single scalar value.
We often use aggregate functions with the GROUP
BY and HAVING clauses of the SELECT statement.
• AVG – calculates the average of a set of values.
• COUNT – counts rows in a specified table or view.
• MIN – gets the minimum value in a set of values.
• MAX – gets the maximum value in a set of values.
• SUM – calculates the sum of values.
EXAMPLES FOR AGGREGATE FUNCTIONS
SELECT COUNT(*)
EMPLOYEE FROM EMPLOYEE
EID ENAME AGE GENDER SALARY DID
11 ANIL 27 M 65000 1 SELECT AVG(AGE)
FROM EMPLOYEE
12 BIPIN 23 M 55000 1
13 DIYA 25 F 65000 1
SELECT MAX(AGE)
14 RAVI 24 M 25000 2 FROM EMPLOYEE
15 VINUTH 27 M 25000 2
SELECT SUM(SALARY)
16 UTTAM 28 M 35000 3
FROM EMPLOYEE
17 MEGHA 29 F 45000 3
SELECT MIN(SALARY)
FROM EMPLOYEE
SCHEMA DIAGAM FOR COMPANY DATABASE
EMPLOYEE EID ENAME AGE GENDER SALARY DID
DEPARTMENT DID DNAME DHEAD
PROJECTS PID PNAME PLOCATION DID
WORKSON EID PID HOURS
Consider the Company Database,
EMPLOYEE (EID, ENAME, AGE, GENDER, SALARY, DID)
DEPARTMENT (DID, DNAME, DHEAD)
PROJECTS (PID, PNAME, PLOCATION, DID)
WORKSON (EID, PID, HOURS)
EMPLOYEE
EID ENAME AGE GENDER SALARY DID
11 ANIL 27 M 65000 1
DEPARTMENT
12 BIPIN 23 M 55000 1 DID DNAME DHEAD
13 DIYA 25 F 65000 1 1 DESIGN BIPIN
14 RAVI 24 M 25000 2 2 SALES RAVI
15 VINUTH 27 M 25000 2
3 ACCOUNT UTTAM
16 UTTAM 28 M 35000 3
4 PRODUCTION DIYA
17 MEGHA 29 F 45000 3
PROJECTS WORKSON
PID PNAME PLOCATION DID EID PID HOURS
111 PSLV-G Bengaluru 1 11 111 10
222 ARV-1 Bengaluru 1 11 222 10
333 UAN-L Hyderabad 2 12 111 8
444 SLV New Delhi 3 13 333 8
1. Retrieve the details of Employees who draw salary between Rs.25000/- and
Rs.55000/-
2. Retrieve the details of Employees whose age is more than 24.
3. Retrieve the details of Employees whose age is less than 25 and salary is more
than Rs.35000/-.
4. Retrieve the details of Female Employees who draw salary more than Rs.
50000/-
5. Retrieve the details of Employees whose names starts with letter ‘A’.
6. Count the total number of employees working in the company.
7. Find the Highest salary drawn by an employee.
8. Find the age of the Oldest Employee working in the company.
9. Find the details of the youngest employee working in the company.
[Link] the Highest, Lowest and Average Salary drawn by an Employee.
[Link] the total salary drawn by the employees of department number 2.
[Link] the details of employees who are working for “Design” Department.
13. Retrieve the details of Employees who draw maximum salary in the Company.
14. Count the number of Employees who are working for “Sales” Department.
15. Count the total number of Employees working in each Department.
16. Retrieve the details of those Departments who have more than 3 Employees.
17. Retrieve the details of the youngest Employee working in “Design” Department.
18. Retrieve the name of the Department which has no Employees working in it.
19. Retrieve the Project names and their locations controlled by “Design” Department.
20. Retrieve the names of the employees who are working in the Project “PSLV-G”.
21. Find the names of the Projects in which “ANIL” is working.
22. Find the Department names who is not controlling any projects.
23. Retrieve the total number of Projects controlled by each Department.
24. Retrieve the total no of hours worked by “ANIL” in all his projects.
25. Retrieve the Names of the Employees in alphabetical order.
Select Column-1,Column-2,…Column-n (or just * for all columns)
From table_name-1, table_name-2,…. table_name-n
Where condition (use operators like relational, logical, like between, in, not in etc)
Group by column_name(s)
Having condition (condition is applied on the groups formed)
Order by ASC or DESC column_name(s) (default it is ascending)
SAILORS
SIDS SNAME RATING AGE
111 S1 7 22
222 S2 6 24
333 S3 8 30
444 S4 9 26
555 S5 10 28
RESERVES BOATS
BID BNAME COLOR SIDS BID DAY
1 B1 RED 111 1 MON
2 B2 BLUE 111 2 TUE
3 B3 GREEN 222 1 THU
4 B4 YELLOW 333 3 FRI
5 B5 PURPLE 444 4 SAT
• Find the names and ages of all sailors.
• Find all sailors with a rating above 7.
• Find the names of sailors who have reserved
boat number 3.
• Find the sids of sailors who have reserved a
red boat.
• Find the colors of boats reserved by JOHN.
• Find the names of sailors who have reserved
at least one boat.
• Compute increments for the ratings of persons
who have sailed two different boats on the
same day.
SELECT [Link], [Link]+1 AS rating
FROM Sailors S, Reserves R1, Reserves R2
WHERE [Link] = [Link] AND [Link] = [Link] AND
[Link] = [Link] AND [Link] <> [Link]
• Find the names of sailors who have reserved a
red or a green boat.
SELECT [Link]
FROM Sailors S, Reserves R, Boats B
WHERE [Link] = [Link] AND [Link] = [Link] AND
([Link] = ‘red’ OR [Link] = ‘green’)
• Find the names of sailors who have reserved both a red
and a green boat.
SELECT [Link] FROM Sailors S, Reserves R1, Boats B1,
Reserves R2, Boats B2 WHERE [Link] = [Link] AND [Link]
= [Link] AND [Link] = [Link] AND [Link] = [Link] AND
[Link]=‘red’ AND [Link] = ‘green’
SELECT [Link] FROM Sailors S, Reserves R, Boats B
WHERE [Link] = [Link] AND [Link] = [Link] AND [Link] =
‘red’ UNION SELECT [Link] FROM Sailors S2, Boats
B2, Reserves R2 WHERE [Link] = [Link] AND [Link] =
[Link] AND [Link] = ‘green’
• Find the names of sailors who have NOT reserved
ANY boat . (USE NOT IN FOR NOT RESERVED ANY
BOAT)
SELECT [Link]
FROM Sailors S
WHERE [Link]
IN
(SELECT [Link]
FROM Reserves R);
• Find the sids of all sailors who have reserved
red boats but not green boats.
SELECT [Link] FROM Boats B, Reserves R
WHERE [Link] = [Link] AND [Link] = ‘red’
EXCEPT OR MINUS
SELECT [Link] FROM Boats B2, Reserves R2
WHERE [Link] = [Link] AND [Link] = ‘green’
• Find the names of sailors who have reserved
both a red and a green boat.
SELECT [Link] FROM Sailors S, Reserves R,
Boats B WHERE [Link] = [Link] AND [Link] = [Link]
AND [Link] = ‘red’ AND [Link] IN ( SELECT
[Link] FROM Sailors S2, Boats B2, Reserves R2
WHERE [Link] = [Link] AND [Link] = [Link]
AND [Link] = ‘green’ )
• Find the names of sailors who have reserved
all boats.
SELECT [Link]
FROM Sailors S
WHERE NOT EXISTS
(( SELECT [Link] FROM Boats B ) minus
(SELECT [Link] FROM Reserves R WHERE [Link]
= [Link] ))
• Find the names of sailors who are older than
the oldest sailor with a rating of 10.
SELECT [Link] FROM Sailors S WHERE [Link]
> ( SELECT MAX ( [Link] ) FROM Sailors S2
WHERE [Link] = 10 )