0% found this document useful (0 votes)
66 views

All in One Mysql Notes

Uploaded by

hod.it
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views

All in One Mysql Notes

Uploaded by

hod.it
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 24

DBMS concepts and SQL

Database
o A collection of interrelated data stored together to serve multiple applications.
Purpose of DBMS
 Database Management System is a software that is responsible for storing,
maintaining, and utilizing databases.
 Reduces data redundancy ( Duplication of data)
 Control data inconsistency to a large extent. When redundancy is not controlled, there
may be occasions on which 2 entries of same data not been agreed. This is called
inconsistent. If redundancy retained for some technical purpose then when there is a
change in one duplicate value the other one also will get changed. This concept is
called propagating updates.
 Facilitates sharing of data.
 Enforce standards.
 Ensures data security
 Integrity maintained through databases.(Conditions or rules)
o Different users
 End user
 Application system analyst
 Physical storage system analyst
o Database Abstraction
 A good DBMS system ensures easy smooth and efficient data structures .Should
be easy to access for all the 3 users.
o Various levels of database implementation
 Internal level (physical level): How the data is stored in the storage medium.
 Conceptual level : It describes what data are actually stored in the database. It also
describes the relationships existing among data. In this the database is described in
terms of simple data structures.
 External view (view level) : In this the data is viewed by individual users. Most of the
users are not concerned with all information in the database.
o Different data models
 Relational data model
 Hierarchical data model
 Network data model
o Relational data model
 In this the data are organized into tables.
 The rows are called tuples and the columns are called attributes.
 A row in a table represents relationship among set of values.
 The relational data model is based on collection of tables.
 The user in this type can edit , delete , add tuples.
o Network data model
 In this the collection of records are connected with each other by means of links.
 The link is association between 2 records.
 In network model we can do operations link find , insert , delete , modify etc.,
o The hierarchical data model
 In this model the records are organized as trees.
 The relationship is parent child relationship.
 The operations in this model performed by DML(Data Manipulation Language)

1
Domain
 A domain is a pool of values from which the actual values appearing in a given
column are drawn.
 Tuple: The rows of relation are called tuple.
 Attributes: The columns of a relation table is called attributes.
 Degree: The number of attributes in a relation is called DEGREE.
 Cardinality : The number of rows in a relation is called cardinality.
View
 A view is a table that does not really exist in its own right but is instead derived from
one or more underlying base tables.
Keys
o Primary Key : A primary key is a set of one or more attributes that can uniquely
identify tuples within the relation
o Candidate Keys : All attribute combinations inside a relation that can serve as
primary key are candidate keys as they are candidates for the primary key
position.
o Alternate Key : A candidate key that is not the primary key is called alternate key.
Candidate Key:
A candidate key is a set of attributes (or attribute) which uniquely identify the tuples
in relation or table. As we know that Primary key is a minimal super key, so there is
one and only one primary key in any relationship but there is more than one
candidate key can take place. Candidate key’s attributes can contain a NULL value
which opposes to the primary key. For example,
Student{ID, First_name, Last_name, Age}
Here we can see the two candidate keys ID and {First_name, Last_name, DOB}.
So here, there are present more than one candidate keys, which can uniquely
identify a tuple in a relation.

ALTERNATE KEYS is a column or group of columns in a table that uniquely


identify every row in that table. A table can have multiple choices for a primary key
but only one can be set as the primary key. All the keys which are not primary key
are called an Alternate Key.
Example:
In this table, StudID, Roll No, Email are qualified to become a primary key. But
since StudID is the primary key, Roll No, Email becomes the alternative key.

StudID Roll No First Name LastName Email


1 11 Tom Price [email protected]

2 12 Nick Wright [email protected]

3 13 Dana Natan [email protected]

What is a Candidate Key?


CANDIDATE KEY is a set of attributes that uniquely identify tuples in a table.
Candidate Key is a super key with no repeated attributes. The Primary key should
be selected from the candidate keys. Every table must have at least a single
candidate key. A table can have multiple candidate keys but only a single primary
2
key.

o Foreign Key : A non-key attribute whose values are derived from the primary key
of some other table, is known as foreign key in its current table.
o Referential Integrity
It is a system of rules that a DBMS uses to ensure that relationships between records in
related tables are valid, and that users don’t accidentally delete or change related data.

