Unit1 Dbms
Unit1 Dbms
Unit1 Dbms
Introduction to SQL
SQL (Structured Query Language) is used to perform operations on the records stored in
the database, such as updating records, inserting records, deleting records, creating and
modifying database tables, views, etc.
SQL is not a database system, but it is a query language.
SQL has two broad categories:
o DDL (Data Definition Language):used for defining, managing, and manipulating
the structure of a relational database. DDL statements are primarily concerned
with the creation, modification, and deletion of database objects such as tables,
indexes, views, and constraints. The data definition contains commands like
create, drop, truncate, alter and rename .
o DML(Data Manipulation Language): DML statements are used to perform
operations like retrieving, inserting, updating, and deleting data from database
tables. It contains Select, Insert, Update and Delete command
Data types are used to represent the nature of the data that can be stored in the
database table.
Data types mainly classified into three categories for every database.
1|Page
numbers, letters, and special characters. Its size can be from 0 to
65535 characters.
BINARY(Size) It is equal to CHAR() but stores binary byte strings. Its size
parameter specifies the column length in the bytes. Default is 1.
ENUM(val1, val2, It is used when a string object having only one value, chosen
val3,...) from a list of possible values. It contains 65535 values in an
ENUM list. If you insert a value that is not in the list, a blank
value will be inserted.
BIT(Size) It is used for a bit-value type. The number of bits per value is
specified in size. Its size can be 1 to 64. The default value is 1.
INT(size) It is used for the integer value. Its signed range varies from -
2147483648 to 2147483647 and unsigned range varies from 0 to
4294967295. The size parameter specifies the max display width that
is 255.
2|Page
FLOAT(p) It is used to specify a floating point number. MySQL used p
parameter to determine whether to use FLOAT or DOUBLE. If p is
between 0 to24, the data type becomes FLOAT (). If p is from 25 to
53, the data type becomes DOUBLE().
DOUBLE(size, It is a normal size floating point number. Its size parameter specifies
d) the total number of digits. The number of digits after the decimal is
specified by d parameter.
DECIMAL(size, It is used to specify a fixed point number. Its size parameter specifies
d) the total number of digits. The number of digits after the decimal
parameter is specified by d parameter. The maximum value for the
size is 65, and the default value is 10. The maximum value for d is 30,
and the default value is 0.
BOOL It is used to specify Boolean values true and false. Zero is considered
as false, and nonzero values are considered as true.
DATETIME(fsp) It is used to specify date and time combination. Its format is YYYY-
MM-DD hh:mm:ss. Its supported range is from '1000-01-01
00:00:00' to 9999-12-31 23:59:59'.
TIMESTAMP(fsp) It is used to specify the timestamp. Its value is stored as the number
of seconds since the Unix epoch('1970-01-01 00:00:00' UTC). Its
format is YYYY-MM-DD hh:mm:ss. Its supported range is from
'1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC.
TIME(fsp) It is used to specify the time format. Its format is hh:mm:ss. Its
supported range is from '-838:59:59' to '838:59:59'
3|Page
CREATE TABLE statement is used to create table in a database.
If you want to create a table, you should name the table and define its column and each
column's data type.
Syntax:
create table "tablename"
("column1" "data type",
"column2" "data type",
"column3" "data type",
...
"columnN" "data type");
Example:
create table student(name varchar(10),address varchar(50),mobn int(10));
SQL constraints are used to specify rules for the data in a table.
Constraints can be column level or table level. Column level constraints apply to a
column, and table level constraints apply to the whole table.
Constraints can be specified when the table is created with the CREATE TABLE
statement, or after the table is created with the ALTER TABLE statement.
Syntax
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
1. NOT NULL
Ensures that a column cannot have a NULL value
Example
create table employee(ename varchar(10) not null,address varchar(10) not null,
mnumber int not null);
2. UNIQUE
4|Page
The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for
a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint.
However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.
Example
create table emp2 (enamevarchar(12) not null unique , adress varchar(40) not null);
3. PRIMARY KEY
The PRIMARY KEY constraint uniquely identifies each record in a table.
Primary keys must contain UNIQUE values, and cannot contain NULL values.
Example
create table emp3(eid int not null,ename varchar(12) not null , adress varchar(40) not
null,primary key (eid));
4. FOREIGN KEY
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY
KEY in another table.
The table with the foreign key is called the child table, and the table with the primary
key is called the referenced or parent table.
Example
CREATE TABLE teacher(tid int not null, tname varchar(10), PRIMARY KEY (tid));
CREATE TABLE student ( sid int NOT NULL, sname varchar(12) NOT NULL, tid int,
PRIMARY KEY (sid),FOREIGN KEY (tid) REFERENCES teacher(tid));
5. CHECK–
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a column it will allow only certain values for this
column.
If you define a CHECK constraint on a table it can limit the values in certain columns
based on values in other columns in the row.
Example
CREATE TABLE student1 ( sid int NOT NULL, sname varchar(12) NOT NULL,age int not
null, check (age>=10));
5|Page
6. DEFAULT–
The DEFAULT constraint is used to set a default value for a column.
The default value will be added to all new records, if no other value is specified.
Example
CREATE TABLE student (sid int not null,sname varchar(12), scity varchar(12) default
"kalol");
7. CREATE INDEX
The CREATE INDEX statement is used to create indexes in tables.
Indexes are used to retrieve data from the database more quickly than otherwise. The
users cannot see the indexes, they are just used to speed up searches/queries.
Example
create index index_sname on student(sname);
Que 4: How to add Table row ?
SQL requires the use of the INSERT command to enter data into a table.
Syntax
It is possible to write the INSERT INTO statement in two ways:
sid sname
1 monali
2. If you are adding values for all the columns of the table, you do not need to
specify the column names in the SQL query. However, make sure the order of the
values is in the same order as the columns in the table. Here, the INSERT INTO
syntax would be as follows:
6|Page
Example
Que
Que 5 :Saving table changes and restoring table data or commit or rollback
command in sql
Commit
If you want to save all the commands which are executed in a transaction, then just after
completing the transaction, you have to execute the commit command.
This command will save all the commands which are executed on a table. All these
changes made to the table will be saved to the disk permanently.
STAFF
7|Pa ge
sql> COMMIT;
Output:
rollback
The rollback command is used to get back to the previous permanent status of the
table, which is saved by the commit command.
Suppose, we have started editing a table and later thought that the changes that we
have recently carried out on a table are not required. Then, in that case, we can roll back
our transaction, which simply means to get back to the previous permanent status of
the table, which is saved by the commit command.
Example:
COMMIT ROLLBACK
1. COMMIT permanently saves the ROLLBACK undo the changes made by the
8|Pa ge
COMMIT ROLLBACK
9|Page
Que 7:How to update rows in table?
The UPDATE statement in SQL is used to update the data of an existing table in
the database.
We can update single columns as well as multiple columns using the UPDATE
statement as per our requirement.
Syntax
Example
Output
Que 8:How to delete table row? Or how to delete records from table?
10 | P a g e
Syntax
1. Conditional Operators
2. Arithmetic Operators
3. Logical Operators
4. Special Operators
The SQL reserved words and characters are called operators, which are used with a
WHERE clause in a SQL query. In SQL, an operator can either be a unary or binary
operator. The unary operator uses only one operand for performing the unary
operation, whereas the binary operator uses two operands for performing the binary
operation.You can select partial table contents by placing restrictions on the rows to be
included in the output.
This is done by using the WHERE clause to add conditional restrictions to the SELECT
statement.
Numerous conditional restrictions can be placed on the selected table contents. For
example, the comparison
operators shown in following Table can be used to restrict output.
11 | P a g e
The following syntax enables you to specify which rows to select:
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example:
SID SNAME SCITY
1 TULSI AMDAVAD
2 JANVI AMDAVAD
3 HIRAL KALOL
4 MONALI MEHSANA
5 SUCHITA KADI
12 | P a g e
1. SQL Addition Operator (+)
The SQL Addition Operator performs the addition on the numerical columns in the
table.
If you want to add the values of two numerical columns in the table, then you have to
specify both columns as the first and second operand.
You can also add the new integer value in the value of the integer column.
The syntax for using the WHERE clause with the addition operator is given
below:
Example
13 | P a g e
SELECT Emp_Salary + Emp_Bonus AS Emp_Total_Salary FROM Employee;
The following query performs the addition operation on the above Employee table
with the WHERE clause:
SELECT Emp_Salary + Emp_Bonus AS Emp_Total_Salary FROM Employee WHERE
Emp_Salary> 25000;
14 | P a g e
Syntax of SQL Subtraction Operator:
The following query performs the subtraction operation on the above Employee
table with the WHERE clause:
15 | P a g e
3. SQL Multiplication Operator (*)
The SQL Multiplication Operator performs the multiplication on the numerical
columns in the table.
If you want to multiply the values of two numerical columns, then you have to
specify both columns as the first and second operand.
You can also multiply the integer value with the values of an integer column.
The syntax for using the WHERE clause with the multiplication operator is given
below:
SELECT Column_Name_1 Multilplication_Operator Column_Name2 FROM Table_Name
WHERE Condition;
Example
16 | P a g e
SELECT Car_Amount * Car_Price AS Car_Total_Price FROM Cars;
17 | P a g e
Division Operator with WHERE Clause
The SQL division operator can also be used with the WHERE clause in the SELECT
query.
The syntax for using the WHERE clause with the division operator is given below:
Example
18 | P a g e
Que 10: Explain select query with Logical Operators.
The Logical Operators in SQL perform the Boolean operations, which give two
results True and False. These operators provide True value if both operands match the
logical condition.
Following are the various logical operators which are performed on the data
stored in the SQL database tables:
The ALL operator in SQL compares the specified value to all the values of a column from
the sub-query in the SQL database.
SELECT,
HAVING, and
WHERE.
Example
19 | P a g e
SELECT Emp_Id, Emp_Name FROM Employee_details WHERE Emp_Salary > ALL ( SELECT Emp_Sa
lary FROM Employee_details WHERE Emp_City = Jaipur)
The AND operator in SQL would show the record from the database table if all the
conditions separated by the AND operator evaluated to True. It is also known as the
conjunctive operator and is used with the WHERE clause.
SELECT column1, ...., columnN FROM table_Name WHERE condition1 AND condition2
AND condition3AND ....... AND conditionN;
Example
20 | P a g e
Suppose, we want to access all the records of those employees from the
Employee_details table whose salary is 25000 and the city is Delhi. For this, we
have to write the following query in SQL:
Here,SQL AND operator with WHERE clause shows the record of employees whose
salary is 25000 and the city is Delhi.
3. SQL OR Operator
The OR operator in SQL shows the record from the table if any of the conditions
separated by the OR operator evaluates to True. It is also known as the conjunctive
operator and is used with the WHERE clause.
Syntax of OR operator:
Example
The NOT operator in SQL shows the record from the table if the condition evaluates to
false. It is always used with the WHERE clause.
Syntax of NOT operator:
SELECT column1, column2 ...., columnN FROM table_Name WHERE NOT condition;
Example
Suppose, we want to show all the information of those employees from
the Employee_details table whose Cityis not Delhi and Chandigarh. For this, we have to
write the following query in SQL:
SELECT * FROM Employee_details WHERE NOT Emp_City = 'Delhi' AND NOT Emp_City =
'Chandigarh';
21 | P a g e
The ANY operator in SQL shows the records when any of the values returned by the
sub-query meet the condition.
The ANY logical operator must match at least one record in the inner query and must be
preceded by any SQL comparison operator.
SELECT column1, column2 ...., columnN FROM table_Name WHERE column_name comp
arison_operator ANY ( SELECT column_name FROM table_name WHERE condition(s)) ;
Example
The following SQL statement lists the ProductName if it finds ANY records in the
OrderDetails table has Quantity equal to 10 (this will return TRUE because the Quantity
column has some values of 10):
1. Between Operator
2. Is Null Operator
3. Like Operator
4. In Operator
5. Exists Operator
1. Between Operator
The BETWEEN operator in SQL shows the record within the range mentioned in the SQL
query. This operator operates on the numbers, characters, and date/time operands.
If there is no value in the given range, then this operator shows NULL value.
22 | P a g e
2. Is Null Operator
IS NULL operator is used to test for a NULL value.
Syntax
SELECT [column_name1,column_name2 ]FROM [table_name]WHERE [column_name] IS
[NOT] NULL;
Example
To get data of all columns from the 'listofitem' table with following condition -
3. Like Operator
Syntax of Like operator
SELECT column_Name1, column_Name2 ...., column_NameN FROM table_Name WHERE colum
n_name LIKE pattern;
Example
If we want to show all the information of those employees from the Employee_details whose
name starts with ''s''. For this, we have to write the following query in SQL:
SELECT * FROM Employee_details WHERE Emp_Name LIKE 's%' ;
4. In Operator
The IN operator in SQL allows database users to specify two or more values in a WHERE
clause. This logical operator minimizes the requirement of multiple OR conditions.
This operator makes the query easier to learn and understand. This operator returns those
rows whose values match with any value of the given list.
23 | P a g e
Syntax of IN operator:
5. Exists Operator
The EXISTS operator is used to test for the existence of any record in a subquery.
The EXISTS operator returns TRUE if the subquery returns one or more records.
Syntax
Example
SELECT fname, lname FROM Customers WHERE EXISTS (SELECT * FROM Orders
WHERE Customers.customer_id = Orders.c_id);
The ALTER TABLE statement in Structured Query Language allows you to add, modify,
and delete columns of an existing table.
This statement also allows database users to add and remove various SQL constraints on
the existing tables.Any user can also change the name of the table using this statement.
In many situations, you may require to add the columns in the existing table. Instead of
creating a whole table or database again you can easily add single and multiple columns
using the ADD keyword.
Syntax
24 | P a g e
ALTER TABLE table_name ADD column_name column-definition;
Example
To delete a column in a table, use the following syntax (notice that some
database systems don't allow deleting a column):
Syntax
Example
Syntax
Example
To change the data type of a column in a table, use the following syntax:
Example
25 | P a g e
If the column to be changed already contains data, you can make changes in the
column’s characteristics if thosechanges do not alter the data type.
For example, if you want to increase the width of the P_PRICE column to 9 digits, use the
command:
Example
Example:
CREATE: This command is used to create the database or its objects (like table, index, function,
views, store procedure, and triggers).
26 | P a g e
If you want to create a table, you should name the table and define its column and each
column's data type.
Syntax:
create table "tablename"
("column1" "data type",
"column2" "data type",
"column3" "data type",
...
"columnN" "data type");
Example:
create table student(name varchar(10),address varchar(50),mobn int(10));
TRUNCATE: This is used to remove all records from a table, including all spaces allocated for
the records are removed. The major difference between TRUNCATE and DROP is that truncate
is used to delete the data inside the table not the whole table.
Syntax
TRUNCATE TABLE table_name;
Example:
To truncate the Student_details table from the student_data database.
Query:
TRUNCATE TABLE Student_details;
COMMENT: This is used to add comments to the data dictionary.
Comments can be written in the following three formats:
Single-line comments
Comments starting and ending in a single line are considered single-line comments. A line
starting with ‘–‘ is a comment and will not be executed.
Example
SELECT * FROM customers;
-- This is a comment that explains
27 | P a g e
the purpose of the query.
Multi-line comments
Comments starting in one line and ending in different lines are considered as multi-line
comments.
A line starting with ‘/*’ is considered as starting point of the comment and is terminated
when ‘*/’ is encountered.
Example
/*
This is a multi-line comment that explains
the purpose of the query below.
The query selects all the orders from the orders
table that were placed in the year 2022.
*/
SELECT * FROM orders WHERE YEAR(order_date) = 2022;
In-line comments
In-line comments are an extension of multi-line comments, comments can be stated in
between the statements and are enclosed in between ‘/*’ and ‘*/’.
Example
SELECT * FROM /* Customers; */
RENAME: Sometimes we may want to rename our table to give it a more relevant name. For
this purpose, we can use ALTER TABLE to rename the name of the table.
DQL statements are used for performing queries on the data within schema objects.
The purpose of the DQL Command is to get some schema relation based on the query
passed to it.
We can define DQL as follows it is a component of SQL statement that allows getting data
from the database and imposing order upon it. It includes the SELECT statement.
List of DQL:
SELECT: It is used to retrieve data from the database.
28 | P a g e
It is the component of the SQL statement that controls access to data and to the
database. Basically, DCL statements are grouped with DML statements.
List of DML commands:
1) Insert Command
• The INSERT INTO statement is used to insert new records in a table.
It is possible to write the INSERT INTO statement in two ways:
1) Specify both the column names and the values to be inserted:
Syntax:
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2,
value3, ...);
Example: INSERT INTO Person (id,name,age) VALUES (1,’mira’,30);
2) If you are adding values for all the columns of the table, you do not need to
specifythe column names in the SQL query. However, make sure the order of the
values is in the same order as the columns in the table. Here, the INSERT INTO
Syntax:
INSERT INTO table_name VALUES (value1, value2, value3, ...);
Example:
INSERT INTO Person VALUES (1,’dixita’,30);
2) Update Command
• The UPDATE statement is used to modify the existing records in a table.
Syntax:
UPDATE table_name SET column1 = value1, column2 = value2 WHERE condition;
Example:
UPDATE Customers SET ContactName = 'Alfred' WHERE CustomerID = 1;
3) Delete Command
• The DELETE statement is used to delete existing records in a table.
Syntax:
DELETE FROM table_name WHERE condition;
Example:
29 | P a g e
DELETE FROM Customers WHERE CustomerID = 1;
4) Select Command
• The SELECT statement is used to select data from a database.
Syntax:
SELECT column1, column2, FROM table_name;
Here, column1, column2, are the field names of the table you want to select data from. If
you want to select all the fields available in the table, use the following syntax:
SELECT * FROM table_name;
Example:
SELECT * FROM Person;
Syntax:
SELECT DISTINCT column1, column2,FROM table_name;
Example:
SELECT DISTINCT Country FROM Customers;
2. SELECT with WHERE Clause
• The WHERE clause is used to filter records.
• The WHERE clause is used to extract only those records that fulfill a specified
condition.
Syntax:
SELECT column1, column2, FROM table_name WHERE condition;
30 | P a g e
Example:
SELECT * FROM Customers WHERE Country='Mexico';
3. SELECT with ORDER BY Keyword
• The ORDER BY keyword is used to sort the result-set in ascending or descending
order.
• The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword.
Syntax:
SELECT column1, column2, FROM table_name ORDER BY column1, column2, ASC|DESC;
Example:
SELECT * FROM Customers ORDER BY Country DESC;
4. SELECT with Group by Clause
• The GROUP BY statement groups rows that have the same values into summary rows
like "find the number of customers in each country".
• The GROUP BY statement is often used with aggregate functions (COUNT (), MAX (),
MIN (), SUM (), AVG ()) to group the result-set by one or more columns.
Syntax:
SELECT column_name(s) FROM table_name WHERE condition GROUP BY
column_name(s) ORDER BY column_name(s);
Example:
SELECT COUNT (CustomerID), Country FROM Customers GROUP BY Country;
Output:
31 | P a g e
5. SELECT with Having Clause
• The HAVING clause was added to SQL because the WHERE keyword cannot be
used with aggregate functions.
Syntax:
SELECT expression1, expression2,expression_n,aggregate_function
(aggregate_expression) FROM tables WHERE conditions GROUP BY expression1,
expression2, ... expression_n HAVING having_condition; ORDER BY column_name(s);
• expression1, expression2, expression_n: It specifies the expressions that are
not encapsulated within aggregate function. These expressions must be included
in GROUP BY clause.
• aggregate_function: It specifies the aggregate functions i.e. SUM, COUNT, MIN,
MAX or AVG functions.
• aggregate_expression: It specifies the column or expression on that the aggregate
function is based on.
• tables: It specifies the table from where you want to retrieve records.
• conditions: It specifies the conditions that must be fulfilled for the record to be
selected.
• having_conditions: It specifies the conditions that are applied only to the
aggregated results to restrict the groups of returned rows.
Example
Table Name: sales_department
32 | P a g e
Example:
SELECT item, SUM(sale) FROM salesdepartment GROUP BY item HAVING SUM(sale) <
1000;
Output:
REVOKE: This command withdraws the user’s access privileges given by using the
GRANT command.
Syntax:
33 | P a g e
REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;
SAVEPOINT SAVEPOINT_NAME;
34 | P a g e