SQL Notes Campus Monk
SQL Notes Campus Monk
To store multiple information, the most convenient way is to store the information on
the internet. To do this we can make use of databases.
• Student
• Course
• Department
• Instructor
• Student name
• Student Id
• Course Name
• Description
• Department
• Name
SQL is the structured query language which will be used to communicate with
the database that we have created.
We use certain queries to communicate with our database, for eg:-
For e.g: -
1 Riya 25
2 Divya 23
• Record - All the single entry or row in a table is known as a record. So, in the
above example we have 2 records.
• Fields :- The name of the columns in a table are fields. In the above example,
S.No, Name, Age are fields
• Column - It is a set of the same datatype value. Eg, Name(String), Age(Integer).
Types Of Commands
Commands In SQL: SQL commands are used for database communication.
Additionally, they are utilised to carry out duties, activities, and data enquiries. Table
creation, data addition, table deletion, table modification, and user permission setting
are just a few of the many activities that we can do with the help of SQL commands.
1. DDL: - Whenever there’s the need to change the structure of any table for example
creating the table, deleting the table or altering the table DDL come into the role. If any
change is made in DDL than it can’t be rolled back. Hence, they are permanent.
2. DML: - Whenever there’s the need to modify the database than DML come into the
role than DML is responsible for all possible changes in the database. If any change is
made in DML than it can be rolled back. Hence, they are not permanent.
3. DCL: - Whenever there’s the need to grant or take back authority from any user
in the database than DCL come into the role.
4. TCL: - TCL commands are the commands which are automatically committed and
can only used with DML commands like INSERT, DELETE etc. These commands cannot
be used while creating or Dropping tables.
5. DQL: - Whenever there’s the need to fetch the data from the database than DQL
come into the role. Whenever we need to print something or show something as
output than this command is needed.
Key: - key is used to identify each record or row of data in the table in a unique way.
Additionally, it is employed to define and pinpoint links between tables.
1. Primary Key: - It is the initial key used to uniquely identify each instance of an
object. An entity can have many keys. From those lists, the key that is most
appropriate becomes the primary key.
Example: -
Let say student details is a table that contains roll number, name, and class as
columns.
Here Primary key = Roll number
2. Candidate Key: - A minimum group of attributes that may independently identify
any other attribute is known as a candidate key.
The remaining attributes except primary key are regarded as candidate key. The
candidate keys are just as secure as the primary key.
Example: -
Let say student details is a table that contains roll number, name, and class as
columns.
Here Primary key = Roll number
So remaining name and class are considered as a candidate key.
3. Super Key: - Any numbers of attributes that may independently identify any other
attribute is known as a Super key.
Example: -
Let say student details is a table that contains roll number, name, and class as
columns.
Group of all 3 attributes will be considered as Super key.
4. Foreign Key: - A table's foreign key is a column that is used to refer to another
table's primary key.
Example: -
Let say student details is a table that contains roll number, name, and class as
columns.
And if there is another table where class and class teachers are attributes.
Here Foreign key = Class
5. Alternate Key: - The number of candidate keys minus the primary key equals the
total number of alternate keys. There could or might not be an alternative key. If
we have just one candidate key than does not have any alternate key.
Inserting Data
To insert the data into the table we use the INSERT INTO query.
INSERT INTO: -To insert new records inside the table, we use insert into key word.
We can use insert into syntax in two major ways: -
Let say we have the table Students with attributes as Roll number, Student name, and
class.
To insert details of new Student syntax that will be used will be: -
1. INSERT INTO Students
VALUES (17, Rohit, 12);
SELECT statement
Select: - To select any data from the database we generally use SELECT statements.
We may also obtain a specific record from a certain table column by using this
command. A result-set table is the one that contains the record that the SELECT query
returned.
Example: - We have a Table CUSTOMERS given here along with attributes as ID,
NAME, AGE, ADDRESS, and SALARY.
+-----+----------+-----+-----------+----------+--------+
| ID | NAME | AGE | ADDRESS | SALARY |
+-----+----------+-----+-----------+----------+---------+
+----+----------+-----+-----------+----------+----------+
| ID | NAME | SALARY |
+--+---------+-----------+
| 1 | Rohit | 20000.00 |
| 2 | Deepak | 12500.00 |
| 3 | Nisha | 21000.00 |
| 4 | Parveen | 65000.00 |
| 5 | Samay | 85000.00 |
| 6 | Virat | 5100.00 |
| 7 | Nikhil | 70000.00 |
+----+----------+--------------+
+-----+----------+-----+-----------+----------+--------+
| ID | NAME | AGE | ADDRESS | SALARY |
+-----+----------+-----+-----------+----------+---------+
+----+----------+-----+-----------+----------+----------+
Numbers:
Numbers are of three types either Integer value which can be created as int.
Example:
Characters:
The character values can be stored in the form of the strings or character, the data
which is stored statically stored in data type 'CHAR' and the data which needs to be
stored dynamically stored in 'VARCHAR'
Date can be stored in the following given format by using the Date data type:
Date-YYYY MM DD
Year can be stored in the following given format by using the Year data type:
Year-YY/YYYY
Date and timing can be stored in combined format in the following given format by
using the DateTime data type:
Datetime-YYYY MM DD HH MM SS
Constraints in SQL
The constraints which will be applied on the fields to maintain the data suppose the
column data should be unique or not null and many other constraints would help in
maintaining the data.
NOT NULL:
The Not Null constraint helps in creating the fields data which can't be allowed to have
any NULL value in the whole column data.
Example:
UNIQUE:
The UNIQUE constraint would help in having the data which is not going to be
duplicate in the same column.
Example:
PRIMARY KEY:
The primary key is the key which can be just assigned to only one field in one table,
and this primary key would help in making the fields UNIQUE as well as NOT NULL.
Example:
FOREIGN KEY:
The Foreign key is a key which belongs to the other table primary key, suppose you
have a ID of the orders table, and you want to reference that ID to the another table
named customers then this constraint would be helpful.
Example:
);
);
CHECK:
The check constraint would help in checking a particular condition while inserting the
data, suppose if you are feeding less than 18 age in a adult form than it not needs to be
submitted.
Example:
ID int,
DEFAULT:
The default constraint is used when we needs to have the default value when there is
no value will get entered by the user.
Example:
ID int,
)
SELECT, WHERE, AND, OR clause in SQL
SELECT clause:
The select clause helps in printing the values present in the table
Example:
SELECT * FROM example; // here example is the name of table already exist in
database
Output:
Name Age
Anupam 22
Kunal 20
Rishabh 25
WHERE clause:
The WHERE clause helps in making some decision inside the query data printing,
suppose you need to print the data whose age is 22.
Output:
Name Age
Anupam 22
These clauses helps in making a decision when there is more than one condition is
required.
Suppose you need to print the values whose age is between 21 and 23
Example 1:
Name Age
Anupam 22
Suppose you need to print the values whose age is less than 21 or greater than 26.
Example 2:
Output:
Name Age
Kunal 20
Create table(
Name varchar(100),
Age int
);
Then inserting the following data into the above given table:
LIKE clause:
This clause helps to print the values whose particular value looks like something
specific.
Suppose, you need to print the values whose name is starting with A.
Example:
Output:
Name Age
Anupam 22
Similarly , you need to print the values whose name is ending with m.
Example:
Name Age
Anupam 22
TOP clause:
This clause helps in printing the values with the specific number of top values.
Example:
Anupam 22
Kunal 20
The UPDATE keyword uses in updating the rows data in the system.
Example:
UPDATE example
SET name = ‘Rohit’
WHERE age = 20;
SELECT * FROM example;
Output:
Name Age
Anupam 22
Rohit 20
Rishabh 25
DELETE clause:
The delete keyword is used in deleting the particular query from the table data.
Suppose you need to delete the data from the table whose name is ‘Anupam’
Example:
Name Age
Rohit 20
Rishabh 25
Operators In SQL
1. Arithmetic Operators: -
The mathematical operations are carried out by the arithmetic operators on the
numerical
data in SQL tables. On the numerical operands, these operators carry out the
operations
of addition, subtraction, multiplication, and division.
Example: -
I. SQL Addition Operator
SELECT operand1 + operand2;
II. SQL Subtraction Operator
SELECT operand1 - operand2;
III. SQL Multiplication Operator
SELECT operand1 * operand2;
IV. SQL Division Operator
SELECT operand1 / operand2;
2. Comparison Operators: -
The SQL comparison operators compare two distinct SQL table values and
determine
whether they are equal, greater, or less. The WHERE clause and SQL comparison
operators are combined in SQL queries.
Example: -
I. SQL Equal operator (=)
II. SQL Not Equal operator (! =)
III. SQL Greater Than operator (>)
IV. SQL Greater Than Equals to operator (>=)
V. SQL Less Than operator (<)
VI. SQL Less Than Equals to operator (<=)
3. Logical Operators: -
Boolean operations, which produce the two outcomes True and False, are carried
out by
the logical operators in SQL. If the logical condition is met by both operands, these
operators return True.
Example: -
I. ALL operator: - It is used with SELECT, HAVING and WHERE statements.
II. AND operator: - It is used with WHERE clause.
III. OR operator: - It is used with WHERE clause.
IV. BETWEEN operator: -To show record within the range mentioned in query.
V. IN operator: - It is used with WHERE clause.
VI. NOT operator: - It is used to show records where condition results in false.
VII. ANY operator: - It is used to show records when at least one sub query value is
true.
VIII. LIKE operator: - It is used in WHERE clause with SELECT, UPDATE and DELETE
statements.
4. Wildcard Operators: -
To replace one or more characters in a string, use a wildcard character. The LIKE
operator uses wildcard characters. To look for a specific pattern in a column, use
the
LIKE operator in a WHERE clause.
Example: -
I. Words that starts with A: - WHERE WORD LIKE ‘A%’
II. Words that have A at any position: - WHERE WORD LIKE ‘%A%’
III. Words that have A at 2nd positon: - WHERE WORD LIKE ‘_A%’
V. Words that have five alphabets and end with B: - WHERE WORD LIKE ‘____B’
JOINS
WHAT ARE JOINS
Joins in SQL are used to combine data or rows from two or more tables based on a
common field between them.
Let’s consider this example. We have two tables named student and studentcourse.
Table Student
Table StudentCourse
Course_id Roll_No
1 1
2 5
2 3
5 2
3 6
Now suppose we want to fetch the course_id of the student Rohit. We can see that name
and course_id are in different columns, but there is a common attribute in both of the
tables that is Roll_No. So what we can do is, we can take the roll_no of the Rohit from
table student and then from roll_no we can take the course_id from the table
StudentCourse.
Note: We can do other things as well like we want to check the age of students who
have the same course_ids. So we can take roll_no’s from table StudentCourse and then
from table Student we will check the ages of those students.
Types of joins-
There can be some problems while joining the tables in SQL like for example, for any
entry in table A there is a possible situation that entry is not present in table B. So for
dealing with these kinds of scenarios we have different types of joins. These are-
Inner join- Inner join will give the common values from both the tables as the resultant
set.So for example if we apply inner join on the above table then it will give the resultant
set as values having common roll_no’s.
Left Join- It will give all the values from table1 and will provide only the matching
values from table2 and if no value is present for any value in table2 than it will provide
NULL .So from the above table it will give all the values from table1 and matching values
from table2.
Right Join- It will give all the values from table2 and only matching values with table1
and if no value is present for any value in table1 then it will provide NULL . So from the
above table it will give all the values from table2 and matching values from table1.
Full Join/Outer Join- It will give all the values from table1 and table2.
UNION
The union clause is used to combine two separate select statements and produce the
result set as a union of both the select statements.
This statement is used if we want that our resultant set contains distinct values.
This statement is used if we want that our resultant set contains duplicate values too.
Notes: The fields used in both the select statements must be in the same order, number
and data type.
The Union clause produces distinct values in the result set, to fetch the duplicate values
too UNION ALL must be used instead of UNION.
Student
Student_Details
1 IT O
2 CSE E
3 CSE O
4 ME A
So the syntax will be for not wanting duplicates in the resultant set will be
SELECT ROLL_NO FROM Student UNION SELECT ROLL_NO FROM Student Details;
SELECT ROLL_NO FROM Student UNION ALL SELECT ROLL_NO FROM Student Details;
Output -
For query1 the output will be 4 rows from the beginning joined from union
1 Anupam 12 23
2 Kunal 12 25
First of all, we need to create the structure of the database by using the following SQL
command:
After execution of the above steps, we can simply copy the data of table1 to table2 by
using the following command:
1 Anupam 12 23
2 Kunal 12 25
Handling Duplicates
In this , we would learn how to handle a table which is having the duplicate values in
the same table but we just need to have the values which is not duplicate in the list.
Let's take an example, we are having a table which is having the name "Anupam" more
than one time:
Anupam 2 ECE
Anupam 3 EEE
Suppose we just need to print the data only once with the same name than this
condition would help in handling duplicates.
This following given line would help in removing the duplicated data in case of similar
name removal.
After using the command, we will just get one record with the name "Anupam".
DCL Commands
-> We are aware that SQL enables a user to specify the structure, classification, and
relationships among the data items to be stored as well as how to access the data from
the database.
-> The user can also modify and change the current data in the database of an
application software.
-> Thus, we will discover how SQL may be used in this article to deny a user the ability
to alter, add to, or retrieve data and safeguard all data from unauthorised access. Data
Control Language (DCL) in SQL is used for this.
-> Data Control Language (DCL) is the name given to the set of SQL commands that
allow a user to access, modify, or interact with the various rights needed to control the
database.
1. GRANT: -The GRANT DCL command is used to grant (provide access to) security
rights to particular database users. It mostly serves to limit user access to INSERT,
SLECT, UPDATE, DELETE etc. or to provide access to user’s data.
2. REVOKE: -The REVOKE DCL command is used to revoke access that has been
granted using the GRANT command. Removing the authorization that was granted to
carry out particular operations is the main application of going back to the time when
no access was specified.
Some of the examples through which we will try to understand these two operations
are: -
Examples of GRANT: -
III. Now after allowing to create table how to grant permission for creating
any table
GRANT CREATE ANY TABLE TO mytab;
Examples of REVOKE: -
-> Transaction is what results from several instructions being executed one after the
other in a database.
-> The user can manage the transactions that occur in a database by using particular
SQL commands called as TCL commands.
Particularly they are: -
1. COMMIT: -
To save all transaction-related changes to the disc permanently in SQL,
use the COMMIT command. When DDL commands like INSERT,
UPDATE, and DELETE are performed, the modifications they make
become permanent only after the current session is closed.
Example: -
Basic syntax for using COMMIT command is: -
BEGIN TRANSACTION;
(A set of SQL statements)
COMMIT TRANSACTION;
More simplified version of using this command is: -
(A set of SQL statements)
COMMIT;
2. ROLLBACK: -
The COMMIT command's ROLLBACK option resets the database to its
initial state.
It is employed to return the database to its most recently committed state.
Example: -
So let say we deleted the record of age where age is equal to 30 years.
Now we have to ROLLBACK that. So, syntax of this is: -
DELETE FROM CUSTOMERS
WHERE age = 30;
ROLLBACK;
So, this query will get back the deleted values again to the table.
3. SAVEPOINT: -
The database operations may be split up into different components. For
instance, we may think of the delete command as one half of the
transaction and all the insert-related queries that we would run
sequentially as the other.
We may store these several components of the same transaction using
various names by utilising the SAVEPOINT command.
EXAMPLE: -
Syntax of SAVEPOINT Command is shown below.
SAVEPOINT Name_of_Savepoint;
FUNCTION IN SQL-
DATE FUNCTIONS
The first function in SQL is GETDATE(). This GETDATE() function will return the
current date and time.
Syntax-
SELECT GETDATE();
Output-
2022-10-27 19:52:15
We can also provide some ALIAS to this and the syntax for it will be -
Output-
2022-10-27 19:52:15
DATEPART- This function will select a certain part from a date and the part that is
going to split will depend on us. It takes two parameters, one is what part you want to
select and second is from which date we want to select.
Syntax, if we want to select the year
Output-
1999
Output-
12
Output-
19
DATEADD- It is used to add a certain number to a specific date that we are providing.
It takes three parameters, first parameter is in which you want a change, second is the
number to add and third is the date and time.
Syntax -If we want to add a certain number to the date. In this we want to add 10 to the
date 19 so output should be 29.
Output-
1999-12-29 13:25:42.666
DATEDIFF- It will return the difference between the two dates. It takes three
parameters, first is the parameter in which you want to change, second and third are
the two dates.
Output-
12
SUBSTRING-
Substrings are the part of the strings and we can apply them to SQL as well.
It takes three parameters, first is the parent string, second is the position from where
you want to fetch a substring and third is the length of the substring.
Syntax-
SELECT SUBSTRING(‘Campusmonk’,6,5);
Output- smonk
Note: If this is applied on a table then table name is written in place of the parent string.
ASCII- It takes the parameter of which you want the ASCII value and returns the ASCII
value of it.
Syntax-
SELECT ASCII(‘A’);
Output-
65
Note: We can directly apply it on a column name by writing column name instead of the
character provided.
CHAR- This function will give the character by taking an integer as an input.
Syntax-
SELECT CHAR(65);
Output-
CONCAT- This function is used to concatenate two strings. It can take any number of
strings as a parameter.
Syntax-
SELECT CONCAT(‘GEEKS’,’FOR’,’GEEKS’);
Output-
GEEKSFORGEEKS
DATALENGTH- It will give the length of the data that we pass in the function.
Syntax-
Output-
LEFT- This function will return the number of characters mentioned from left.
Syntax-
Output-
campus
Right- This function will return the number of characters mentioned from right.
Syntax-
Output-
onk
LOWER- This function will return all the characters in the lower case.
Syntax-
SELECT LOWER(‘CAMPUS’);
Output-
campus
UPPER- This function will return all the characters in the upper case.
SELECT UPPER(‘campus’);
Output-
CAMPUS
Syntax-
SELECT REVERSE(‘campus’);
Output-
Supmac
Example -
Note1: We can also create this by using joins but creating a view is much easier.
Note2: View has an advantage that we can put only selected columns in it which we
want to show, we don’t have to put all the columns in it.
ADVANTAGES OF VIEWS-
Simplicity- Joining two or more tables can be done using joins as well but creating a
view is much simpler.
Security- View gives us a choice to put only those columns which we want to, so every
column is not accessible by everyone providing security.
CRUD stands for create, read , update and delete. These are the operations we can
perform on a view.
Syntax-
From table_name
Where condition;
Example-
Creating a view-
CREATE VIEW [Description] AS SELECT C.C_Name, P.P_Name, P.P_ID, P.P_Price,
P.P_MAN_DATE, P.P_EXP_DATE
Reading a view-
Updating a view-
P.P_EXP_DATE, C_NO
Deleting a view-
Normalization DBMS
Database normalization is the process of organizing the attributes of the database to
reduce or eliminate data redundancy (having the same data but at different places) .
Data redundancy unnecessarily increases the size of the database as the same data is
repeated in many places. Inconsistency problems also arise during insert, delete and
update operations.
Functional Dependency
To be in second normal form, a relation must be in first normal form and relation must
not contain any partial dependency. A relation is in 2NF if it has No Partial Dependency,
i.e., no non-prime attribute (attributes which are not part of any candidate key) is
dependent on any proper subset of any candidate key of the table.
Partial Dependency – If the proper subset of candidate key determines non-prime
attribute, it is called partial dependency.
In the above relation, AB is the only candidate key and there is no partial dependency,
i.e., any proper subset of AB doesn’t determine any non-prime attribute.
X is a super key.
Transitive dependency – If A->B and B->C are two FDs then A->C is called transitive
dependency.