11 SQL
11 SQL
✓ DML commands are used to modify the database. It is responsible for all changes in
the database.
✓ DML is of two types:
Procedural DMLs require a user to specify what data is needed and how to get it.
1
Non-Procedural DMLs require a user to specify what data is needed without
specifying how to get it.
The commonly used commands of DML are
• SELECT – To retrieve data from the table
• INSERT – To insert new tuple/row in the table
• UPDATE – To update existing tuple/row from the table
• DELETE – To delete existing tuple/row from the table
DDL DML
DDL stands for Data Definition Language. DML stands for Data Manipulation Language.
It is used to create databases, schemas, It is used to select, insert, update or delete the
constraints, users, tables etc. records.
DDL has no further classification. DML is further classified into procedural DML
and non-procedural DML
Basic commands present in DDL are CREATE, Basic commands present in DML are INSERT,
DROP, RENAME ,ALTER etc SELECT, UPDATE ,DELETE etc
2
1. Date and time values are always in the format YYYY-MM-DD HH:MM:SS
2. Enclose character datatype values in single or double quotation marks
show tables;
5. Display the name of the current database.
select database();
6. To create a new table in a database.
create table table_name( column1 datatype[(size)] [constraint] ,column2
datatype[(Size)] [constraint] ,....);
3
mysql>create table student (rollno int primary key, sname VARCHAR(20) not null,
rank int(2));
A constraint is a condition or check applicable to a field or set of fields. These can
be specified at the time of creating the table. They are used to ensure the integrity
of a relation, hence named as integrity constraints. Types: Column constraint and
Table constraint.
• NOT NULL Constraint It ensures that a column cannot store a NULL value.
• UNIQUE Constraint It is used to uniquely identify each record in a
database.
• PRIMARY KEY Constraint uniquely identifies each record in a table. The
primary key cannot contain NULL values. A table can have only one primary
key.
• FOREIGN KEY Constraint It is a column or combination of columns as a
foreign key and establishes its relationship with a primary key in different
tables.
• CHECK KEY Constraint It is used to limit the range of values for that
column.
• DEFAULT Constraint It is used to set the default value for a column.
4
mysql>insert into student values (10,'sumitha',5);
9. Select data from table using Select statement
1. Selecting/displaying the entire data from the table
SELECT * From tablename;
mysql>select * from student;
[Link] nulls: The IFNULL() function returns a specified value if the expression is
NULL.
mysql>SELECT IFNULL(mark, “absent”) from student;
5
Not in operator makes sure that the expression proceeded does not have any of the
values present in the arguments.
mysql> select * from student where dept not in(‘mat-cs’,’bio-cs’);
12. Searching for NULL
NULL (absence of value) cannot be compared using the relational operator. It is not
possible to test for NULL values with comparison operators such as =, <, or <>.
Between operator selects values within a given range. The values can be
numbers, text, or dates. Both the lower value and the upper value are inclusive
mysql> select * from student where mark between 90 and 100;
6
1. Adding new column to the exiting table
4. Renaming a column
7. Order of Columns
7
18. Drop database command is used to remove an existing database.
drop database<databasename>;
mysql>drop database eg;
The above command will generate an error, if database already exists. To avoid
this error, the following command can be used:
mysql>drop database if exists mydb;
▪ Relational Operator
= Equal to > Greater than <Lesser than >=Greater than equal to
<=Lesser than equal to <> or != Not Equal to
▪ Logical Operator
The Logical operator[AND OR NOT] is used to combine two or more logical
expressions.
MYSQL Functions:
-----------------------------------------------------------------------------------------------
A function is a special type of predefined command set that performs some operation and
returns a single value.
Single row Functions : String functions, Numeric functions & Date functions.
Multiple row Functions: Aggregate functions.
String Functions:
Function Description Example
UCASE(string) Converts a string into mysql> select ucase("hello");
OR uppercase. ----------------
UPPER(string) ucase("hello")
----------------
HELLO
LCASE(string) Converts a string into mysql> select ucase("hello");
OR lowercase. ----------------
LOWER(string) ucase("hello")
----------------
HELLO
MID(string, pos, n) Returns a substring of mysql> select mid("computer",3,4);
OR size n starting from the ---------------------
SUBSTRING(string, specified position (pos) mid("computer",3,4)
of the string. If n is not
pos, n) ---------------------
specified, it returns the
OR mput
substring from the
SUBSTR(string, pos, n) position pos until the mysql> select mid("computer",5);
end of the string. -------------------
mid("computer",5)
-------------------
uter
8
LENGTH(string) Return the number of mysql> select length("computer");
characters in the --------------------
specified string. length("computer")
--------------------
8
Numeric Functions:
Function Description Example
POWER(X,Y) Calculates X to the mysql> select power(5,2);
power of Y. power(5,2)
POW(X,Y) --------------
25
11
--------------
11
mysql> select month('2023-11-26');
--------------------
month('2022-11-26')
--------------------
11
Aggregate Functions
Note:
13
Differentiate between WHERE clause and HAVING clause
WHERE Clause HAVING Clause
WHERE Clause is used to filter the records HAVING Clause is used to filter record from
from the table based on the specified the groups based on the specified
condition. condition.
Can be used without GROUP BY Clause Cannot be used without GROUP BY Clause
WHERE Clause is used before GROUP BY HAVING Clause is used after GROUP BY
Clause Clause
Used with single row operations such as Applicable with multiple row functions such
Upper, Lower and so on as Sum, count and so on
SYNTAX:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
14
mysql>select dept, count(*) from student group by dept;
mysql> select dept,count(*) from student group by dept order by dept desc;
15
Note :
A non – group field is the field that has different values in the rows belonging to
that group. In this case, it will return the value from the first record of the group from that
non – group field.
Having clause:
• The HAVING clause is used with GROUP BY clause to place condition because the
WHERE keyword could not be used with aggregate functions.
• If you omit the GROUP BY clause, the HAVING clause behaves like the WHERE
clause.
SYNTAX:
SELECT column(s) FROM table_name WHERE condition GROUP BY column1,
HAVING condition;
Joins
✓ A JOIN clause is used to combine rows from two or more tables, based on a related
column between them.
✓ In a join query, more than one tables are listed in FROM clause.
✓ The SQL Join condition is always used in the WHERE clause of SELECT, UPDATE and
DELETE statements.
✓ When two or more tables have a column with the same name, the name can be
accessed by using the table name combined with the period (.) in referring to the
column. Eg: [Link]
16
SELECT * FROM CUSTOMERS, CONTACTS;
Equi Join
The join, in which the columns are compared for equality (=). Results of Equi joins
are the same as simple joins or inner joins.
e.g. To join two tables PERSON and ORDERS using a P_Id column (common column)
MySQL>SELECT Last_Name, First_Name, Order_No FROM PERSON, ORDERS WHERE
PERSON.P_Id=ORDERS.P_Id ORDER BY PERSON.Last_Name;
17
NON EQUI JOIN :
NON EQUI JOIN performs a JOIN using comparison operator other than equal(=)
sign like >, <, >=, <= with conditions.
Natural Join
• Natural join is an SQL join operation that creates a join on the base of the
common columns in the tables
• The join in which only one of the identical columns exists is called a natural join.
• The natural join is a type of equi join and is structured in such a way that columns
with the same name as associated tables will appear only once.
SELECT * FROM EMPLOYEE;
18
Table aliases
It is a temporary label given along with the table name in FROM clause.
19