Relational Database
A relational database is a collection of data items organized as logically related tables.
Relational Database Management System
The software required to handle/manipulate these table/relations is know as Relational Database
Management System (RDBMS). Example - Oracle , Sybase, DB2, MSSQL, etc.
Table/Relation
A group of rows and columns from a table. The horizontal subset of the Table is known as a
Row/Tuple. The vertical subset of the Table is known as a Column/an Attribute.
A relation in a database has the following characteristics:
 Every value in a relation is a atomic-i.e. it can not be further divided
 Names of columns are distinct and order of columns is immaterial
 The rows in the relation are not ordered
Relational algebra
Relational algebra is a formal system for manipulating relations. Set of operations that can be
carried out on a relation:
 Selection : To select a horizontal subset of a relation
 Projection : To select vertical subset of a relation
 Cartesian Product: It operates on two relations and is denoted by X. for example
Cartesian product of two relation R1 and R2 is represented by R=R1X R2. The degree
of R is equal to sum of degrees of R1 and R2. The cardinality of R is product of
cardinality of R1 and cardinality of R2
Example cartesian Product
The table R1
Empno Ename Dept
1 Bill A
2 Sarah C
3
3 John A
The table R2
Dno Dname
A Marketing
B Sales
C Legal
R1 X R2
Empno Ename Dept Dno Dname
1 Bill A A Marketing
1 Bill A B Sales
1 Bill A C Legal
2 Sarah C A Marketing
2 Sarah C B Sales
2 Sarah C C Legal
3 John A A Marketing
3 John A B Sales
3 John A C Legal

SQL- Structured Query Language


SQL commands classified by function:
Data definition language (DDL) - used to define or change database structure(s)
(e.g., CREATE, ALTER, DROP)
Data manipulation language (DML) - used to select or change data (e.g., INSERT, UPDATE,
DELETE, SELECT)

Creating a new table in the database


Syntax :
CREATE TABLE table_name
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
);
Example :
CREATE TABLE student (rno int,name char(25), fees int, dob date, class char(3));
Inserting a new row at the bottom of the table
Syntax :
INSERT INTO table_name VALUES (value1,value2,value3,...);
You can also specifies both the column names and the values to be
inserted: INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
Examples
4
INSERT INTO student VALUES(10, 'Alex', 7800, '1998-10-03','K12');
INSERT INTO student(rno, name, fees, dob, class)
values(11, 'Peter', 6700, '1997-11-15', 'K12');
Displaying the content from a table – SELECT
Example :
SELECT * FROM student;
rno name fees dob class
10 Alex 7800 1998-10-03 K12
11 Peter 6700 1997-11-15 K12
12 Alisha 7800 1999-07-03 K11
13 John 6900 2000-12-13 K11
SELECT name FROM student;
name
Alex
Peter
Alisha
John
Relational Operator
=, <, >, <=, >=, <>
Logical Operator
AND, OR, NOT
SELECT * FROM student WHERE fees < 7000;
rno name fees dob class
11 Peter 6700 1997-11-15 K12
13 John 6900 2000-12-13 K11

SELECT * FROM student WHERE fess > 7000 AND fees < 8000;
rno name fees dob class
10 Alex 7800 1998-10-03 K12
12 Alisha 7800 1999-07-03 K11

SELECT * FROM student WHERE fees > 7000 OR class = 'K12';


rno name fees dob class
10 Alex 7800 1998-10-03 K12
11 Peter 6700 1997-11-15 K12

5
12 Alisha 7800 1999-07-03 K11

SELECT name, fees FROM student WHERE NOT (class = 'K12');


name fees
Alisha 7800
John 6900

SELECT name, fees FROM student WHERE class <> 'K12';


name fees
Alisha 7800
John 6900

SELECT * FROM student WHERE rno IN(10, 12, 13);


rno name fees dob class
10 Alex 7800 1998-10-03 K12
12 Alisha 7800 1999-07-03 K11
13 John 6900 2000-12-13 K11

SELECT * FROM student WHERE rno BETWEEN 11 AND 13;


rno name fees dob class
11 Peter 6700 1997-11-15 K12
12 Alisha 7800 1999-07-03 K11
13 John 6900 2000-12-13 K11

