Dbmsss Notes
Dbmsss Notes
SQL Commands
SQL commands are instructions. It is used to communicate with the database. It is also used
to perform specific tasks, functions, and queries of data.
SQL can perform various tasks like create a table, add data to tables, drop the table, modify
the table, set permission for users.
• DROP: It is used to delete both the structure and record stored in the table.
Syntax:
DROP TABLE table_name;
Examples:
DROP TABLE EMPLOYEE;
• ALTER: This is used to alter the structure of the database. ALTER TABLE – ADD
ADD is used to add columns into the existing table. Sometimes we may require to add
additional information, in that case we do not require to create the whole database
again, ADD comes to our rescue.
Syntax:
To add a new column in the table
EXAMPLE
• TRUNCATE: This is used to remove all records from a table, including all
spaces allocated for the records are removed. TRUNCATE statement is a Data
Definition Language (DDL) operation that is used to mark the extents of a table
for deallocation (empty for reuse). The result of this operation quickly removes
all data from a table, typically bypassing a number of integrity enforcing
mechanisms. It was officially introduced in the SQL:2008 standard.
The TRUNCATE TABLE mytable statement is logically (though not physically)
equivalent to the DELETE FROM mytable statement (without a WHERE clause).
Syntax:
TRUNCATE TABLE table_name;
table_name: Name of the table to be truncated.
DATABASE name - student_data
Syntax:
1. SELECT expressions
2. FROM TABLES
3. WHERE conditions;
For example:
1. SELECT emp_name
2. FROM employee
3. WHERE age > 20;
Apart from just using the SELECT keyword individually, you can use the following
keywords with the SELECT statement:
o DISTINCT
o ORDER BY
o GROUP BY
o HAVING Clause
o INTO
Syntax
Example
The ‘ORDER BY’ statement is used to sort the required results in ascending or descending
order. The results are sorted in ascending order by default. Yet, if you wish to get the required
results in descending order, you have to use the DESC keyword.
Syntax
Example
-- Select all employees from the 'Emp table sorted by EmpNo in Descending order:
-- Select all employees from the 'Empl’ table sorted by EmpNo and EName:
/* Select all employees from the 'Emp' table sorted bsoEmpNo in Descending order and
Ename in
Ascending order: */
This ‘GROUP BY’ statement is used with the aggregate functions to group the result-set by
one or more columns.
Syntax
Example
The ‘HAVING’ clause is used in SQL because the WHERE keyword cannot be used
everywhere.
Syntax
Example
To list the number of employees in each city. The employees should be sorted high to low
and only
COUNT(EmpNo) DESC;
The ‘SELECT INTO’ statement is used to copy data from one table to another.
DML commands are used to modify the database. It is responsible for all form of changes in
the database.
The command of DML is not auto-committed that means it can't permanently save all the
changes in the database. They can be rollback.
Example:
UPDATE students
SET User_Name = 'Sonoo'
WHERE Student_Id = '3'
Updating single column: Update the column NAME and set the value to
‘PRATIK’ in all the rows where Age is 20.
UPDATE Student SET NAME = 'PRATIK' WHERE Age = 20;
For example:
Example
• REVOKE: This command withdraws the user’s access privileges given by using the
GRANT command.
Revoke command withdraw user privileges on database objects if any granted. It
does operations opposite to the Grant command. When a privilege is revoked from
a particular user U, then the privileges granted to all other users by user U will be
revoked.
Syntax:
revoke privilege_name on object_name
from {user_name | public | role_name}
Example:
grant insert,
select on accounts to Ram
By the above command user ram has granted permissions on accounts database object
like he can query or insert into accounts.
revoke insert,
select on accounts from Ram
By the above command user ram’s permissions like query or insert on accounts
database object has been removed.
List of TCL commands:
Syntax:
COMMIT;
ROLLBACK: If any error occurs with any of the SQL grouped statements, all
changes need to be aborted. The process of reversing changes is
called rollback. This command can only be used to undo transactions since the last
COMMIT or ROLLBACK command was issued.
Syntax:
ROLLBACK;
SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back
the entire transaction.
Sets a save point within a transaction. It creates points within the groups of
transactions in which to ROLLBACK. A SAVEPOINT is a point in a transaction in which
you can roll the transaction back to a certain point without rolling back the entire
transaction.
Syntax for Savepoint command:
SAVEPOINT SAVEPOINT_NAME;
This command is used only in the creation of SAVEPOINT among all the transactions.
Sample:
SAVEPOINT SP1;
//Savepoint created.
DELETE FROM Student WHERE AGE = 20;
//deleted
SAVEPOINT SP2;
//Savepoint created.
SQL Constraints
In a database table, we can add rules to a column known as constraints. These rules control
the data that can be stored in a column.
Constraint Description
NOT NULL values cannot be null
UNIQUE values cannot match any older value
PRIMARY KEY used to uniquely identify a row
FOREIGN KEY references a row in another table
CHECK validates condition for new value
DEFAULT set default value if not passed
CREATE INDEX used to speedup the read process
UNIQUE Constraint
The UNIQUE constraint in a column means that the column must have unique value. For
example,
Here, the value of the college_code column must be unique. Similarly, the value of
college_id must be unique as well as it cannot store NULL values.
The PRIMARY KEY constraint is simply a combination of NOT NULL and UNIQUE constraints. It
means that the column value is used to uniquely identify the row. For example,
Here, the value of the college_id column is a unique identifier for a row. Similarly, it cannot
store NULL value and must be UNIQUE.
In SQL, the FOREIGN KEY constraint is used to create a relationship between two tables. A
foreign key is defined using the FOREIGN KEY and REFERENCES keywords.
Example
-- this table doesn't contain foreign keys
CREATE TABLE Customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100),
age INTEGER
);
Here, the customer_id column in the Products table references the id column in the
Customers table.
Check Constraint
The CHECK constraint checks the condition before allowing values in a table. For example,
Here, the value of the amount column must be greater than or equal to 100. If not, the SQL
statement results in an error.
DEFAULT Constraint
The DEFAULT constraint is used to set the default value if we try to store NULL in a column.
For example,
If we try to store the NULL value in the college_country column, its value will be US.
The SQL Set operation is used to combine the two or more SQL SELECT statements.
• The SQL Union operation is used to combine the result of two or more SQL SELECT
queries.
• In the union operation, all the number of datatype and columns must be same in both
the tables on which UNION operation is being applied.
• The union operation eliminates the duplicate rows from its resultset.
Syntax
Example:
ID NAME
1 Jack
2 Harry
3 Jackson
ID NAME
3 Jackson
4 Stephan
5 David
ID NAME
1 Jack
2 Harry
3 Jackson
4 Stephan
5 David
2. Union All
Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.
Syntax:
ID NAME
1 Jack
2 Harry
3 Jackson
3 Jackson
4 Stephan
5 David
3. Intersect
• It is used to combine two SELECT statements. The Intersect operation returns the
common rows from both the SELECT statements.
• In the Intersect operation, the number of datatype and columns must be the same.
• It has no duplicates and it arranges the data in ascending order by default.
Syntax
Example:
ID NAME
3 Jackson
4. Minus
• It combines the result of two SELECT statements. Minus operator is used to display
the rows which are present in the first query but absent in the second query.
• It has no duplicates and data arranged in ascending order by default.
Syntax:
Example
ID NAME
1 Jack
2 Harry
JOIN
SQL Join statement is used to combine data or rows from two or more tables based on a
common field between them. Different types of Joins are as follows:
• INNER JOIN
• LEFT JOIN
• RIGHT JOIN
• FULL JOIN
• NATURAL JOIN
Student
StudentCourse
The simplest Join is INNER JOIN.
A. INNER JOIN
The INNER JOIN keyword selects all rows from both the tables as long as the condition is
satisfied. This keyword will create the result-set by combining all rows from both the tables
where the condition satisfies i.e value of the common field will be the same.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER JOIN.
This query will show the names and age of students enrolled in different courses.
B. LEFT JOIN
This join returns all the rows of the table on the left side of the join and matches rows for the
table on the right side of the join. For the rows for which there is no matching row on the
right side, the result-set will contain null. LEFT JOIN is also known as LEFT OUTER JOIN.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are the same.
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:
C. RIGHT JOIN
RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table on the right
side of the join and matching rows for the table on the left side of the join. For the rows for
which there is no matching row on the left side, the result-set will contain null. RIGHT JOIN
is also known as RIGHT OUTER JOIN.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
Note: We can also use RIGHT OUTER JOIN instead of RIGHT JOIN, both are the same.
Example Queries(RIGHT JOIN):
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:
D. FULL JOIN
FULL JOIN creates the result-set by combining results of both LEFT JOIN and RIGHT
JOIN. The result-set will contain all the rows from both tables. For the rows for which there
is no matching, the result-set will contain NULL values.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:
NAME COURSE_ID
HARSH 1
PRATIK 2
RIYANKA 2
DEEP 3
SAPTARHI 1
DHANRAJ NULL
ROHIT NULL
NIRAJ NULL
NULL 4
NULL 5
NULL 4
Count ():
Count (*): Returns total number of records .i.e. 6.
Count (salary): Return number of Non Null values over the column salary. i.e.5.
Count (Distinct Salary): Return number of distinct Non Null values over the column
salary .i.e. 4
Sum ():
Sum (salary): Sum all Non Null values of Column salary i.e., 310
sum (Distinct salary): Sum of all distinct Non-Null values i.e., 250.
Avg ():
Avg (salary) = Sum (salary) / count (salary) = 310/5
Avg (Distinct salary) = Sum (Distinct salary) / Count (Distinct Salary) = 250/4
Min ():
Min (salary): Minimum value in the salary column except NULL i.e., 40.
Max (salary): Maximum value in the salary i.e., 80.
SQL Views
o Views in SQL are considered as a virtual table. A view also contains rows and
columns.
o To create the view, we can select the pields from one or more tables present in the
database.
o A view can either have specipic rows based on certain condition or all the rows of
a table.
Sample table:
Student_Detail
1 Stephan Delhi
2 Kathrin Noida
3 David Ghaziabad
4 Alina Gurugram
Student_Marks
1 Stephan 97 19
2 Kathrin 86 21
3 David 74 18
4 Alina 90 20
5 John 96 18
1. Creating view
A view can be created using the CREATE VIEW statement. We can create a view from a
single table or multiple tables.
Syntax:
In this example, we create a View named DetailsView from the table Student_Detail
Query:
Just like table query, we can query the view to view the data.
Output:
NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad
View from multiple tables can be created by simply include multiple tables in the SELECT
statement. In the given example, a view is created named MarksView from two tables
Student_Detail and Student_Marks.
Query:
Stephan Delhi 97
Kathrin Noida 86
David Ghaziabad 74
Alina Gurugram 90
4. Deleting View
Syntax
SQL Subquery
A SQL subquery as the term suggested is a query nested within another query. These
subqueries can be present in the FROM clause, WHERE clause, or the SELECT clause.
Subqueries are a powerful tool for combining data available in two tables into a single result.
An SQL subquery is nothing but a query inside another query. We use a subquery to fetch data
from two tables. A subquery is often also referred to as an inner query, while the statement
containing a subquery is also called an outer query or outer select. We can implement
subqueries with the SELECT, INSERT, UPDATE, and DELETE statements along with the
operators like =, <, >, >=, <=, IN, BETWEEN, etc.
Now, let us implement the following SQL subquery with SELECT statement.
The following SQL query fetches the result where quantity in stock from products_bkp table
where the quantity in stock is greater than average quantity in stock
Subqueries With an INSERT statement
Consider the table ‘products_bkp’ with a similar structure to the ‘products’ table.
Now, to copy the complete ‘products’ table into the ‘products_bkp’ table, you can use the SQL
subquery with INSERT statement in the following way.
Example:
If you want to update the unit price of products_bkp table where the unit price will be greater
than the minimum unit price from the products table, we can use the following SQL query:
Example:
The following SQL query will delete the data from the products_bkp table where the unit price
is less than the maximum unit price from the table products.