SQL Unit 5
SQL Unit 5
SQL Unit 5
SQL
SQL (Structured Query Language) is used to perform operations on the records stored in the
database such as updating records, deleting records, creating and modifying tables, views, etc.
SQL is just a query language; it is not a database. To perform SQL queries, you need to install
any database, for example, Oracle, MySQL, MongoDB, PostGre SQL, SQL Server, DB2, etc.
What is SQL?
SQL stands for Structured Query Language.
It is designed for managing data in a relational database management system (RDBMS).
It is pronounced as S-Q-L or sometime See-Qwell.
SQL is a database language, it is used for database creation, deletion, fetching rows, and
modifying rows, etc.
SQL is based on relational algebra and tuple relational calculus.
All DBMS like MySQL, Oracle, MS Access, Sybase, Informix, PostgreSQL, and SQL
Server use SQL as standard database language.
1
Database Management System (CS/IT 4th SEM) unit 5
2
Database Management System (CS/IT 4th SEM) unit 5
A list of data types used in MySQL database. This is based on MySQL 8.0.
CHAR(Size) It is used to specify a fixed length string that can contain numbers,
letters, and special characters. Its size can be 0 to 255 characters.
Default is 1.
VARCHAR(Size) It is used to specify a variable length string that can contain 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.
VARBINARY(Size It is equal to VARCHAR() but stores binary byte strings. Its size
) parameter specifies the maximum column length in bytes.
TEXT(Size) It holds a string that can contain a maximum length of 255 characters.
3
Database Management System (CS/IT 4th SEM) unit 5
ENUM(val1, val2, It is used when a string object having only one value, chosen from a
val3,...) 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.
SET( val1,val2,val3 It is used to specify a string that can have 0 or more values, chosen
,....) from a list of possible values. You can list up to 64 values at one time
in a SET list.
BLOB(size) It is used for BLOBs (Binary Large Objects). It can hold up to 65,535
bytes.
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.
DOUBLE(size, d) It is a normal size floating point number. Its size parameter specifies
the total number of digits. The number of digits after the decimal is
4
Database Management System (CS/IT 4th SEM) unit 5
specified by d parameter.
DECIMAL(size, d) It is used to specify a fixed point number. Its size parameter specifies
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'
5
Database Management System (CS/IT 4th SEM) unit 5
SQL Operators
SQL statements generally contain some reserved words or characters that are used to perform
operations such as comparison and arithmetical operations etc. These reserved words or
characters are known as operators.
Generally there are three types of operators in SQL:
SQL Arithmetic Operators
SQL Comparison Operators
SQL Logical Operators
SQL Arithmetic Operators:
Let's assume two variables "a" and "b". Here "a" is valued 50 and "b" valued 100.
Example:
+ It is used to add containing values of both operands a+b will give 150
- It subtracts right hand operand from left hand operand a-b will give -50
/ It divides left hand operand by right hand operand b/a will give 2
% It divides left hand operand by right hand operand and b%a will give 0
returns reminder
= Examine both operands value that are equal or not,if yes (a=b) is not
condition become true. true
!= This is used to check the value of both operands equal or not,if (a!=b) is true
not condition become true.
6
Database Management System (CS/IT 4th SEM) unit 5
<> Examines the operand's value equal or not, if values are not (a<>b) is true
equal condition is true
> Examine the left operand value is greater than right Operand, if (a>b) is not
yes condition becomes true true
< Examines the left operand value is less than right Operand, if (a<="" td="">
yes condition becomes true
>= Examines that the value of left operand is greater than or equal (a>=b) is not
to the value of right operand or not,if yes condition become true
true
<= Examines that the value of left operand is less than or equal to (a<=b) is true
the value of right operand or not, if yes condition becomes true
!< Examines that the left operand value is not less than the right (a!<=""
operand value td="">
!> Examines that the value of left operand is not greater than the (a!>b) is true
value of right operand
SQL Logical Operators:
This is the list of logical operators used in SQL.
Operator Description
ALL This is used to compare a value to all values in another value set.
ANY This operator is used to compare the value in list according to the condition.
BETWEEN this operator is used to search for values, that are within a set of values
NOT the NOT operator reverse the meaning of any logical operator
7
Database Management System (CS/IT 4th SEM) unit 5
EXISTS the EXISTS operator is used to search for the presence of a row in a specified
table
LIKE this operator is used to compare a value to similar values using wildcard
operator
CREATE DATABASE database_name;
If you want to add tables in that database, you can use CREATE TABLE statement.
CREATE DATABASE database_name;
SQL DROP Database
SQL DROP statement is used to delete or remove indexes from a table in the database.
If you want to delete or drop an existing database in a SQL schema, you can use SQL DROP
DATABASE
Let's see the syntax of SQL DROP DATABASE:
DROP DATABASE database_name;
8
Database Management System (CS/IT 4th SEM) unit 5
RENAME DATABASE old_db_name TO new_db_name;
SQL SELECT Database
In MySQL database, you need to select a database first before executing any query on table,
view etc. To do so, we use following query:
USE DATABASE database_name;
SQL Table
Table is a collection of data, organized in terms of rows and columns. In DBMS term, table is
known as relation and row as tuple.
Table is the simple form of data storage. A table is also considered as a convenient
representation of relations.
Let's see an example of an employee table:
Employee
9
Database Management System (CS/IT 4th SEM) unit 5
It is a variable where we temporary store records and results. This is same like temp table but in
the case of temp table we need to explicitly drop it.
Table variables are used to store a set of records. So declaration syntax generally looks like
CREATE TABLE syntax.
create table "tablename"
("column1" "data type",
"column2" "data type",
...
"columnN" "data type");
When a transaction rolled back the data associated with table variable is not rolled back.
A table variable generally uses lesser resources than a temporary variable.
Table variable cannot be used as an input or an output parameter.
SQL Table
Table is a collection of data, organized in terms of rows and columns. In DBMS term, table is
known as relation and row as tuple.
Table is the simple form of data storage. A table is also considered as a convenient
representation of relations.
Let's see an example of an employee table:
The SQL Table variable is used to create, modify, rename, copy and delete tables. Table
variable was introduced by Microsoft.
It was introduced with SQL server 2000 to be an alternative of temporary tables.
10
Database Management System (CS/IT 4th SEM) unit 5
It is a variable where we temporary store records and results. This is same like temp table but in
the case of temp table we need to explicitly drop it.
Table variables are used to store a set of records. So declaration syntax generally looks like
CREATE TABLE syntax.
create table "tablename"
("column1" "data type",
"column2" "data type",
...
"columnN" "data type");
When a transaction rolled back the data associated with table variable is not rolled back.
A table variable generally uses lesser resources than a temporary variable.
Table variable cannot be used as an input or an output parameter.
SQL CREATE TABLE
SQL 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.
Let's see the simple syntax to create the table.
create table "tablename"
("column1" "data type",
"column2" "data type",
"column3" "data type",
...
"columnN" "data type");
The data type of the columns may vary from one database to another. For example, NUMBER is
supported in Oracle database for integer value whereas INT is supported in MySQL.
Let us take an example to create a STUDENTS table with ID as primary key and NOT NULL
are the constraint showing that these fields cannot be NULL while creating records in the table.
SQL> CREATE TABLE STUDENTS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
11
Database Management System (CS/IT 4th SEM) unit 5
PRIMARY KEY (ID)
);
You can verify it, if you have created the table successfully by looking at the message displayed
by the SQL Server, else you can use DESC command as follows:
SQL> DESC STUDENTS;
ID Int(11) NO PRI
NAME Varchar(20) NO
AGE Int(11) NO
Now you have the STUDENTS table available in your database and you can use to store required
information related to students.
12
Database Management System (CS/IT 4th SEM) unit 5
ID Int(11) NO PRI
NAME Varchar(20) NO
AGE Int(11) NO
13
Database Management System (CS/IT 4th SEM) unit 5
14
Database Management System (CS/IT 4th SEM) unit 5
RENAME TO new_table_name;
Optionally, you can write following command to rename the table.
RENAME old_table _name To new_table_name;
Let us take an example of a table named "STUDENTS", now due to some reason we want to
change it into table name "ARTISTS".
Table1: students
15
Database Management System (CS/IT 4th SEM) unit 5
1. COUNT FUNCTION
COUNT function is used to Count the number of rows in a database table. It can work on
both numeric and non-numeric data types.
COUNT function uses the COUNT(*) that returns the count of all the rows in a specified
table. COUNT(*) considers duplicate and Null.
Syntax
1. COUNT(*)
2. or
3. COUNT( [ALL|DISTINCT] expression )
Sample table:
16
Database Management System (CS/IT 4th SEM) unit 5
PRODUCT_MAST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Example: COUNT()
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
Output:
10
17
Database Management System (CS/IT 4th SEM) unit 5
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
3. WHERE RATE>=20;
Output:
1. SELECT COUNT(DISTINCT COMPANY)
2. FROM PRODUCT_MAST;
Output:
1. SELECT COMPANY, COUNT(*)
2. FROM PRODUCT_MAST
3. GROUP BY COMPANY;
Output:
Com1 5
Com2 3
Com3 2
18
Database Management System (CS/IT 4th SEM) unit 5
1. SELECT COMPANY, COUNT(*)
2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING COUNT(*)>2;
Output:
Com1 5
Com2 3
2. SUM Function
Sum function is used to calculate the sum of all selected columns. It works on numeric fields
only.
Syntax
1. SUM()
2. or
3. SUM( [ALL|DISTINCT] expression )
Example: SUM()
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST;
Output:
670
1. SELECT SUM(COST)
19
Database Management System (CS/IT 4th SEM) unit 5
2. FROM PRODUCT_MAST
3. WHERE QTY>3;
Output:
320
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3
4. GROUP BY COMPANY;
Output:
Com1 150
Com2 170
1. SELECT COMPANY, SUM(COST)
2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING SUM(COST)>=170;
Output:
Com1 335
Com3 170
20
Database Management System (CS/IT 4th SEM) unit 5
3. AVG function
The AVG function is used to calculate the average value of the numeric type. AVG function
returns the average of all non-Null values.
Syntax
1. AVG()
2. or
3. AVG( [ALL|DISTINCT] expression )
Example:
1. SELECT AVG(COST)
2. FROM PRODUCT_MAST;
Output:
67.00
4. MAX Function
MAX function is used to find the maximum value of a certain column. This function determines
the largest value of all selected values of a column.
Syntax
1. MAX()
2. or
3. MAX( [ALL|DISTINCT] expression )
Example:
1. SELECT MAX(RATE)
2. FROM PRODUCT_MAST;
30
21
Database Management System (CS/IT 4th SEM) unit 5
5. MIN Function
MIN function is used to find the minimum value of a certain column. This function determines
the smallest value of all selected values of a column.
Syntax
1. MIN()
2. or
3. MIN( [ALL|DISTINCT] expression )
Example:
1. SELECT MIN(RATE)
2. FROM PRODUCT_MAST;
Output:
10
22
Database Management System (CS/IT 4th SEM) unit 5
SQL JOIN
As the name shows, JOIN means to combine something. In case of SQL, JOIN means "to
combine two or more tables".
In SQL, JOIN clause is used to combine the records from two or more tables in a database.
1. INNER JOIN
2. LEFT JOIN
3. RIGHT JOIN
4. FULL JOIN
Sample Table
EMPLOYEE
23
Database Management System (CS/IT 4th SEM) unit 5
PROJECT
101 1 Testing
102 2 Development
103 3 Designing
104 4 Development
1. INNER JOIN
In SQL, INNER JOIN selects records that have matching values in both tables as long as the
condition is satisfied. It returns the combination of all rows from both the tables where the
condition satisfies.
Syntax
1. SELECT table1.column1, table1.column2, table2.column1,....
2. FROM table1
3. INNER JOIN table2
4. ON table1.matching_column = table2.matching_column;
Query
1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
2. FROM EMPLOYEE
3. INNER JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
24
Database Management System (CS/IT 4th SEM) unit 5
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
2. LEFT JOIN
The SQL left join returns all the values from left table and the matching values from the right
table. If there is no matching join value, it will return NULL.
Syntax
1. SELECT table1.column1, table1.column2, table2.column1,....
2. FROM table1
3. LEFT JOIN table2
4. ON table1.matching_column = table2.matching_column;
Query
1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
2. FROM EMPLOYEE
3. LEFT JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
25
Database Management System (CS/IT 4th SEM) unit 5
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
3. RIGHT JOIN
In SQL, RIGHT JOIN returns all the values from the values from the rows of right table and the
matched values from the left table. If there is no matching in both tables, it will return NULL.
Syntax
1. SELECT table1.column1, table1.column2, table2.column1,....
2. FROM table1
3. RIGHT JOIN table2
4. ON table1.matching_column = table2.matching_column;
Query
1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
2. FROM EMPLOYEE
26
Database Management System (CS/IT 4th SEM) unit 5
3. RIGHT JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
4. FULL JOIN
In SQL, FULL JOIN is the result of a combination of both left and right outer join. Join tables
have all the records from both tables. It puts NULL on the place of matches not found.
Syntax
1. SELECT table1.column1, table1.column2, table2.column1,....
2. FROM table1
3. FULL JOIN table2
4. ON table1.matching_column = table2.matching_column;
Query
1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
2. FROM EMPLOYEE
3. FULL JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
27
Database Management System (CS/IT 4th SEM) unit 5
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
The SQL Set operation is used to combine the two or more SQL SELECT statements.
1. Union
2. Union All
3. Intersect
4. Minus
28
Database Management System (CS/IT 4th SEM) unit 5
1. Union
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
1. SELECT column_name FROM table1
2. UNION
3. SELECT column_name FROM table2;
ID NAME
1 Jack
2 Harry
3 Jackson
29
Database Management System (CS/IT 4th SEM) unit 5
ID NAME
3 Jackson
4 Stephan
5 David
1. SELECT * FROM First
2. UNION
3. SELECT * FROM Second;
ID NAME
1 Jack
2 Harry
3 Jackson
4 Stephan
5 David
30
Database Management System (CS/IT 4th SEM) unit 5
2. Union All
Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.
Syntax:
1. SELECT column_name FROM table1
2. UNION ALL
3. SELECT column_name FROM table2;
1. SELECT * FROM First
2. UNION ALL
3. SELECT * FROM Second;
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.
31
Database Management System (CS/IT 4th SEM) unit 5
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
1. SELECT column_name FROM table1
2. INTERSECT
3. SELECT column_name FROM table2;
Example:
1. SELECT * FROM First
2. INTERSECT
3. SELECT * FROM Second;
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:
1. SELECT column_name FROM table1
32
Database Management System (CS/IT 4th SEM) unit 5
2. MINUS
3. SELECT column_name FROM table2;
Example
1. SELECT * FROM First
2. MINUS
3. SELECT * FROM Second;
ID NAME
1 Jack
2 Harry
33
Database Management System (CS/IT 4th SEM) unit 5
ASCII()
1
Returns numeric value of left-most character
BIN()
2
Returns a string representation of the argument
BIT_LENGTH()
3
Returns length of argument in bits
CHAR_LENGTH()
4
Returns number of characters in argument
CHAR()
5
Returns the character for each integer passed
CHARACTER_LENGTH()
6
A synonym for CHAR_LENGTH()
CONCAT_WS()
7
Returns concatenate with separator
CONCAT()
8
Returns concatenated string
34
Database Management System (CS/IT 4th SEM) unit 5
CONV()
9
Converts numbers between different number bases
ELT()
10
Returns string at index number
EXPORT_SET()
11 Returns a string such that for every bit set in the value bits,
you get an on string and for every unset bit, you get an off
string
FIELD()
12
Returns the index (position) of the first argument in the
subsequent arguments
FIND_IN_SET()
13
Returns the index position of the first argument within the
second argument
FORMAT()
HEX()
15
Returns a string representation of a hex value
16 INSERT()
35
Database Management System (CS/IT 4th SEM) unit 5
INSTR()
17
Returns the index of the first occurrence of substring
LCASE()
18
Synonym for LOWER()
LEFT()
19
Returns the leftmost number of characters as specified
LENGTH()
20
Returns the length of a string in bytes
LOAD_FILE()
21
Loads the named file
LOCATE()
22
Returns the position of the first occurrence of substring
LOWER()
23
Returns the argument in lowercase
LPAD()
24
Returns the string argument, left-padded with the specified
string
LTRIM()
25
Removes leading spaces
36
Database Management System (CS/IT 4th SEM) unit 5
MAKE_SET()
26
Returns a set of comma-separated strings that have the
corresponding bit in bits set
MID()
27
Returns a substring starting from the specified position
OCT()
28
Returns a string representation of the octal argument
OCTET_LENGTH()
29
A synonym for LENGTH()
ORD()
POSITION()
31
A synonym for LOCATE()
QUOTE()
32
Escapes the argument for use in an SQL statement
REGEXP
33
Pattern matching using regular expressions
34 REPEAT()
37
Database Management System (CS/IT 4th SEM) unit 5
REPLACE()
35
Replaces occurrences of a specified string
REVERSE()
36
Reverses the characters in a string
RIGHT()
37
Returns the specified rightmost number of characters
RPAD()
38
Appends string the specified number of times
RTRIM()
39
Removes trailing spaces
SOUNDEX()
40
Returns a soundex string
SOUNDS LIKE
41
Compares sounds
SPACE()
42
Returns a string of the specified number of spaces
STRCMP()
43
Compares two strings
44 SUBSTRING_INDEX()
38
Database Management System (CS/IT 4th SEM) unit 5
SUBSTRING(), SUBSTR()
45
Returns the substring as specified
TRIM()
46
Removes leading and trailing spaces
UCASE()
47
Synonym for UPPER()
UNHEX()
48
Converts each pair of hexadecimal digits to a character
UPPER()
49
Converts to uppercase
ASCII(str)
Returns the numeric value of the leftmost character of the string str. Returns 0 if str is the empty
string. Returns NULL if str is NULL. ASCII() works for characters with numeric values from 0
to 255.
SQL> SELECT ASCII('2');
+---------------------------------------------------------+
| ASCII('2') |
+---------------------------------------------------------+
| 50 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
39
Database Management System (CS/IT 4th SEM) unit 5
| ASCII('dx') |
+---------------------------------------------------------+
| 100 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
BIN(N)
BIT_LENGTH(str)
CHAR() interprets each argument N as an integer and returns a string consisting of the
characters given by the code values of those integers. NULL values are skipped.
40
Database Management System (CS/IT 4th SEM) unit 5
CHAR_LENGTH(str)
Returns the length of the string str measured in characters. A multi-byte character counts as a
single character. This means that for a string containing five two-byte characters, LENGTH()
returns 10, whereas CHAR_LENGTH() returns 5.
CHARACTER_LENGTH(str)
CONCAT(str1,str2,...)
Returns the string that results from concatenating the arguments. May have one or more
arguments. If all arguments are non-binary strings, the result is a non-binary string. If the
arguments include any binary strings, the result is a binary string. A numeric argument is
converted to its equivalent binary string form; if you want to avoid that, you can use an explicit
type cast, as in this example −
CONCAT_WS(separator,str1,str2,...)
CONCAT_WS() stands for Concatenate With Separator and is a special form of CONCAT().
The first argument is the separator for the rest of the arguments. The separator is added between
41
Database Management System (CS/IT 4th SEM) unit 5
the strings to be concatenated. The separator can be a string, as can the rest of the arguments. If
the separator is NULL, the result is NULL.
CONV(N,from_base,to_base)
Converts numbers between different number bases. Returns a string representation of the
number N, converted from base from_base to to_base. Returns NULL if any argument is
NULL. The argument N is interpreted as an integer, but may be specified as an integer or a
string. The minimum base is 2 and the maximum base is 36. If to_base is a negative number, N
is regarded as a signed number. Otherwise, N is treated as unsigned. CONV() works with 64-bit
precision.
ELT(N,str1,str2,str3,...)
Returns str1 if N = 1, str2 if N = 2, and so on. Returns NULL if N is less than 1 or greater than
the number of arguments. ELT() is the complement of FIELD().
EXPORT_SET(bits,on,off[,separator[,number_of_bits]])
42
Database Management System (CS/IT 4th SEM) unit 5
Returns a string such that for every bit set in the value bits, you get an on string and for every
bit not set in the value, you get an off string. Bits in bits are examined from right to left (from
low-order to high-order bits). Strings are added to the result from left to right, separated by the
separator string (the default being the comma character .,.). The number of bits examined is
given by number_of_bits (defaults to 64).
FIELD(str,str1,str2,str3,...)
Returns the index (position starting with 1) of str in the str1, str2, str3, ... list. Returns 0 if str is
not found.
FIND_IN_SET(str,strlist)
Returns a value in the range of 1 to N if the string str is in the string list strlist consisting of N
substrings.
FORMAT(X,D)
43
Database Management System (CS/IT 4th SEM) unit 5
Formats the number X to a format like '#,###,###.##', rounded to D decimal places, and returns
the result as a string. If D is 0, the result has no decimal point or fractional part.
HEX(N_or_S)
INSERT(str,pos,len,newstr)
Returns the string str, with the substring beginning at position pos and len characters long
replaced by the string newstr. Returns the original string if pos is not within the length of the
string. Replaces the rest of the string from position pos if len is not within the length of the rest
of the string. Returns NULL if any argument is NULL.
SQL> SELECT INSERT('Quadratic', 3, 4, 'What');
44
Database Management System (CS/IT 4th SEM) unit 5
+---------------------------------------------------------+
| INSERT('Quadratic', 3, 4, 'What') |
+---------------------------------------------------------+
| QuWhattic |
+---------------------------------------------------------+
1 row in set (0.00 sec)
INSTR(str,substr)
Returns the position of the first occurrence of substring substr in string str. This is the same as
the two-argument form of LOCATE(), except that the order of the arguments is reversed.
SQL> SELECT INSTR('foobarbar', 'bar');
+---------------------------------------------------------+
| INSTR('foobarbar', 'bar') |
+---------------------------------------------------------+
| 4 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
LCASE(str)
LEFT(str,len)
Returns the leftmost len characters from the string str, or NULL if any argument is NULL.
LENGTH(str)
Returns the length of the string str, measured in bytes. A multi-byte character counts as multiple
bytes. This means that for a string containing five two-byte characters, LENGTH() returns 10,
whereas CHAR_LENGTH() returns 5.
45
Database Management System (CS/IT 4th SEM) unit 5
| LENGTH('text') |
+---------------------------------------------------------+
| 4 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
LOAD_FILE(file_name)
Reads the file and returns the file contents as a string. To use this function, the file must be
located on the server host, you must specify the full pathname to the file, and you must have the
FILE privilege. The file must be readable by all and its size less than max_allowed_packet
bytes.
If the file does not exist or cannot be read because one of the preceding conditions is not
satisfied, the function returns NULL.
LOCATE(substr,str), LOCATE(substr,str,pos)
The first syntax returns the position of the first occurrence of substring substr in string str. The
second syntax returns the position of the first occurrence of substring substr in string str,
starting at position pos. Returns 0 if substr is not in str.
LOWER(str)
46
Database Management System (CS/IT 4th SEM) unit 5
Returns the string str with all characters changed to lowercase according to the current character
set mapping.
LPAD(str,len,padstr)
Returns the string str, left-padded with the string padstr to a length of len characters. If
str is longer than len, the return value is shortened to len characters.
SQL> SELECT LPAD('hi',4,'??');
+---------------------------------------------------------+
| LPAD('hi',4,'??') |
+---------------------------------------------------------+
| ??hi |
+---------------------------------------------------------+
1 row in set (0.00 sec)
LTRIM(str)
MAKE_SET(bits,str1,str2,...)
Returns a set value (a string containing substrings separated by .,. characters) consisting of the
strings that have the corresponding bit in bits set. str1 corresponds to bit 0, str2 to bit 1, and so
on. NULL values in str1, str2, ... are not appended to the result.
SQL> SELECT MAKE_SET(1,'a','b','c');
+---------------------------------------------------------+
| MAKE_SET(1,'a','b','c') |
+---------------------------------------------------------+
| a |
47
Database Management System (CS/IT 4th SEM) unit 5
+---------------------------------------------------------+
1 row in set (0.00 sec)
MID(str,pos,len)
OCT(N)
OCTET_LENGTH(str)
ORD(str)
If the leftmost character of the string str is a multi-byte character, returns the code for that
character, calculated from the numeric values of its constituent bytes using this formula −
(1st byte code)
+ (2nd byte code . 256)
+ (3rd byte code . 2562) ...
If the leftmost character is not a multi-byte character, ORD() returns the same value as the
ASCII() function.
SQL> SELECT ORD('2');
+---------------------------------------------------------+
| ORD('2') |
+---------------------------------------------------------+
| 50 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
POSITION(substr IN str)
48
Database Management System (CS/IT 4th SEM) unit 5
QUOTE(str)
Quotes a string to produce a result that can be used as a properly escaped data value in an SQL
statement. The string is returned enclosed by single quotes and with each instance of single
quote ('), backslash ('\'), ASCII NUL, and Control-Z preceded by a backslash. If the argument is
NULL, the return value is the word 'NULL' without enclosing single quotes.
SQL> SELECT QUOTE('Don\'t!');
+---------------------------------------------------------+
| QUOTE('Don\'t!') |
+---------------------------------------------------------+
| 'Don\'t!' |
+---------------------------------------------------------+
1 row in set (0.00 sec)
NOTE − Please check if your installation has any bug with this function then don't use this
function.
This function performs a pattern match of expr against pattern. Returns 1 if expr matches pat;
otherwise it returns 0. If either expr or pat is NULL, the result is NULL. REGEXP is not case
sensitive, except when used with binary strings.
SQL> SELECT 'ABCDEF' REGEXP 'A%C%%';
+---------------------------------------------------------+
| 'ABCDEF' REGEXP 'A%C%%' |
+---------------------------------------------------------+
| 0 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
Another example is −
SQL> SELECT 'ABCDE' REGEXP '.*';
+---------------------------------------------------------+
| 'ABCDE' REGEXP '.*' |
+---------------------------------------------------------+
| 1 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
49
Database Management System (CS/IT 4th SEM) unit 5
REPEAT(str,count)
Returns a string consisting of the string str repeated count times. If count is less than 1, returns
an empty string. Returns NULL if str or count are NULL.
SQL> SELECT REPEAT('SQL', 3);
+---------------------------------------------------------+
| REPEAT('SQL', 3) |
+---------------------------------------------------------+
| SQLSQLSQL |
+---------------------------------------------------------+
1 row in set (0.00 sec)
REPLACE(str,from_str,to_str)
Returns the string str with all occurrences of the string from_str replaced by the string to_str.
REPLACE() performs a case-sensitive match when searching for from_str.
SQL> SELECT REPLACE('www.mysql.com', 'w', 'Ww');
+---------------------------------------------------------+
| REPLACE('www.mysql.com', 'w', 'Ww') |
+---------------------------------------------------------+
| WwWwWw.mysql.com |
+---------------------------------------------------------+
1 row in set (0.00 sec)
REVERSE(str)
Returns the string str with the order of the characters reversed.
SQL> SELECT REVERSE('abcd');
+---------------------------------------------------------+
| REVERSE('abcd') |
+---------------------------------------------------------+
| dcba |
+---------------------------------------------------------+
1 row in set (0.00 sec)
RIGHT(str,len)
Returns the rightmost len characters from the string str, or NULL if any argument is NULL.
SQL> SELECT RIGHT('foobarbar', 4);
+---------------------------------------------------------+
| RIGHT('foobarbar', 4) |
50
Database Management System (CS/IT 4th SEM) unit 5
+---------------------------------------------------------+
| rbar |
+---------------------------------------------------------+
1 row in set (0.00 sec)
RPAD(str,len,padstr)
Returns the string str, right-padded with the string padstr to a length of len characters. If str is
longer than len, the return value is shortened to len characters.
SQL> SELECT RPAD('hi',5,'?');
+---------------------------------------------------------+
| RPAD('hi',5,'?') |
+---------------------------------------------------------+
| hi??? |
+---------------------------------------------------------+
1 row in set (0.00 sec)
RTRIM(str)
SOUNDEX(str)
Returns a soundex string from str. Two strings that sound almost the same should have identical
soundex strings. A standard soundex string is four characters long, but the SOUNDEX()
function returns an arbitrarily long string. You can use SUBSTRING() on the result to get a
standard soundex string. All non-alphabetic characters in str are ignored. All international
alphabetic characters outside the A-Z range are treated as vowels.
SQL> SELECT SOUNDEX('Hello');
+---------------------------------------------------------+
| SOUNDEX('Hello') |
+---------------------------------------------------------+
| H400 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
SPACE(N)
STRCMP(str1, str2)
Compares two strings and returns 0 if both strings are equal, it returns -1 if the first argument is
smaller than the second according to the current sort order otherwise it returns 1.
SQL> SELECT STRCMP('MOHD', 'MOHD');
+---------------------------------------------------------+
| STRCMP('MOHD', 'MOHD') |
+---------------------------------------------------------+
| 0 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
Another example is −
SQL> SELECT STRCMP('AMOHD', 'MOHD');
+---------------------------------------------------------+
| STRCMP('AMOHD', 'MOHD') |
+---------------------------------------------------------+
| -1 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
SUBSTRING(str,pos)
52
Database Management System (CS/IT 4th SEM) unit 5
SUBSTRING(str,pos,len)
The forms without a len argument return a substring from string str starting at position pos. The
forms with a len argument return a substring len characters long from string str, starting at
position pos. The forms that use FROM are standard SQL syntax. It is also possible to use a
negative value for pos. In this case, the beginning of the substring is pos characters from the end
of the string, rather than the beginning. A negative value may be used for pos in any of the
forms of this function.
SQL> SELECT SUBSTRING('Quadratically',5);
+---------------------------------------------------------+
| SSUBSTRING('Quadratically',5) |
+---------------------------------------------------------+
| ratically |
+---------------------------------------------------------+
1 row in set (0.00 sec)
SUBSTRING_INDEX(str,delim,count)
Returns the substring from string str before count occurrences of the delimiter delim. If count is
positive, everything to the left of the final delimiter (counting from the left) is returned. If count
is negative, everything to the right of the final delimiter (counting from the right) is returned.
SUBSTRING_INDEX() performs a case-sensitive match when searching for delim.
SQL> SELECT SUBSTRING_INDEX('www.mysql.com', '.', 2);
+---------------------------------------------------------+
| SUBSTRING_INDEX('www.mysql.com', '.', 2) |
53
Database Management System (CS/IT 4th SEM) unit 5
+---------------------------------------------------------+
| www.mysql |
+---------------------------------------------------------+
1 row in set (0.00 sec)
Returns the string str with all remstr prefixes or suffixes removed. If none of the specifiers
BOTH, LEADING, or TRAILING is given, BOTH is assumed. remstr is optional and, if not
specified, spaces are removed.
SQL> SELECT TRIM(' bar ');
+---------------------------------------------------------+
| TRIM(' bar ') |
+---------------------------------------------------------+
| bar |
+---------------------------------------------------------+
1 row in set (0.00 sec)
UCASE(str)
54
Database Management System (CS/IT 4th SEM) unit 5
UNHEX(str)
Performs the inverse operation of HEX(str). That is, it interprets each pair of hexadecimal digits
in the argument as a number and converts it to the character represented by the number. The
resulting characters are returned as a binary string.
SQL> SELECT UNHEX('4D7953514C');
+---------------------------------------------------------+
| UNHEX('4D7953514C') |
+---------------------------------------------------------+
| SQL |
+---------------------------------------------------------+
1 row in set (0.00 sec)
The characters in the argument string must be legal hexadecimal digits: '0' .. '9', 'A' .. 'F', 'a' .. 'f'.
If UNHEX() encounters any non-hexadecimal digits in the argument, it returns NULL.
UPPER(str)
Returns the string str with all characters changed to uppercase according to the current character
set mapping.
SQL> SELECT UPPER('Allah-hus-samad');
+---------------------------------------------------------+
| UPPER('Allah-hus-samad') |
+---------------------------------------------------------+
| ALLAH-HUS-SAMAD |
+---------------------------------------------------------+
1 row in set (0.00 sec)
55
Database Management System (CS/IT 4th SEM) unit 5
ADDDATE()
1
Adds dates
ADDTIME()
2
Adds time
CONVERT_TZ()
3
Converts from one timezone to another
CURDATE()
4
Returns the current date
CURRENT_DATE(), CURRENT_DATE
5
Synonyms for CURDATE()
CURRENT_TIME(), CURRENT_TIME
6
Synonyms for CURTIME()
CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP
7
Synonyms for NOW()
CURTIME()
8
Returns the current time
DATE_ADD()
9
Adds two dates
DATE_FORMAT()
10
Formats date as specified
DATE_SUB()
11
Subtracts two dates
DATE()
12
Extracts the date part of a date or datetime expression
13 DATEDIFF()
56
Database Management System (CS/IT 4th SEM) unit 5
DAY()
14
Synonym for DAYOFMONTH()
DAYNAME()
15
Returns the name of the weekday
DAYOFMONTH()
16
Returns the day of the month (1-31)
DAYOFWEEK()
17
Returns the weekday index of the argument
DAYOFYEAR()
18
Returns the day of the year (1-366)
EXTRACT
19
Extracts part of a date
FROM_DAYS()
20
Converts a day number to a date
FROM_UNIXTIME()
21
Formats date as a UNIX timestamp
HOUR()
22
Extracts the hour
LAST_DAY
23
Returns the last day of the month for the argument
LOCALTIME(), LOCALTIME
24
Synonym for NOW()
LOCALTIMESTAMP, LOCALTIMESTAMP()
25
Synonym for NOW()
MAKEDATE()
26
Creates a date from the year and day of year
MAKETIME
27
MAKETIME()
MICROSECOND()
28
Returns the microseconds from argument
57
Database Management System (CS/IT 4th SEM) unit 5
MINUTE()
29
Returns the minute from the argument
MONTH()
30
Return the month from the date passed
MONTHNAME()
31
Returns the name of the month
NOW()
32
Returns the current date and time
PERIOD_ADD()
33
Adds a period to a year-month
PERIOD_DIFF()
34
Returns the number of months between periods
QUARTER()
35
Returns the quarter from a date argument
SEC_TO_TIME()
36
Converts seconds to 'HH:MM:SS' format
SECOND()
37
Returns the second (0-59)
STR_TO_DATE()
38
Converts a string to a date
SUBDATE()
39
When invoked with three arguments a synonym for DATE_SUB()
SUBTIME()
40
Subtracts times
SYSDATE()
41
Returns the time at which the function executes
TIME_FORMAT()
42
Formats as time
TIME_TO_SEC()
43
Returns the argument converted to seconds
TIME()
44
Extracts the time portion of the expression passed
58
Database Management System (CS/IT 4th SEM) unit 5
TIMEDIFF()
45
Subtracts time
TIMESTAMP()
46 With a single argument this function returns the date or datetime
expression. With two arguments, the sum of the arguments
TIMESTAMPADD()
47
Adds an interval to a datetime expression
TIMESTAMPDIFF()
48
Subtracts an interval from a datetime expression
TO_DAYS()
49
Returns the date argument converted to days
UNIX_TIMESTAMP()
50
Returns a UNIX timestamp
UTC_DATE()
51
Returns the current UTC date
UTC_TIME()
52
Returns the current UTC time
UTC_TIMESTAMP()
53
Returns the current UTC date and time
WEEK()
54
Returns the week number
WEEKDAY()
55
Returns the weekday index
WEEKOFYEAR()
56
Returns the calendar week of the date (1-53)
YEAR()
57
Returns the year
YEARWEEK()
58
Returns the year and week
59
Database Management System (CS/IT 4th SEM) unit 5
When invoked with the INTERVAL form of the second argument, ADDDATE() is a
synonym for DATE_ADD(). The related function SUBDATE() is a synonym for
DATE_SUB(). For information on the INTERVAL unit argument, see the discussion for
DATE_ADD().
mysql> SELECT DATE_ADD('1998-01-02', INTERVAL 31 DAY);
+---------------------------------------------------------+
| DATE_ADD('1998-01-02', INTERVAL 31 DAY) |
+---------------------------------------------------------+
| 1998-02-02 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
When invoked with the days form of the second argument, MySQL treats it as an
integer number of days to be added to expr.
mysql> SELECT ADDDATE('1998-01-02', 31);
+---------------------------------------------------------+
| DATE_ADD('1998-01-02', INTERVAL 31 DAY) |
+---------------------------------------------------------+
| 1998-02-02 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
ADDTIME(expr1,expr2)
ADDTIME() adds expr2 to expr1 and returns the result. The expr1 is a time or datetime
expression, while the expr2 is a time expression.
mysql> SELECT ADDTIME('1997-12-31 23:59:59.999999','1
1:1:1.000002');
+---------------------------------------------------------+
| DATE_ADD('1997-12-31 23:59:59.999999','1 1:1:1.000002') |
+---------------------------------------------------------+
| 1998-01-02 01:01:01.000001 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
CONVERT_TZ(dt,from_tz,to_tz)
60
Database Management System (CS/IT 4th SEM) unit 5
This converts a datetime value dt from the time zone given by from_tz to the time zone
given by to_tz and returns the resulting value. This function returns NULL if the
arguments are invalid.
mysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','GMT','MET');
+---------------------------------------------------------+
| CONVERT_TZ('2004-01-01 12:00:00','GMT','MET') |
+---------------------------------------------------------+
| 2004-01-01 13:00:00 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
CURDATE()
Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format,
depending on whether the function is used in a string or in a numeric context.
mysql> SELECT CURDATE();
+---------------------------------------------------------+
| CURDATE() |
+---------------------------------------------------------+
| 1997-12-15 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
CURTIME()
61
Database Management System (CS/IT 4th SEM) unit 5
DATE(expr)
Extracts the date part of the date or datetime expression expr.
mysql> SELECT DATE('2003-12-31 01:02:03');
+---------------------------------------------------------+
| DATE('2003-12-31 01:02:03') |
+---------------------------------------------------------+
| 2003-12-31 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
DATEDIFF(expr1,expr2)
DATEDIFF() returns expr1 . expr2 expressed as a value in days from one date to the
other. Both expr1 and expr2 are date or date-and-time expressions. Only the date parts
of the values are used in the calculation.
62
Database Management System (CS/IT 4th SEM) unit 5
MICROSECOND MICROSECONDS
SECOND SECONDS
MINUTE MINUTES
HOUR HOURS
DAY DAYS
WEEK WEEKS
MONTH MONTHS
QUARTER QUARTERS
63
Database Management System (CS/IT 4th SEM) unit 5
YEAR YEARS
SECOND_MICROSECOND 'SECONDS.MICROSECONDS'
MINUTE_MICROSECOND 'MINUTES.MICROSECONDS'
MINUTE_SECOND 'MINUTES:SECONDS'
HOUR_MICROSECOND 'HOURS.MICROSECONDS'
HOUR_SECOND 'HOURS:MINUTES:SECONDS'
HOUR_MINUTE 'HOURS:MINUTES'
DAY_MICROSECOND 'DAYS.MICROSECONDS'
YEAR_MONTH 'YEARS-MONTHS'
64
Database Management System (CS/IT 4th SEM) unit 5
DATE_FORMAT(date,format)
This command formats the date value as per the format string.
The following specifiers may be used in the format string. The '%' character is required before
the format specifier characters.
%a
1
Abbreviated weekday name (Sun..Sat)
%b
2
Abbreviated month name (Jan..Dec)
%c
3
Month, numeric (0..12)
%D
4
Day of the month with English suffix (0th, 1st, 2nd, 3rd, .)
%d
5
Day of the month, numeric (00..31)
%e
6
Day of the month, numeric (0..31)
%f
7
Microseconds (000000..999999)
%H
8
Hour (00..23)
%h
9
Hour (01..12)
65
Database Management System (CS/IT 4th SEM) unit 5
%I
10
Hour (01..12)
%i
11
Minutes, numeric (00..59)
%j
12
Day of year (001..366)
%k
13
Hour (0..23)
%l
14
Hour (1..12)
%M
15
Month name (January..December)
%m
16
Month, numeric (00..12)
%p
17
AM or PM
%r
18
Time, 12-hour (hh:mm:ss followed by AM or PM)
%S
19
Seconds (00..59)
%s
20
Seconds (00..59)
%T
21
Time, 24-hour (hh:mm:ss)
%U
22
Week (00..53), where Sunday is the first day of the week
%u
23
Week (00..53), where Monday is the first day of the week
24 %V
Week (01..53), where Sunday is the first day of the week; used
66
Database Management System (CS/IT 4th SEM) unit 5
with %X
%v
25 Week (01..53), where Monday is the first day of the week; used
with %x
%W
26
Weekday name (Sunday..Saturday)
%w
27
Day of the week (0=Sunday..6=Saturday)
%X
28 Year for the week where Sunday is the first day of the week,
numeric, four digits; used with %V
%x
29 Year for the week, where Monday is the first day of the week,
numeric, four digits; used with %v
%Y
30
Year, numeric, four digits
%y
31
Year, numeric (two digits)
%%
32
A literal .%. character
%x
33
x, for any.x. not listed above
mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y');
+---------------------------------------------------------+
| DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y') |
+---------------------------------------------------------+
| Saturday October 1997 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
67
Database Management System (CS/IT 4th SEM) unit 5
+---------------------------------------------------------+
1 row in set (0.00 sec)
DAY(date)
The DAY() is a synonym for the DAYOFMONTH() function.
DAYNAME(date)
Returns the name of the weekday for date.
mysql> SELECT DAYNAME('1998-02-05');
+---------------------------------------------------------+
| DAYNAME('1998-02-05') |
+---------------------------------------------------------+
| Thursday |
+---------------------------------------------------------+
1 row in set (0.00 sec)
DAYOFMONTH(date)
Returns the day of the month for date, in the range 0 to 31.
mysql> SELECT DAYOFMONTH('1998-02-03');
+---------------------------------------------------------+
| DAYOFMONTH('1998-02-03') |
+---------------------------------------------------------+
| 3 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
DAYOFWEEK(date)
Returns the weekday index for date (1 = Sunday, 2 = Monday, ., 7 = Saturday). These index
values correspond to the ODBC standard.
mysql> SELECT DAYOFWEEK('1998-02-03');
+---------------------------------------------------------+
|DAYOFWEEK('1998-02-03') |
+---------------------------------------------------------+
| 3 |
68
Database Management System (CS/IT 4th SEM) unit 5
+---------------------------------------------------------+
1 row in set (0.00 sec)
DAYOFYEAR(date)
Returns the day of the year for date, in the range 1 to 366.
mysql> SELECT DAYOFYEAR('1998-02-03');
+---------------------------------------------------------+
| DAYOFYEAR('1998-02-03') |
+---------------------------------------------------------+
| 34 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
FROM_DAYS(N)
Given a day number N, returns a DATE value.
mysql> SELECT FROM_DAYS(729669);
+---------------------------------------------------------+
| FROM_DAYS(729669) |
+---------------------------------------------------------+
| 1997-10-07 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
69
Database Management System (CS/IT 4th SEM) unit 5
Note − Use FROM_DAYS() with caution on old dates. It is not intended for use with values
that precede the advent of the Gregorian calendar (1582).
FROM_UNIXTIME(unix_timestamp)
FROM_UNIXTIME(unix_timestamp,format)
Returns a representation of the unix_timestamp argument as a value in 'YYYY-MM-DD
HH:MM:SS or YYYYMMDDHHMMSS format, depending on whether the function is used in
a string or in a numeric context. The value is expressed in the current time zone. The
unix_timestamp argument is an internal timestamp values, which are produced by
the UNIX_TIMESTAMP() function.
If the format is given, the result is formatted according to the format string, which is used in the
same way as is listed in the entry for the DATE_FORMAT() function.
mysql> SELECT FROM_UNIXTIME(875996580);
+---------------------------------------------------------+
| FROM_UNIXTIME(875996580) |
+---------------------------------------------------------+
| 1997-10-04 22:23:00 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
HOUR(time)
Returns the hour for time. The range of the return value is 0 to 23 for time-of-day values.
However, the range of TIME values actually is much larger, so HOUR can return values greater
than 23.
mysql> SELECT HOUR('10:05:03');
+---------------------------------------------------------+
| HOUR('10:05:03') |
+---------------------------------------------------------+
| 10 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
LAST_DAY(date)
Takes a date or datetime value and returns the corresponding value for the last day of the month.
Returns NULL if the argument is invalid.
mysql> SELECT LAST_DAY('2003-02-05');
+---------------------------------------------------------+
| LAST_DAY('2003-02-05') |
70
Database Management System (CS/IT 4th SEM) unit 5
+---------------------------------------------------------+
| 2003-02-28 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
MAKEDATE(year,dayofyear)
Returns a date, given year and day-of-year values. The dayofyear value must be greater than 0
or the result will be NULL.
mysql> SELECT MAKEDATE(2001,31), MAKEDATE(2001,32);
+---------------------------------------------------------+
| MAKEDATE(2001,31), MAKEDATE(2001,32) |
+---------------------------------------------------------+
| '2001-01-31', '2001-02-01' |
+---------------------------------------------------------+
1 row in set (0.00 sec)
MAKETIME(hour,minute,second)
Returns a time value calculated from the hour, minute and second arguments.
mysql> SELECT MAKETIME(12,15,30);
+---------------------------------------------------------+
| MAKETIME(12,15,30) |
+---------------------------------------------------------+
| '12:15:30' |
+---------------------------------------------------------+
1 row in set (0.00 sec)
MICROSECOND(expr)
Returns the microseconds from the time or datetime expression (expr) as a number in the range
from 0 to 999999.
mysql> SELECT MICROSECOND('12:00:00.123456');
+---------------------------------------------------------+
71
Database Management System (CS/IT 4th SEM) unit 5
| MICROSECOND('12:00:00.123456') |
+---------------------------------------------------------+
| 123456 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
MINUTE(time)
Returns the minute for time, in the range 0 to 59.
mysql> SELECT MINUTE('98-02-03 10:05:03');
+---------------------------------------------------------+
| MINUTE('98-02-03 10:05:03') |
+---------------------------------------------------------+
| 5 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
MONTH(date)
Returns the month for date, in the range 0 to 12.
mysql> SELECT MONTH('1998-02-03')
+---------------------------------------------------------+
| MONTH('1998-02-03') |
+---------------------------------------------------------+
| 2 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
MONTHNAME(date)
Returns the full name of the month for a date.
mysql> SELECT MONTHNAME('1998-02-05');
+---------------------------------------------------------+
| MONTHNAME('1998-02-05') |
+---------------------------------------------------------+
| February |
+---------------------------------------------------------+
1 row in set (0.00 sec)
NOW()
72
Database Management System (CS/IT 4th SEM) unit 5
PERIOD_ADD(P,N)
Adds N months to a period P (in the format YYMM or YYYYMM). Returns a value in the
format YYYYMM. Note that the period argument P is not a date value.
mysql> SELECT PERIOD_ADD(9801,2);
+---------------------------------------------------------+
| PERIOD_ADD(9801,2) |
+---------------------------------------------------------+
| 199803 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
PERIOD_DIFF(P1,P2)
Returns the number of months between periods P1 and P2. These periods P1 and P2 should be
in the format YYMM or YYYYMM. Note that the period arguments P1 and P2 are not date
values.
mysql> SELECT PERIOD_DIFF(9802,199703);
+---------------------------------------------------------+
| PERIOD_DIFF(9802,199703) |
+---------------------------------------------------------+
| 11 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
QUARTER(date)
Returns the quarter of the year for date, in the range 1 to 4.
mysql> SELECT QUARTER('98-04-01');
73
Database Management System (CS/IT 4th SEM) unit 5
+---------------------------------------------------------+
| QUARTER('98-04-01') |
+---------------------------------------------------------+
| 2 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
SECOND(time)
Returns the second for time, in the range 0 to 59.
mysql> SELECT SECOND('10:05:03');
+---------------------------------------------------------+
| SECOND('10:05:03') |
+---------------------------------------------------------+
| 3 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
SEC_TO_TIME(seconds)
Returns the seconds argument, converted to hours, minutes and seconds, as a value in
'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or
numeric context.
mysql> SELECT SEC_TO_TIME(2378);
+---------------------------------------------------------+
| SEC_TO_TIME(2378) |
+---------------------------------------------------------+
| 00:39:38 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
STR_TO_DATE(str,format)
This is the inverse of the DATE_FORMAT() function. It takes a string str and a format string
format. The STR_TO_DATE() function returns a DATETIME value if the format string
contains both date and time parts. Else, it returns a DATE or TIME value if the string contains
only date or time parts.
mysql> SELECT STR_TO_DATE('04/31/2004', '%m/%d/%Y');
+---------------------------------------------------------+
| STR_TO_DATE('04/31/2004', '%m/%d/%Y') |
+---------------------------------------------------------+
| 2004-04-31 |
+---------------------------------------------------------+
74
Database Management System (CS/IT 4th SEM) unit 5
SUBTIME(expr1,expr2)
The SUBTIME() function returns expr1 . expr2 expressed as a value in the same format as
expr1. The expr1 value is a time or a datetime expression, while the expr2 value is a time
expression.
mysql> SELECT SUBTIME('1997-12-31 23:59:59.999999',
-> '1 1:1:1.000002');
+---------------------------------------------------------+
| SUBTIME('1997-12-31 23:59:59.999999'... |
+---------------------------------------------------------+
| 1997-12-30 22:58:58.999997 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
SYSDATE()
Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or
YYYYMMDDHHMMSS format, depending on whether the function is used in a string or in a
numeric context.
75
Database Management System (CS/IT 4th SEM) unit 5
TIME(expr)
Extracts the time part of the time or datetime expression expr and returns it as a string.
mysql> SELECT TIME('2003-12-31 01:02:03');
+---------------------------------------------------------+
| TIME('2003-12-31 01:02:03') |
+---------------------------------------------------------+
| 01:02:03 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
TIMEDIFF(expr1,expr2)
The TIMEDIFF() function returns expr1 . expr2 expressed as a time value. These expr1 and
expr2 values are time or date-and-time expressions, but both must be of the same type.
mysql> SELECT TIMEDIFF('1997-12-31 23:59:59.000001',
-> '1997-12-30 01:01:01.000002');
+---------------------------------------------------------+
| TIMEDIFF('1997-12-31 23:59:59.000001'..... |
+---------------------------------------------------------+
| 46:58:57.999999 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
TIMESTAMP(expr), TIMESTAMP(expr1,expr2)
With a single argument, this function returns the date or datetime expression expr as a datetime
value. With two arguments, it adds the time expression expr2 to the date or datetime
expression expr1 and returns the result as a datetime value.
mysql> SELECT TIMESTAMP('2003-12-31');
+---------------------------------------------------------+
| TIMESTAMP('2003-12-31') |
+---------------------------------------------------------+
| 2003-12-31 00:00:00 |
+---------------------------------------------------------+
76
Database Management System (CS/IT 4th SEM) unit 5
TIMESTAMPADD(unit,interval,datetime_expr)
This function adds the integer expression interval to the date or datetime
expression datetime_expr. The unit for interval is given by the unit argument, which should be
one of the following values −
FRAC_SECOND
SECOND, MINUTE
HOUR, DAY
WEEK
MONTH
QUARTER or
YEAR
The unit value may be specified using one of the keywords as shown or with a prefix of
SQL_TSI_.
For example, DAY and SQL_TSI_DAY both are legal.
mysql> SELECT TIMESTAMPADD(MINUTE,1,'2003-01-02');
+---------------------------------------------------------+
| TIMESTAMPADD(MINUTE,1,'2003-01-02') |
+---------------------------------------------------------+
| 2003-01-02 00:01:00 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)
Returns the integer difference between the date or datetime expressions datetime_expr1 and
datetime_expr2. The unit for the result is given by the unit argument. The legal values for the
unit are the same as those listed in the description of the TIMESTAMPADD() function.
mysql> SELECT TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01');
+---------------------------------------------------------+
| TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01') |
+---------------------------------------------------------+
| 3 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
TIME_FORMAT(time,format)
77
Database Management System (CS/IT 4th SEM) unit 5
This function is used like the DATE_FORMAT() function, but the format string may contain
format specifiers only for hours, minutes and seconds.
If the time value contains an hour part that is greater than 23, the %H and %k hour format
specifiers produce a value larger than the usual range of 0 to 23. The other hour format
specifiers produce the hour value modulo 12.
mysql> SELECT TIME_FORMAT('100:00:00', '%H %k %h %I %l');
+---------------------------------------------------------+
| TIME_FORMAT('100:00:00', '%H %k %h %I %l') |
+---------------------------------------------------------+
| 100 100 04 04 4 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
TIME_TO_SEC(time)
Returns the time argument converted to seconds.
mysql> SELECT TIME_TO_SEC('22:23:00');
+---------------------------------------------------------+
| TIME_TO_SEC('22:23:00') |
+---------------------------------------------------------+
| 80580 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
TO_DAYS(date)
Given a date, returns a day number (the number of days since year 0).
mysql> SELECT TO_DAYS(950501);
+---------------------------------------------------------+
| TO_DAYS(950501) |
+---------------------------------------------------------+
| 728779 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
UNIX_TIMESTAMP(), UNIX_TIMESTAMP(date)
If called with no argument, this function returns a Unix timestamp (seconds since '1970-01-01
00:00:00' UTC) as an unsigned integer. If UNIX_TIMESTAMP() is called with a date
argument, it returns the value of the argument as seconds since '1970-01-01 00:00:00' UTC.
date may be a DATE string, a DATETIME string, a TIMESTAMP, or a number in the format
YYMMDD or YYYYMMDD.
78
Database Management System (CS/IT 4th SEM) unit 5
UTC_DATE, UTC_DATE()
Returns the current UTC date as a value in 'YYYY-MM-DD' or YYYYMMDD format,
depending on whether the function is used in a string or numeric context.
mysql> SELECT UTC_DATE(), UTC_DATE() + 0;
+---------------------------------------------------------+
| UTC_DATE(), UTC_DATE() + 0 |
+---------------------------------------------------------+
| 2003-08-14, 20030814 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
UTC_TIME, UTC_TIME()
Returns the current UTC time as a value in 'HH:MM:SS' or HHMMSS format, depending on
whether the function is used in a string or numeric context.
mysql> SELECT UTC_TIME(), UTC_TIME() + 0;
+---------------------------------------------------------+
| UTC_TIME(), UTC_TIME() + 0 |
+---------------------------------------------------------+
| 18:07:53, 180753 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
UTC_TIMESTAMP, UTC_TIMESTAMP()
Returns the current UTC date and time as a value in 'YYYY-MM-DD HH:MM:SS' or in a
YYYYMMDDHHMMSS format, depending on whether the function is used in a string or in a
numeric context.
79
Database Management System (CS/IT 4th SEM) unit 5
WEEK(date[,mode])
This function returns the week number for date. The two-argument form of WEEK() allows you
to specify whether the week starts on a Sunday or a Monday and whether the return value
should be in the range from 0 to 53 or from 1 to 53. If the mode argument is omitted, the value
of the default_week_format system variable is used
80
Database Management System (CS/IT 4th SEM) unit 5
| WEEK('1998-02-20') |
+---------------------------------------------------------+
| 7 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
WEEKDAY(date)
WEEKOFYEAR(date)
Returns the calendar week of the date as a number in the range from 1 to 53. WEEKOFYEAR()
is a compatibility function that is equivalent to WEEK(date,3).
mysql> SELECT WEEKOFYEAR('1998-02-20');
+---------------------------------------------------------+
| WEEKOFYEAR('1998-02-20') |
+---------------------------------------------------------+
| 8 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
YEAR(date)
Returns the year for date, in the range 1000 to 9999, or 0 for the .zero. date.
mysql> SELECT YEAR('98-02-03');
+---------------------------------------------------------+
| YEAR('98-02-03') |
+---------------------------------------------------------+
| 1998 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
YEARWEEK(date), YEARWEEK(date,mode)
81
Database Management System (CS/IT 4th SEM) unit 5
Returns the year and the week for a date. The mode argument works exactly like the mode
argument to the WEEK() function. The year in the result may be different from the year in the
date argument for the first and the last week of the year.
mysql> SELECT YEARWEEK('1987-01-01');
+---------------------------------------------------------+
| YEAR('98-02-03')YEARWEEK('1987-01-01') |
+---------------------------------------------------------+
| 198653 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
Note − The week number is different from what the WEEK() function would return (0) for
optional arguments 0 or 1, as WEEK() then returns the week in the context of the given year.
82
Database Management System (CS/IT 4th SEM) unit 5
A field with a NULL value is a field with no value. It is very important to understand that a
NULL value is different than a zero value or a field that contains spaces.
Syntax
Here, NOT NULL signifies that column should always accept an explicit value of the given
data type. There are two columns where we did not use NOT NULL, which means these
columns could be NULL.
A field with a NULL value is the one that has been left blank during the record creation.
Example
The NULL value can cause problems when selecting data. However, because when comparing
an unknown value to any other value, the result is always unknown and not included in the
results. You must use the IS NULL or IS NOT NULL operators to check for a NULL value.
Consider the following CUSTOMERS table having the records as shown below.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
83
Database Management System (CS/IT 4th SEM) unit 5
84