SELECT name FROM student WHERE name LIKE 'A%';


name
Alex
Alisha

SELECT * name FROM student WHERE name LIKE '%a';


rno name fees dob class
12 Alisha 7800 1999-07-03 K11

SELECT name FROM student WHERE Name LIKE '%e%' ;

6
name
Alex
Peter

Modifying the existing content of the table


Syntax:
UPDATE table_name SET column1=value1,column2=value2,... WHERE
some_column=some_value; Example
UPDATE student SET fees = '7900' WHERE rno = 12 ;
SELECT * FROM student;
rno name fees dob class
10 Alex 7800 1998-10-03 K12
11 Peter 6700 1997-11-15 K12
12 Alisha 7900 1999-07-03 K11
13 John 6900 2000-12-13 K11
Arranging the data in ascending or descending order of one/multiple columns (ORDER BY
clause)
Syntax:
SELECT column_name,column_name
FROM table_name
ORDER BY column_name,column_name ASC|DESC;
Example
SELECT * FROM student ORDER BY name;
rno name fees dob class
10 Alex 7800 1998-10-03 K12
12 Alisha 7900 1999-07-03 K11
13 John 6900 2000-12-13 K11
11 Peter 6700 1997-11-15 K12

SELECT * FROM student ORDER BY fees DESC;

rno name fees dob class


12 Alisha 7900 1999-07-03 K11
10 Alex 7800 1998-10-03 K12
13 John 6900 2000-12-13 K11
11 Peter 6700 1997-11-15 K12

7
SELECT class, name, dob, fees FROM student ORDER BY class, name DESC;
class name dob fees
K11 John 2000-12-13 6900
K11 Alisha 1999-07-03 7900
K12 Peter 1997-11-15 6700
K12 Alex 1998-10-03 7800

SELECT class, name, fees, fees*12 annualfees FROM student;


class name fees annualfees
K12 Alex 7800 93600
K12 Peter 6700 80400
K11 Alisha 7900 94800
K11 John 6900 82800
Using Aggregate Functions with SELECT COUNT( )
To count the number of rows
SUM( ) To find the sum of values in the column MAX( )
To find the maximum value in the column MIN( ) To find
the minimum value in the column AVG( ) To find the
average of values in the column SELECT COUNT(*)
FROM student;
COUNT(*)
4

SELECT COUNT(rno) FROM student;

COUNT(rno)
4

SELECT SUM(fees) FROM student;

SUM(fees)
29300

SELECT AVG(fees) FROM student;

8
AVG(fees)
7325.000
0

SELECT MAX(fees), MIN(fees) FROM student;


MAX(fees) MIN(fees)
7900 6700
Grouping data under given Column- (GROUP BY)
SELECT class, SUM(fees) FROM student GROUP BY class;
class SUM(fees)
K11 14800
K12 14500
SELECT class, MAX(fees), MIN(fees) FROM student GROUP BY class;
class MAX(fees) MIN(fees)
K11 7900 6900
K12 7800 6700

SELECT class, MAX(dob) FROM student GROUP BY class HAVING COUNT(*)>1;


class MAX(dob)
K11 2000-12-13
K12 1998-10-03
Deleting a row/rows from a table
Syntax:
DELETE FROM table_name WHERE some_column=some_value;
Example:
DELETE FROM Student WHERE rno = 13;

Adding a new column(s) in the table


Syntax :
ALTER TABLE table_name
ADD column_name datatype

Examples :
ALTER TABLE student ADD (grade CHAR(2));

Modifying the data type of a column


Syntax;
ALTER TABLE table_name MODIFY
column_name datatype Example:
ALTER TABLE student MODIFY (grade CHAR(1));
9
Deleting a table
Syntax:
DROP TABLE table_name
Example:
DROP TABLE student;
Working with more than one table
Syntax:
SELECT col1, col2, col3...
FROM table_name1, table_name2
WHERE table_name1.col2 = table_name2.col1;
Table - product
product_id product_name supplier_name unit_price
100 Camera Nikon 300
101 Television Onida 100
102 Refrigerator Videocon 150
103 Ipod Apple 75
104 Mobile Nokia 50
Table - order_items
order_id product_id total_units customer
5100 104 30 Infosys
5101 102 5 Satyam
5102 103 25 Wipro
5103 101 10 TCS
SELECT order_id, product_name, unit_price, supplier_name, total_units FROM
product, order_items
WHERE order_items.product_id = product.product_id;

ALTER COMMANDS
DROP DATABASE testDB;

DROP TABLE table1;

DROP TABLE IF EXISTS table1;

DROP TABLE IF EXISTS table1, table2, table3;

ALTER TABLE Customers


ADD Email varchar(255);

ALTER TABLE Customers

10
DROP COLUMN Email;

ALTER TABLE Persons


ADD DateOfBirth date;

ALTER TABLE Persons


MODIFY COLUMN DateOfBirth year;

ALTER TABLE Persons


DROP COLUMN DateOfBirth;

ALTER TABLE contacts


DROP COLUMN contact_type;
Suppose we want to

1. Change the field name from “full_names” to “fullname


2. Change it to char data type with a width of 250
3. Add a NOT NULL constraint

We can accomplish this using the change command as follows –

ALTER TABLE `members` CHANGE COLUMN `full_names` `fullname` char(250) NOT NULL;
MODIFY KEYWORD
The MODIFY Keyword allows you to

1. Modify Column Data Type


2. Modify Column Constraints

The script below changes the width of “fullname” field from 250 to 50.

ALTER TABLE `members`MODIFY `fullname` char(50) NOT NULL;

to change our employees table to “users,”

ALTER TABLE employees RENAME users;

ALTER TABLE Persons


ADD PRIMARY KEY (ID);
ALTER TABLE Persons
ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName);

ALTER TABLE Persons


DROP PRIMARY KEY;

ALTER TABLE Persons


ADD UNIQUE (ID);

11
ALTER TABLE Persons
DROP INDEX UC_Person;

ALTER TABLE Persons


MODIFY Age int NOT NULL;

ALTER TABLE testTable ALTER COLUMN colA DROP NOT NULL;

ALTER TABLE Persons


ALTER City SET DEFAULT 'Sandnes';

ALTER TABLE Persons


ALTER City DROP DEFAULT;

ALTER TABLE Persons


ADD CHECK (Age>=18);

ALTER TABLE Persons


ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');

ALTER TABLE Persons


DROP CHECK CHK_PersonAge;

ALTER TABLE Orders


ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

ALTER TABLE Orders


DROP FOREIGN KEY FK_PersonOrder;

A Constraint is a condition or check applicable on a field or set of fields.


Data constraints are the rules that are defined when a table is created.
They can also be defined or modified after creating the tables.When constraints are defined any
data entering in the table is first checked to satisfy conditions the specified in particular
constraint if it is, only then table data can be updated.

When a constraint is applied to a single column, it is called a column level constraint but if a
constraint is applied on a combination of columns it is called a table constraint.

Following constraints can be defined on a table in SQL:

Constraint name Description


PRIMARY KEY to create a primary key
UNIQUE to create a unique key
NOT NULL to define that column will not accept null values
FOREIGNKEY/ REFERENCES to define referential integrity with another table.
12
DEFAUT to define the columns default value.
CHECK to define the custom rule

Joins

SELECT name,stream FROM stu1 JOIN stud2 where stud1.sno = stud2.roll;


SELECT * FROM stud2 natural JOIN stu3 where stud2.roll = stu3.roll;
SELECT name,stream FROM stu1 natural JOIN stud2 where stud1.sno = stud2.roll;

Equi Join Natural Join

Equi Join is a join having a condition where we use an While performing a natural join, we
equal operator. do not use an equal operator.

We use Equi Join if we need both tables in the output We use Natural Join if we need only
without missing any column. the unique columns without
repetition.

We can use the WHERE clause or the ON clause in Equi Just use the keyword NATURAL
join. JOIN to perform the task.

The common column comes twice if we select all columns The common column comes only
in the query. once, even if we select all columns in
the query.

The syntax of Equi Join is The syntax of Natural Join is


SELECT columnName (s) SELECT columnName (s)
FROM tableName (s) WHERE tableName1.columnName FROM tableName1
= tableName2.columnName; NATURAL JOIN tableName2;

SQL EQUI JOIN

SQL EQUI JOIN is a specific type comparison base join (equally comparison) not allowing
other comparison operator such as <, > <= etc. And create record set result that are combining
columns value from the tables (two or more table).

Cross JOIN

SQL> SELECT * 13

FROM product JOIN category


ON product.category_id = category.category_id;
Cross JOIN is a simplest form of JOINs which matches each row from one database table to all
rows of another.
In other words it gives us combinations of each row of first table with all records in second
table.

Suppose we want to get all member records against all the movie records, we can use the script
shown below to get our desired results.

SELECT * FROM `movies` CROSS JOIN `members`

INNER JOIN and Equi join are the same.

The inner JOIN is used to return rows from both tables that satisfy the given condition.

Adding constraints during the creation


Create table emp1(eno int primary key, name varchar(15) not null, dept varchar(15) unique,
address varchar(15) default “Peelamedu”, sal int , check(eno>=100), check(sal<=500000);
Table level primary key
Create table bank(cust_id int , Ac_No int,name varchar(20),deposit_amt int not null,primary
key(cust_id,Ac_no);
Adding / Dropping constraints in an existing table:
Primary key
Alter table emp add primary key(eno);
Alter table emp drop primary key;

Not null
ALTER TABLE emp MODIFY sal int NOT NULL;
ALTER TABLE emp MODIFY sal INT NULL;
Unique
Alter table emp add unique(dept);
alter table emp drop INDEX dept;

Check
Alter table emp add check(sal<=200000);
ALTER TABLE emp DROP CHECK emp_chk_1;

Default
Alter table emp alter address set default "Peelamedu";
ALTER TABLE emp ALTER address DROP DEFAULT;

14
CREATE TABLE A(ID INT PRIMARY KEY,NAME CHAR(10));

CREATE TABLE B(ID INT ,MARK INT);

ALTER TABLE B ADD FOREIGN KEY(ID) REFERENCES A(ID) ON DELETE CASCADE ON


UPDATE CASCADE;

How to Find the Name of a Constraint in MySQL


SELECT TABLE_NAME, CONSTRAINT_TYPE, CONSTRAINT_NAME
FROM information_schema.table_constraints
WHERE table_name='emp’;

AUTO_INCREMENT
CREATE TABLE Persons (
Personid int NOT NULL AUTO_INCREMENT,LastName archar(255) NOT NULL,
FirstName varchar(255), Age int, PRIMARY KEY (Personid));
ALTER TABLE Persons AUTO_INCREMENT=100;

BOOL Zero is considered as false, nonzero values are


considered as true.

INT(size) A medium integer. Signed range is from -2147483648 to


2147483647. Unsigned range is from 0 to 4294967295.

INTEGER(size) Equal to INT(size)

FLOAT(size, d) A floating point number. The total number of digits is


specified in size. The number of digits after the decimal
point is specified in the d parameter

DOUBLE(size, d) A normal-size floating point number. The total number of


digits is specified in size. The number of digits after the
decimal point is specified in the d parameter

DECIMAL/DEC(size, d) An exact fixed-point number. The total number of digits is


specified in size. The number of digits after the decimal

15
point is specified in the d parameter. The maximum
number for size is 65. The maximum number for d is 30.
The default value for size is 10. The default value for d is
0.

DATE A date. Format: YYYY-MM-DD. The supported range is


from '1000-01-01' to '9999-12-31'

DATETIME(fsp) A date and time combination. Format: YYYY-MM-DD


hh:mm:ss. The supported range is from '1000-01-01
00:00:00' to '9999-12-31 23:59:59'. Adding DEFAULT
and ON UPDATE in the column definition to get
automatic initialization and updating to the current date
and time

TIME(fsp) A time. Format: hh:mm:ss. The supported range is from '-


838:59:59' to '838:59:59'

16
Difference between char and varchar

Difference Group by and Order By


With the GROUP BY clause not every row is include in the result. To summarize, the key
difference between order by and group by is: ORDER BY is used to sort a result by a
list of columns or expressions. GROUP BY is used to create unique combinations of a list
of columns that can be used to form summaries.

Difference single row and Multiple row functions


Single Row functions - Single row functions are the one who work on
single row and return one output per row. For example, length and case
conversion functions are single row functions.
Multiple Row functions - Multiple row functions work upon group of rows
and return one result for the complete set of rows.
Eg Aggregate functions

Difference candidate and alternate key

The candidate key is a set of attributes that uniquely identify the rows in a table. An
alternate key is a column or group of columns that uniquely identify every row in a table.

Alternate Key: In a table when more than one column is used for the identification of tuples in the
table, then that is an alternate key.

17
 Each table has only one primary key, although there are several choices.
 All the columns in the table other than the primary key act as an alternate key for that
table.

Candidate Key: This key is also used to identify the rows in a table.

 It contains a group of attributes that can be used to identify a particular row.


 Every table must have at least one column as a candidate key.
 In the candidate key column it does not contain any NULL value.

Primary, Alternate, and Foreign Keys


A key is a column, or a combination of columns, that uniquely identifies a row in a table. Each
key can generate a unique index or a unique constraint in a target database.
You can create the following types of keys:
Primary keys - Contain one or more columns whose combined values uniquely identify every
row in a table. Each table can have only one primary key.
Alternate keys - Contain one or more columns whose combined values uniquely identify every
row in a table.

Foreign keys - Contain one or more columns whose values match a primary or alternate key in
some other table.
In the following example, the TITLE table has a primary, alternate and foreign key:

The primary key, TITLE_ID contains the column TITLE ISBN, and uniquely identifies each book
in the table.
The alternate key, TITLE_NAME, contains the columns TITLE NAME and TITLE TYPE, and
enforces a constraint that no two titles of the same type can have the same name.
The foreign key contains the column PUBLISHER ID and references the primary key column in
the Publisher table.

18
19
20
5. MYSQL FUNCTIONS
MySQL has many built-in functions.

This reference contains string, numeric, date, and some advanced functions in MySQL.

MySQL String Functions

Function Description
ASCII Returns the ASCII value for the specific character
CHAR_LENGTH Returns the length of a string (in characters)
CHARACTER_LENGTH Returns the length of a string (in characters)
CONCAT Adds two or more expressions together
Returns the position of the first occurrence of a string in another
INSTR
string
LCASE Converts a string to lower-case
LEFT Extracts a number of characters from a string (starting from left)
LENGTH Returns the length of a string (in bytes)
LOWER Converts a string to lower-case
LTRIM Removes leading spaces from a string
MID Extracts a substring from a string (starting at any position)
RIGHT Extracts a number of characters from a string (starting from right)
RTRIM Removes trailing spaces from a string
SUBSTR Extracts a substring from a string (starting at any position)
TRIM Removes leading and trailing spaces from a string
UCASE Converts a string to upper-case
UPPER Converts a string to upper-case

MySQL Numeric Functions

Function Description
ABS Returns the absolute value of a number
AVG Returns the average value of an expression
CEIL Returns the smallest integer value that is >= to a number
CEILING Returns the smallest integer value that is >= to a number
COS Returns the cosine of a number
COT Returns the cotangent of a number
COUNT Returns the number of records returned by a select query
FLOOR Returns the largest integer value that is <= to a number
MAX Returns the maximum value in a set of values
MIN Returns the minimum value in a set of values
pg. 21
MOD Returns the remainder of a number divided by another number
POW Returns the value of a number raised to the power of another number
POWER Returns the value of a number raised to the power of another number
RAND Returns a random number
ROUND Rounds a number to a specified number of decimal places
SIGN Returns the sign of a number
SQRT Returns the square root of a number
SUM Calculates the sum of a set of values
TRUNCATE Truncates a number to the specified number of decimal places

MySQL Date Functions

Function Description
CURDATE Returns the current date
DATE Extracts the date part from a datetime expression
DAY Returns the day of the month for a given date
DAYNAME Returns the weekday name for a given date
DAYOFMONTH Returns the day of the month for a given date
DAYOFWEEK Returns the weekday index for a given date
DAYOFYEAR Returns the day of the year for a given date
MONTH Returns the month part for a given date
MONTHNAME Returns the name of the month for a given date
NOW Returns the current date and time
SYSDATE Returns the current date and time
TIME Extracts the time part from a given time/datetime
WEEKDAY Returns the weekday number for a given date
WEEKOFYEAR Returns the week number for a given date
YEAR Returns the year part for a given date

AGGREGATE FUNCTIONS
To perform such calculations in a query, you use aggregate functions. By
definition, an aggregate function performs a calculation on a set of values and
returns a single value. MySQL provides many aggregate functions that include
AVG , COUNT , SUM , MIN , MAX , etc.

1.SUM
2.AVG
3.MAX
4.MIN
5.COUNT

1.SELECT COUNT(*) FROM EMP;


O/P : 5
2.SELECT COUNT(*) FROM EMP WHERE SALARY >25000
O/P :2
pg. 22
3.SELECT COUNT(*) WHERE DEPT_CODE=10;
O/P: 65000

SELECT MIN(SAL) FROM EMP;


SELECT MAX(SALARY) FROM EMP;

1.SELECT SUM(SALARY) FROM EMP;


O/P : 139000
2.SELECT SUM(SALARY) FROM EMP WHERE DEPT_CODE=”ACCT”;
NUMERIC FUNCTIONS
1.SELECT ROUND(29.21) O/P:29
2.SELECT ROUND(32.76) O/P:33
3.SELECT ROUND(29.21,1) O/P:29.2
4.SELECT ROUND(32.76,1) O/P: 32.8
5.SELECT MOD(15,2) O/P : 1
6.SELECT POWER(3,2) O/P : 9
7.SELECT SIGN(-15) O/P :-1
8.SELECT SIGN(15) O/P :1
9.SELECT SQRT(81) O/P:9
10.SELECT TRUNCATE(15.79,1) O/P:15.7
(AFTER DECIMAL THE PLACE WILL BE TRUNCATED TO 1)

STRING FUNCTIONS
1.SELECT SUBSTR(COACHNAME,1,2) FROM CLUB WHERE DATEOFAPP>”1998-01-31”;
o/p : FIRST 2 CHARECTERS FROM THE COACHNAME ALSO DEPENDING UPON THE
DATE)
2.SELECT LOWER(ENAME) FROM EMP;
(WILL CONVERT ALL THE NAMES INTO LOWER CASE)
3.SELECT UPPER(ENAME) FROM EMP;
(WILL CONVERT ENAME TO UPPER CASE)
4.SELECT INSTR(“corporate floor”,”or”)
(RETURNS THE FIRST OCCURANCE POSITION OF THE GIVEN STRING);
O/P: 2
5.SELECT LENGTH(“PSG PUBLIC SCHOOLS”)
O/P : 18
6.SELECT LEFT(“USS/23/67/09”,3)
O/P: USS(RETURNS 3 CHARECTERS FROM THE LEFT)
7.SELECT RIGHT(“USS/23/67/09”,3);
O/P : /09 (RETURNS 3 CHARECTERS FROM THE RIGHT)
8.MID AND SUBSTR ARE THE SAME

DATE AND TIME FUNCTIONS

1.SELECT CURDATE()
O/P : RETURNS CURRENT DATE
2. SELECT DATE('2003-12-31 01:02:03');
O/P: 2003-12-31
3. SELECT MONTH('2008-02-03');
O/P: 2
4. SELECT YEAR('1987-01-01');
pg. 23
O/P: 1987
5. SELECT DAYNAME('2007-02-03');
O/P: 'Saturday'
6. SELECT DAYOFMONTH('2007-02-03');
O/P: 3
7. SELECT DAYOFWEEK('2007-02-03');
O/P: 7
8. SELECT DAYOFYEAR('2007-02-03');
O/P: 34
9.SELECT NOW()
RETURNS CURRENT DATE AND TIME
10.SYSDATE returns the time at which it executes. This differs from the behavior for NOW(), which
returns a constant time that indicates the time at which the statement began to execute. (Within a
stored function.

SELECT NOW(), SLEEP(2), NOW();


+---------------------+----------+---------------------+
| NOW() | SLEEP(2) | NOW() |
+---------------------+----------+---------------------+
| 2006-04-12 13:47:36 | 0 | 2006-04-12 13:47:36 |
+---------------------+----------+---------------------+

mysql> SELECT SYSDATE(), SLEEP(2), SYSDATE();


+---------------------+----------+---------------------+
| SYSDATE() | SLEEP(2) | SYSDATE() |
+---------------------+----------+---------------------+
| 2006-04-12 13:47:44 | 0 | 2006-04-12 13:47:46 |
+---------------------+----------+---------------------+

pg. 24

You might also like