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

MySQL 2

The document provides a comprehensive guide on SQL commands and operations, including database and table creation, data manipulation, and various SQL functions. It covers essential concepts such as SELECT statements, JOIN operations, and aggregate functions, along with examples for clarity. Additionally, it explains string functions and operators used for data querying and manipulation.

Uploaded by

ares.g1202
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

MySQL 2

The document provides a comprehensive guide on SQL commands and operations, including database and table creation, data manipulation, and various SQL functions. It covers essential concepts such as SELECT statements, JOIN operations, and aggregate functions, along with examples for clarity. Additionally, it explains string functions and operators used for data querying and manipulation.

Uploaded by

ares.g1202
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 25

Notes:

show databases;
drop database -Database Name- //Delete a database

1. Create A Database
create database -Name-;

2. Table Creation
use -database -Name-; // To state the database which will be used
create table -Table Name-(attributes of the table) //e.g. create table
user(id int(11) primary key, name varchar(30) not null, email varchar(30) not
null);
show tables; //show existing tables in the current database
desc -Table Name-; //show how the table is created

3. Table Manipulation
insert into -Table Name- values(attribute values); //e.g. insert into
user values("1","Mark","[email protected]");
select * from -Table Name-; //show the table and the attributes e.g.
select * from user;
update set -Table Name- set -What to change- where -Number-; //e.g.
update user set name="Jake" where id="1";
alter table -Table Name- add column -Attribute-; //e.g. alter table
user add column password varchar(30) not null;
delete -Table Name- where -What to delete-; //e.g. delete from user
where id="1";

4. AND, OR, NOT


Basis Structure: Select -Condition- From -Table Name- Where -Condition-
OR/AND/NOT -Condition-
SELECT * FROM Customers WHERE Country = 'Germany' AND City =
'Berlin'; //Show only where conditions are met (Ciy and COuntry)
SELECT * FROM Customers WHERE Country = 'Germany' AND (City = 'Berlin'
OR City = 'Stuttgart');
SELECT * FROM Customers WHERE NOT Country = 'Germany';
SELECT * FROM Customers WHERE NOT Country = 'Germany' AND NOT Country =
'USA';

5. ORDER BY - The ORDER BY keyword is used to sort the result-set in


ascending or descending order.
Basic Structure: Select -Condition- From -Table Name- OrDER BY -Column-
SELECT * FROM Customers ORDER BY Country;
SELECT * FROM Customers ORDER BY Country DESC;
SELECT * FROM Customers ORDER BY Country, CustomerName;
SELECT * FROM Customers ORDER BY Country ASC, CustomerName DESC;

6. INSERT INTO - The INSERT INTO statement is used to insert new records in a
table.
Basic Structure(Specified): INSERT INTO table_name (column1, column2,
column3, ...) VALUES (value1, value2, value3, ...);
Basic Structure(All Column): INSERT INTO table_name VALUES (value1,
value2, value3, ...);

7. NULL - A field with a NULL value is a field with no value.


Basic Structure: SELECT column_names FROM table_name WHERE column_name
IS NOT NULL;
- Help Find where there is null or no null valus.
SELECT CustomerName, ContactName, Address FROM Customers WHERE Address
IS NULL;
SELECT CustomerName, ContactName, Address FROM Customers WHERE Address
IS NOT NULL;

8. LIMT - The LIMIT clause is used to specify the number of records to


return.
Basic Structure: SELECT column_name(s) FROM table_name WHERE condition
LIMIT number;
SELECT * FROM Customers LIMIT 3; //Shows Only 3
SELECT * FROM Customers LIMIT 3 OFFSET 3; //Ignores the first 3(1,2,3)
then shows the next 3 (4,5,6)
SELECT * FROM Customers WHERE Country='Germany' LIMIT 3;

9. MIN, MAX
Basic Structure: SELECT MIN(column_name) FROM table_name WHERE
condition;
SELECT MIN(Price) AS SmallestPrice FROM Products;
SELECT MAX(Price) AS SmallestPrice FROM Products;

10. AVG, COUNT, SUM


Basic Structure: SELECT COUNT/AVG/SUM(column_name) FROM table_name
WHERE condition;
SELECT COUNT(ProductID) FROM Products;
SELECT AVG(Price) FROM Products;
SELECT SUM(Quantity) FROM OrderDetails;

11. LIKE - The LIKE operator is used in a WHERE clause to search for a
specified pattern in a column.
Basic Structure: SELECT column1, column2, ... FROM table_name WHERE
columnN LIKE pattern;
- The percent sign (%) represents zero, one, or multiple characters
- The underscore sign (_) represents one, single character
SELECT * FROM Customers WHERE CustomerName LIKE 'a%'; //Starting with
"a"
SELECT * FROM Customers WHERE CustomerName LIKE '%a'; //Ending with "a"
SELECT * FROM Customers WHERE CustomerName LIKE '%or%'; //Have "or" in
any position
SELECT * FROM Customers WHERE CustomerName LIKE '_r%'; //Have "r" as
the second letter
SELECT * FROM Customers WHERE CustomerName LIKE 'a__%'; //Starts with
"a" and are at least 3 characters in length
SELECT * FROM Customers WHERE ContactName LIKE 'a%o'; //Start with "a"
ends with "o"
SELECT * FROM Customers WHERE CustomerName NOT LIKE 'a%'; //No Letter
"a"

12. IN - The IN operator allows you to specify multiple values in a WHERE


clause.
Basic Structure: SELECT column_name(s) FROM table_name WHERE
column_name IN (value1, value2, ...);
SELECT * FROM Customers WHERE Country IN ('Germany', 'France', 'UK');
SELECT * FROM Customers WHERE Country NOT IN ('Germany', 'France',
'UK');
SELECT * FROM Customers WHERE Country IN (SELECT Country FROM
Suppliers); //Selects all customers that are from the same countries as the
suppliers

13. BETWEEN - The BETWEEN operator selects values within a given range. The
values can be numbers, text, or dates.
Basic Structure: SELECT column_name(s) FROM table_name WHERE
column_name BETWEEN value1 AND value2;
SELECT * FROM Products WHERE Price BETWEEN 10 AND 20;
SELECT * FROM Products WHERE Price NOT BETWEEN 10 AND 20;

14. ALIAS - Aliases are used to give a table, or a column in a table, a


temporary name.
Basic Structure: SELECT column_name AS alias_name FROM table_name;
SELECT CustomerID AS ID, CustomerName AS Customer FROM Customers;
SELECT CustomerName, CONCAT_WS(', ', Address, PostalCode, City,
Country) AS Address FROM Customers;

15 JOIN - A JOIN clause is used to combine rows from two or more tables,
based on a related column between them.
Basic Structure: SELECT Orders.OrderID, Customers.CustomerName,
Orders.OrderDate FROM Orders INNER JOIN Customers ON
Orders.CustomerID=Customers.CustomerID;
INNER JOIN: Returns records that have matching values in both tables
SELECT Orders.OrderID, Customers.CustomerName FROM Orders INNER
JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
3 Tables: SELECT Orders.OrderID, Customers.CustomerName,
Shippers.ShipperName FROM ((Orders INNER JOIN Customers ON Orders.CustomerID =
Customers.CustomerID) INNER JOIN Shippers ON Orders.ShipperID =
Shippers.ShipperID);
LEFT JOIN: Returns all records from the left table, and the matched
records from the right table
SELECT Customers.CustomerName, Orders.OrderID FROM Customers LEFT
JOIN Orders ON Customers.CustomerID = Orders.CustomerID ORDER BY
Customers.CustomerName;
RIGHT JOIN: Returns all records from the right table, and the matched
records from the left table
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID ORDER
BY Orders.OrderID;
CROSS JOIN: Returns all records from both tables
SELECT Customers.CustomerName, Orders.OrderID FROM Customers
CROSS JOIN Orders;
SELF JOIN
SELECT A.CustomerName AS CustomerName1, B.CustomerName AS
CustomerName2, A.City FROM Customers A, Customers B WHERE A.CustomerID <>
B.CustomerID AND A.City = B.City ORDER BY A.City;

16. UNION - The UNION operator is used to combine the result-set of two or
more SELECT statements.
Basic Structure: SELECT column_name(s) FROM table1 UNION SELECT
column_name(s) FROM table2;
Basic Structure(Allow Duplicates): SELECT column_name(s) FROM table1
UNION ALL SELECT column_name(s) FROM table2;
SELECT City FROM Customers UNION SELECT City FROM Suppliers ORDER BY
City;
SELECT City FROM Customers UNION ALL SELECT City FROM Suppliers ORDER
BY City;

17. GROUP BY - The GROUP BY statement groups rows that have the same values
into summary rows, like "find the number of customers in each country".
Basic Structure - SELECT column_name(s) FROM table_name WHERE condition
GROUP BY column_name(s) ORDER BY column_name(s);
SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country;
18. HAVING - The HAVING clause was added to SQL because the WHERE keyword
cannot be used with aggregate functions.
Basic Structure - SELECT column_name(s) FROM table_name WHERE condition
GROUP BY column_name(s) HAVING condition ORDER BY column_name(s);
SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country
HAVING COUNT(CustomerID) > 5;

19. EXISTS - The EXISTS operator is used to test for the existence of any
record in a subquery.
Basic Structure - SELECT column_name(s) FROM table_name WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
SELECT SupplierName FROM Suppliers WHERE EXISTS (SELECT ProductName
FROM Products WHERE Products.SupplierID = Suppliers.supplierID AND Price < 20);

20. ANY, ALL - The ANY and ALL operators allow you to perform a comparison
between a single column value and a range of other values.
Basic Structure(ANY) - SELECT column_name(s) FROM table_name WHERE
column_name operator ANY SELECT column_name FROM table_name WHERE condition);
Basic Structure(ALL) - SELECT ALL column_name(s) FROM table_name WHERE
condition;
SELECT ProductName FROM Products WHERE ProductID = ANY (SELECT
ProductID FROM OrderDetails WHERE Quantity = 10);
SELECT ALL ProductName FROM Products WHERE TRUE;
SELECT ProductName FROM Products WHERE ProductID = ALL (SELECT
ProductID FROM OrderDetails WHERE Quantity = 10);

21. INSERT INTO SELECT - The INSERT INTO SELECT statement copies data from
one table and inserts it into another table. With Matching data types and target
tables
Basic Structure - INSERT INTO table2 SELECT * FROM table1 WHERE
condition;
Basic Structure - INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ... FROM table1 WHERE condition; //Selected
INSERT INTO Customers (CustomerName, City, Country) SELECT
SupplierName, City, Country FROM Suppliers;
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country) SELECT SupplierName, ContactName, Address, City, PostalCode,
Country FROM Suppliers;

22. CASE - The CASE statement goes through conditions and returns a value
when the first condition is met (like an if-then-else statement). So, once a
condition is true, it will stop reading and return the result. If no conditions are
true, it returns the value in the ELSE clause.
Basic Structure - CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;

SELECT OrderID, Quantity,


CASE
WHEN Quantity > 30 THEN 'The quantity is greater than 30'
WHEN Quantity = 30 THEN 'The quantity is 30'
ELSE 'The quantity is under 30'
END AS QuantityText
FROM OrderDetails;
23. COMMENTS
-- --, /* */

24. STRING FUNCTIONS - Example (Output)


ASCII - Returns the ASCII value for the specific character
Syntax: ASCII(character)
Example: ASCII('A') (65)

CHAR_LENGTH - Returns the length of a string (in characters)


Syntax: CHAR_LENGTH(string)
Example: CHAR_LENGTH('Hello') (5)

CHARACTER_LENGTH - Returns the length of a string (in characters)


Syntax: CHARACTER_LENGTH(string)
Example: CHARACTER_LENGTH('Hello') (5)

CONCAT - Adds two or more expressions together


Syntax: CONCAT(string1, string2, ...)
Example: CONCAT('Hello', ' ', 'World') ('Hello World')

CONCAT_WS - Adds two or more expressions together with a separator


Syntax: CONCAT_WS(separator, string1, string2, ...)
Example: CONCAT_WS('-', '2024', '01', '11') ('2024-01-11')

FIELD - Returns the index position of a value in a list of values


Syntax: FIELD(value, val1, val2, ...)
Example: FIELD('B', 'A', 'B', 'C', 'D') (2)

FIND_IN_SET - Returns the position of a string within a list of strings

Syntax: FIND_IN_SET(string, string_list)


Example: FIND_IN_SET('b', 'a,b,c,d') (2)

FORMAT - Formats a number to a format like "#,###,###.##", rounded to a


specified number of decimal places
Syntax: FORMAT(number, decimal_places)
Example: FORMAT(1234567.89, 2) ('1,234,567.89')

INSERT - Inserts a string within a string at the specified position and


for a certain number of characters
Syntax: INSERT(original_string, position, length, new_string)
Example: INSERT('Hello World', 7, 5, 'Universe') ('Hello Universe')

INSTR - Returns the position of the first occurrence of a string in


another string
Syntax: INSTR(string, substring)
Example: INSTR('Hello World', 'World') (7)

LCASE - Converts a string to lower-case


Syntax: LCASE(string)
Example: LCASE('HELLO') ('hello')

LEFT - Extracts a number of characters from a string (starting from


left)
Syntax: LEFT(string, length)
Example: LEFT('Hello World', 5) ('Hello')

LENGTH - Returns the length of a string (in bytes)


Syntax: LENGTH(string)
Example: LENGTH('Hello') (5)

LOCATE - Returns the position of the first occurrence of a substring in


a string
Syntax: LOCATE(substring, string)
Example: LOCATE('World', 'Hello World') (7)

LOWER - Converts a string to lower-case


Syntax: LOWER(string)
Example: LOWER('HELLO') ('hello')

LPAD - Left-pads a string with another string, to a certain length


Syntax: LPAD(string, length, pad_string)
Example: LPAD('Hello', 10, '*') ('*****Hello')

LTRIM - Removes leading spaces from a string


Syntax: LTRIM(string)
Example: LTRIM(' Hello') ('Hello')

MID - Extracts a substring from a string (starting at any position)


Syntax: MID(string, position, length)
Example: MID('Hello World', 7, 5) ('World')

POSITION - Returns the position of the first occurrence of a substring


in a string
Syntax: POSITION(substring IN string)
Example: POSITION('World' IN 'Hello World') (7)

REPEAT - Repeats a string as many times as specified


Syntax: REPEAT(string, count)
Example: REPEAT('Hello', 3) ('HelloHelloHello')

REPLACE - Replaces all occurrences of a substring within a string, with


a new substring
Syntax: REPLACE(string, from_string, to_string)
Example: REPLACE('Hello World', 'World', 'Universe') ('Hello Universe')

REVERSE - Reverses a string and returns the result


Syntax: REVERSE(string)
Example: REVERSE('Hello') ('olleH')

RIGHT - Extracts a number of characters from a string (starting from


right)
Syntax: RIGHT(string, length)
Example: RIGHT('Hello World', 5) ('World')

RPAD - Right-pads a string with another string, to a certain length


Syntax: RPAD(string, length, pad_string)
Example: RPAD('Hello', 10, '*') ('Hello*****')

RTRIM - Removes trailing spaces from a string


Syntax: RTRIM(string)
Example: RTRIM('Hello ') ('Hello')

SPACE - Returns a string of the specified number of space characters


Syntax: SPACE(number)
Example: SPACE(5) (' ')
STRCMP - Compares two strings
Syntax: STRCMP(string1, string2)
Example: STRCMP('Hello', 'hello') (-1)

SUBSTR - Extracts a substring from a string (starting at any position)

Syntax: SUBSTR(string, position, length)


Example: SUBSTR('Hello World', 7, 5) ('World')

SUBSTRING - Extracts a substring from a string (starting at any


position)
Syntax: SUBSTRING(string, position, length)
Example: SUBSTRING('Hello World', 1, 5) ('Hello')

SUBSTRING_INDEX - Returns a substring of a string before a specified


number of delimiter occurrences
Syntax: SUBSTRING_INDEX(string, delimiter, count)
Example: SUBSTRING_INDEX('www.example.com', '.', 2) ('www.example')

TRIM - Removes leading and trailing spaces from a string


Syntax: TRIM(string)
Example: TRIM(' Hello ') ('Hello')

UCASE - Converts a string to upper-case


Syntax: UCASE(string)
Example: UCASE('hello') ('HELLO')

UPPER - Converts a string to upper-case


Syntax: UPPER(string)
Example: UPPER('hello') ('HELLO')

25. NUMERIC FUNCTIONS


ABS - Returns the absolute value of a number
Syntax: ABS(number)
Example: ABS(-10) (10)

ACOS - Returns the arc cosine of a number


Syntax: ACOS(number)
Example: ACOS(0.5) (1.047197551)

ASIN - Returns the arc sine of a number


Syntax: ASIN(number)
Example: ASIN(0.5) (0.523598775)

ATAN - Returns the arc tangent of one or two numbers


Syntax: ATAN(number) or ATAN(y, x)
Example: ATAN(1) (0.785398163)

ATAN2 - Returns the arc tangent of two numbers


Syntax: ATAN2(y, x)
Example: ATAN2(1, 1) (0.785398163)

AVG - Returns the average value of an expression


Syntax: AVG(expression)
Example: AVG(2, 4, 6) (4)

CEIL - Returns the smallest integer value that is >= to a number


Syntax: CEIL(number)
Example: CEIL(4.2) (5)
CEILING - Returns the smallest integer value that is >= to a number
Syntax: CEILING(number)
Example: CEILING(4.2) (5)

COS - Returns the cosine of a number


Syntax: COS(number)
Example: COS(0) (1)

COT - Returns the cotangent of a number


Syntax: COT(number)
Example: COT(1) (0.642092616)

COUNT - Returns the number of records returned by a select query


Syntax: COUNT(expression)
Example: COUNT(*) (returns the number of rows)

DEGREES - Converts a value in radians to degrees


Syntax: DEGREES(radians)
Example: DEGREES(PI()) (180)

DIV - Used for integer division


Syntax: number1 DIV number2
Example: 9 DIV 4 (2)

EXP - Returns e raised to the power of a specified number


Syntax: EXP(number)
Example: EXP(1) (2.718281828)

FLOOR - Returns the largest integer value that is <= to a number


Syntax: FLOOR(number)
Example: FLOOR(4.7) (4)

GREATEST - Returns the greatest value of the list of arguments


Syntax: GREATEST(value1, value2, ...)
Example: GREATEST(10, 20, 5) (20)

LEAST - Returns the smallest value of the list of arguments


Syntax: LEAST(value1, value2, ...)
Example: LEAST(10, 20, 5) (5)

LN - Returns the natural logarithm of a number


Syntax: LN(number)
Example: LN(2.718281828) (1)

LOG - Returns the natural logarithm of a number, or the logarithm of a


number to a specified base
Syntax: LOG(number) or LOG(base, number)
Example: LOG(100) (4.605170186)

LOG10 - Returns the natural logarithm of a number to base 10


Syntax: LOG10(number)
Example: LOG10(100) (2)

LOG2 - Returns the natural logarithm of a number to base 2


Syntax: LOG2(number)
Example: LOG2(8) (3)

MAX - Returns the maximum value in a set of values


Syntax: MAX(expression)
Example: MAX(1, 5, 3) (5)

MIN - Returns the minimum value in a set of values


Syntax: MIN(expression)
Example: MIN(1, 5, 3) (1)

MOD - Returns the remainder of a number divided by another number


Syntax: MOD(number1, number2)
Example: MOD(10, 3) (1)

PI - Returns the value of PI


Syntax: PI()
Example: PI() (3.141592654)

POW - Returns the value of a number raised to the power of another


number
Syntax: POW(base, exponent)
Example: POW(2, 3) (8)

POWER - Returns the value of a number raised to the power of another


number
Syntax: POWER(base, exponent)
Example: POWER(2, 3) (8)

RADIANS - Converts a degree value into radians


Syntax: RADIANS(degrees)
Example: RADIANS(180) (3.141592654)

RAND - Returns a random number


Syntax: RAND()
Example: RAND() (random number)

ROUND - Rounds a number to a specified number of decimal places


Syntax: ROUND(number, decimal_places)
Example: ROUND(123.456, 2) (123.46)

SIGN - Returns the sign of a number


Syntax: SIGN(number)
Example: SIGN(-5) (-1)

SIN - Returns the sine of a number


Syntax: SIN(number)
Example: SIN(PI()/2) (1)

SQRT - Returns the square root of a number


Syntax: SQRT(number)
Example: SQRT(9) (3)

SUM - Calculates the sum of a set of values


Syntax: SUM(expression)
Example: SUM(10, 20, 30) (60)

TAN - Returns the tangent of a number


Syntax: TAN(number)
Example: TAN(PI()/4) (1)

TRUNCATE - Truncates a number to the specified number of decimal places


Syntax: TRUNCATE(number, decimal_places)
Example: TRUNCATE(123.456, 2) (123.45)

25. DATE FUNCTIONS


ADDDATE - Adds a time/date interval to a date and then returns the date
Syntax: ADDDATE(date, INTERVAL expr type)
Example: ADDDATE('2023-01-01', INTERVAL 10 DAY) ('2023-01-11')

ADDTIME - Adds a time interval to a time/datetime and then returns the


time/datetime
Syntax: ADDTIME(time, expr)
Example: ADDTIME('10:00:00', '02:30:00') ('12:30:00')

CURDATE - Returns the current date


Syntax: CURDATE()
Example: CURDATE() ('2025-01-11')

CURRENT_DATE - Returns the current date


Syntax: CURRENT_DATE()
Example: CURRENT_DATE() ('2025-01-11')

CURRENT_TIME - Returns the current time


Syntax: CURRENT_TIME()
Example: CURRENT_TIME() ('14:32:10')

CURRENT_TIMESTAMP - Returns the current date and time


Syntax: CURRENT_TIMESTAMP()
Example: CURRENT_TIMESTAMP() ('2025-01-11 14:32:10')

CURTIME - Returns the current time


Syntax: CURTIME()
Example: CURTIME() ('14:32:10')

DATE - Extracts the date part from a datetime expression


Syntax: DATE(datetime)
Example: DATE('2025-01-11 14:32:10') ('2025-01-11')

DATEDIFF - Returns the number of days between two date values


Syntax: DATEDIFF(date1, date2)
Example: DATEDIFF('2025-01-11', '2025-01-01') (10)

DATE_ADD - Adds a time/date interval to a date and then returns the


date
Syntax: DATE_ADD(date, INTERVAL expr type)
Example: DATE_ADD('2023-01-01', INTERVAL 10 DAY) ('2023-01-11')

DATE_FORMAT - Formats a date


Syntax: DATE_FORMAT(date, format)
Example: DATE_FORMAT('2025-01-11', '%Y/%m/%d') ('2025/01/11')

DATE_SUB - Subtracts a time/date interval from a date and then returns


the date
Syntax: DATE_SUB(date, INTERVAL expr type)
Example: DATE_SUB('2025-01-11', INTERVAL 10 DAY) ('2025-01-01')

DAY - Returns the day of the month for a given date


Syntax: DAY(date)
Example: DAY('2025-01-11') (11)

DAYNAME - Returns the weekday name for a given date


Syntax: DAYNAME(date)
Example: DAYNAME('2025-01-11') ('Saturday')

DAYOFMONTH - Returns the day of the month for a given date


Syntax: DAYOFMONTH(date)
Example: DAYOFMONTH('2025-01-11') (11)

DAYOFWEEK - Returns the weekday index for a given date


Syntax: DAYOFWEEK(date)
Example: DAYOFWEEK('2025-01-11') (7)

DAYOFYEAR - Returns the day of the year for a given date


Syntax: DAYOFYEAR(date)
Example: DAYOFYEAR('2025-01-11') (11)

EXTRACT - Extracts a part from a given date


Syntax: EXTRACT(unit FROM date)
Example: EXTRACT(YEAR FROM '2025-01-11') (2025)

FROM_DAYS - Returns a date from a numeric date value


Syntax: FROM_DAYS(days)
Example: FROM_DAYS(738204) ('2025-01-11')

HOUR - Returns the hour part for a given date


Syntax: HOUR(time)
Example: HOUR('14:32:10') (14)

LAST_DAY - Extracts the last day of the month for a given date
Syntax: LAST_DAY(date)
Example: LAST_DAY('2025-01-11') ('2025-01-31')

LOCALTIME - Returns the current date and time


Syntax: LOCALTIME()
Example: LOCALTIME() ('2025-01-11 14:32:10')

LOCALTIMESTAMP - Returns the current date and time


Syntax: LOCALTIMESTAMP()
Example: LOCALTIMESTAMP() ('2025-01-11 14:32:10')

MAKEDATE - Creates and returns a date based on a year and a number of


days value
Syntax: MAKEDATE(year, day_of_year)
Example: MAKEDATE(2025, 11) ('2025-01-11')

MAKETIME - Creates and returns a time based on an hour, minute, and


second value
Syntax: MAKETIME(hour, minute, second)
Example: MAKETIME(14, 32, 10) ('14:32:10')

MICROSECOND - Returns the microsecond part of a time/datetime


Syntax: MICROSECOND(time)
Example: MICROSECOND('14:32:10.123456') (123456)

MINUTE - Returns the minute part of a time/datetime


Syntax: MINUTE(time)
Example: MINUTE('14:32:10') (32)

MONTH - Returns the month part for a given date


Syntax: MONTH(date)
Example: MONTH('2025-01-11') (1)

MONTHNAME - Returns the name of the month for a given date


Syntax: MONTHNAME(date)
Example: MONTHNAME('2025-01-11') ('January')

NOW - Returns the current date and time


Syntax: NOW()
Example: NOW() ('2025-01-11 14:32:10')

PERIOD_ADD - Adds a specified number of months to a period


Syntax: PERIOD_ADD(period, months)
Example: PERIOD_ADD(202501, 2) (202503)

PERIOD_DIFF - Returns the difference between two periods


Syntax: PERIOD_DIFF(period1, period2)
Example: PERIOD_DIFF(202501, 202401) (12)

QUARTER - Returns the quarter of the year for a given date value
Syntax: QUARTER(date)
Example: QUARTER('2025-01-11') (1)

SECOND - Returns the seconds part of a time/datetime


Syntax: SECOND(time)
Example: SECOND('14:32:10') (10)

SEC_TO_TIME - Returns a time value based on the specified seconds


Syntax: SEC_TO_TIME(seconds)
Example: SEC_TO_TIME(3661) ('01:01:01')

STR_TO_DATE - Returns a date based on a string and a format


Syntax: STR_TO_DATE(str, format)
Example: STR_TO_DATE('11-01-2025', '%d-%m-%Y') ('2025-01-11')

SUBDATE - Subtracts a time/date interval from a date and then returns


the date
Syntax: SUBDATE(date, INTERVAL expr type)
Example: SUBDATE('2025-01-11', INTERVAL 10 DAY) ('2025-01-01')

SUBTIME - Subtracts a time interval from a datetime and then returns


the time/datetime
Syntax: SUBTIME(datetime, expr)
Example: SUBTIME('14:32:10', '01:10:00') ('13:22:10')

SYSDATE - Returns the current date and time


Syntax: SYSDATE()
Example: SYSDATE() ('2025-01-11 14:32:10')

TIME - Extracts the time part from a given time/datetime


Syntax: TIME(datetime)
Example: TIME('2025-01-11 14:32:10') ('14:32:10')

TIME_FORMAT - Formats a time by a specified format


Syntax: TIME_FORMAT(time, format)
Example: TIME_FORMAT('14:32:10', '%h:%i %p') ('02:32 PM')

TIME_TO_SEC - Converts a time value into seconds


Syntax: TIME_TO_SEC(time)
Example: TIME_TO_SEC('01:01:01') (3661)
TIMEDIFF - Returns the difference between two time/datetime expressions
Syntax: TIMEDIFF(datetime1, datetime2)
Example: TIMEDIFF('14:32:10', '12:00:00') ('02:32:10')

TIMESTAMP - Returns a datetime value based on a date or datetime value


Syntax: TIMESTAMP(date, time)
Example: TIMESTAMP('2025-01-11', '14:32:10') ('2025-01-11 14:32:10')

TO_DAYS - Returns the number of days between a date and date "0000-00-
00"
Syntax: TO_DAYS(date)
Example: TO_DAYS('2025-01-11') (738204)

WEEK - Returns the week number for a given date


Syntax: WEEK(date)
Example: WEEK('2025-01-11') (2)

WEEKDAY - Returns the weekday number for a given date


Syntax: WEEKDAY(date)
Example: WEEKDAY('2025-01-11') (5)

WEEKOFYEAR - Returns the week number for a given date


Syntax: WEEKOFYEAR(date)
Example: WEEKOFYEAR('2025-01-11') (2)

YEAR - Returns the year part for a given date


Syntax: YEAR(date)
Example: YEAR('2025-01-11') (2025)

YEARWEEK - Returns the year and week number for a given date
Syntax: YEARWEEK(date)
Example: YEARWEEK('2025-01-11') (202502)

26. ADVANCE FUNCTIONS


BIN Returns a binary representation of a number
Syntax
BIN(number)
Example
SELECT BIN(5); -- Output: 101

BINARY Converts a value to a binary string


Syntax
BINARY value
Example
SELECT BINARY 'abc'; -- Output: 'abc' as binary

CASE Goes through conditions and returns a value when the first
condition is met
Syntax
CASE WHEN condition THEN result [WHEN condition THEN result] ... [ELSE
result] END
Example
SELECT CASE WHEN 1 > 0 THEN 'True' ELSE 'False' END; -- Output: True

CAST Converts a value (of any type) into a specified datatype


Syntax
CAST(value AS datatype)
Example
SELECT CAST(12.34 AS SIGNED); -- Output: 12

COALESCE Returns the first non-null value in a list


Syntax
COALESCE(value1, value2, ...)
Example
SELECT COALESCE(NULL, NULL, 'First non-null'); -- Output: First non-
null

CONNECTION_ID Returns the unique connection ID for the current


connection
Syntax
CONNECTION_ID()
Example
SELECT CONNECTION_ID(); -- Output: (connection ID)

CONV Converts a number from one numeric base system to another


Syntax
CONV(number, from_base, to_base)
Example
SELECT CONV(15, 10, 2); -- Output: 1111

CONVERT Converts a value into the specified datatype or character


set
Syntax
CONVERT(value, datatype) or CONVERT(value USING charset)
Example
SELECT CONVERT('abc' USING utf8mb4); -- Output: 'abc' in utf8mb4

CURRENT_USER Returns the user name and host name for the current
MySQL account
Syntax
CURRENT_USER()
Example
SELECT CURRENT_USER(); -- Output: user@host

DATABASE Returns the name of the current database


Syntax
DATABASE()
Example
SELECT DATABASE(); -- Output: (database name)

IF Returns a value if a condition is TRUE, or another value if a


condition is FALSE
Syntax
IF(condition, value_if_true, value_if_false)
Example
SELECT IF(1 > 0, 'Yes', 'No'); -- Output: Yes

IFNULL Returns a specified value if the expression is NULL,


otherwise returns the expression
Syntax
IFNULL(expression, value)
Example
SELECT IFNULL(NULL, 'Default'); -- Output: Default

ISNULL Returns 1 or 0 depending on whether an expression is NULL


Syntax
ISNULL(expression)
Example
SELECT ISNULL(NULL); -- Output: 1

LAST_INSERT_ID Returns the AUTO_INCREMENT id of the last row


inserted or updated
Syntax
LAST_INSERT_ID()
Example
SELECT LAST_INSERT_ID(); -- Output: (last inserted ID)

NULLIF Compares two expressions and returns NULL if they are


equal, otherwise returns the first expression
Syntax
NULLIF(expression1, expression2)
Example
SELECT NULLIF(5, 5); -- Output: NULL

SESSION_USER Returns the current MySQL user name and host name
Syntax
SESSION_USER()
Example
SELECT SESSION_USER(); -- Output: user@host

SYSTEM_USER Returns the current MySQL user name and host name
Syntax
SYSTEM_USER()
Example
SELECT SYSTEM_USER(); -- Output: user@host

USER Returns the current MySQL user name and host name
Syntax
USER()
Example
SELECT USER(); -- Output: user@host

VERSION Returns the current version of the MySQL database


Syntax
VERSION()
Example
SELECT VERSION(); -- Output: (MySQL version)

-----------------------------------------------------------------------------------
---------------------------------------------------------------------------------

NOTES FROM SIR ALZAGA

NOTE 1:
-- Displaying existing databases
SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sakila |
| sys |
| world |
+--------------------+
6 rows in set (0.03 sec)

-- Creating a new database


CREATE DATABASE FIRSTDATABASE;
Query OK, 1 row affected (0.01 sec)

-- Using the newly created database


USE FIRSTDATABASE;
Database changed

-- Mathematical function examples


SELECT ABS(123); -- Absolute value
+----------+
| ABS(123) |
+----------+
| 123 |
+----------+

SELECT MOD(10, 4); -- Modulus operation


+-----------+
| MOD(10,4) |
+-----------+
| 2 |
+-----------+

SELECT MOD(10, 4) AS remainder;


+-----------+
| remainder |
+-----------+
| 2 |
+-----------+

SELECT POWER(4, 2) AS result; -- Exponential calculation


+--------+
| result |
+--------+
| 16 |
+--------+

SELECT GREATEST(2, 23, 435, 343, 34); -- Greatest value


+---------------------------+
| greatest(2,23,435,343,34) |
+---------------------------+
| 435 |
+---------------------------+

SELECT LEAST(1, 2, 4, 53, 45, 4, 4); -- Least value


+------------------------+
| least(1,2,4,53,45,4,4) |
+------------------------+
| 1 |
+------------------------+

SELECT TRUNCATE(22.234242, 2); -- Truncate decimal value


+-----------------------+
| TRUNCATE(22.234242,2) |
+-----------------------+
| 22.23 |
+-----------------------+
SELECT SQRT(25) AS RESULT; -- Square root
+--------+
| RESULT |
+--------+
| 5 |
+--------+

SELECT ROUND(22.987); -- Round without decimal precision


+---------------+
| ROUND(22.987) |
+---------------+
| 23 |
+---------------+

SELECT ROUND(22.987, 2); -- Round to two decimal places


+-----------------+
| ROUND(22.987,2) |
+-----------------+
| 22.99 |
+-----------------+

-- Showing updated databases


SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| firstdatabase |
| information_schema |
| mysql |
| performance_schema |
| sakila |
| sys |
| world |
+--------------------+

-- Creating a table within the database


CREATE TABLE students (
stud_id INT PRIMARY KEY,
stud_name VARCHAR(255),
age INT,
gender CHAR(1),
dob DATE,
city VARCHAR(255)
);
Query OK, 0 rows affected (0.03 sec)

-- Inserting a record into the table


INSERT INTO students VALUES(10000, "tannnnnnnnn", 19, "M", "2005-04-
15", "BAGUIO");
Query OK, 1 row affected (0.01 sec)

-- Attempting to insert a duplicate record (error example)


INSERT INTO students (stud_id, stud_name, age, gender, dob, city)
VALUES(10000, "tannnnnnnnn", 19, "M", "2005-04-15", "BAGUIO");
ERROR 1062 (23000): Duplicate entry '10000' for key 'students.PRIMARY'

-- Displaying tables in the current database


SHOW TABLES;
+-------------------------+
| Tables_in_firstdatabase |
+-------------------------+
| students |
+-------------------------+

-- Querying all records from the 'students' table


SELECT * FROM students;
+---------+-------------+-----+--------+------------+--------+
| stud_id | stud_name | age | gender | dob | city |
+---------+-------------+-----+--------+------------+--------+
| 10000 | tannnnnnnnn | 19 | M | 2005-04-15 | BAGUIO |
+---------+-------------+-----+--------+------------+--------+
1 row in set (0.00 sec)

NOTE 2
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| contacts |
| firstdatabase |
| information_schema |
| mysql |
| new_database |
| performance_schema |
| sakila |
| sys |
| world |
+--------------------+
9 rows in set (0.00 sec)

mysql> use firstdatabase;


Database changed

mysql> show tables;


+-------------------------+
| Tables_in_firstdatabase |
+-------------------------+
| students |
+-------------------------+
1 row in set (0.01 sec)

mysql> describe students;


+-----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| stud_id | int | NO | PRI | NULL | |
| stud_name | varchar(255) | YES | | NULL | |
| age | int | YES | | NULL | |
| gender | char(1) | YES | | NULL | |
| dob | date | YES | | NULL | |
| city | varchar(255) | YES | | NULL | |
+-----------+--------------+------+-----+---------+-------+
6 rows in set (0.00 sec)

mysql> SELECT * FROM students;


+---------+------------------+------+--------+------------+--------+
| stud_id | stud_name | age | gender | dob | city |
+---------+------------------+------+--------+------------+--------+
| 10000 | tannnnnnnnn | 19 | M | 2005-04-15 | BAGUIO |
| 2300217 | My Database | 21 | F | 2005-04-13 | Manila |
+---------+------------------+------+--------+------------+--------+
2 rows in set (0.00 sec)

mysql> select gender from students;


+--------+
| gender |
+--------+
| M |
| F |
+--------+
2 rows in set (0.00 sec)

mysql> select gender from studenrs where gender="M";


ERROR 1146 (42S02): Table 'firstdatabase.studenrs' doesn't exist

mysql> select gender from students where gender="M";


+--------+
| gender |
+--------+
| M |
+--------+
1 row in set (0.00 sec)

mysql> insert into students values(102, "Jose", 22, "M", "2016-11-23",


"La Trinidad");
Query OK, 1 row affected (0.01 sec)

mysql> insert into students values(103, "Jose", 45, "M", "2016-11-23",


"Baguio");
Query OK, 1 row affected (0.00 sec)

mysql> insert into students values(104, "Tina", 30, "F", "2016-11-23",


"Baguio");
Query OK, 1 row affected (0.00 sec)

mysql> SELECT * FROM students;


+---------+------------------+------+--------+------------
+-------------+
| stud_id | stud_name | age | gender | dob | city
|
+---------+------------------+------+--------+------------
+-------------+
| 102 | Jose | 22 | M | 2016-11-23 | La Trinidad
|
| 103 | Jose | 45 | M | 2016-11-23 | Baguio
|
| 104 | Tina | 30 | F | 2016-11-23 | Baguio
|
| 10000 | tannnnnnnnn | 19 | M | 2005-04-15 | BAGUIO
|
| 2300217 | My Database | 21 | F | 2005-04-13 | Manila
|
+---------+------------------+------+--------+------------
+-------------+
5 rows in set (0.00 sec)
mysql> SELECT city from students where city="Baguio";
+--------+
| city |
+--------+
| Baguio |
| Baguio |
| BAGUIO |
+--------+
3 rows in set (0.00 sec)

mysql> SELECT stud_name from students where city="Baguio";


+------------------+
| stud_name |
+------------------+
| Jose |
| Tina |
| tannnnnnnnn |
+------------------+
3 rows in set (0.00 sec)

mysql> select * from students where age=32 or city="Baguio";


+---------+------------------+------+--------+------------+--------+
| stud_id | stud_name | age | gender | dob | city |
+---------+------------------+------+--------+------------+--------+
| 103 | Jose | 45 | M | 2016-11-23 | Baguio |
| 104 | Tina | 30 | F | 2016-11-23 | Baguio |
| 10000 | tannnnnnnnn | 19 | M | 2005-04-15 | BAGUIO |
+---------+------------------+------+--------+------------+--------+
3 rows in set (0.00 sec)

mysql> select city from students;


+-------------+
| city |
+-------------+
| La Trinidad |
| Baguio |
| Baguio |
| BAGUIO |
| Manila |
+-------------+
5 rows in set (0.00 sec)

mysql> select city, count(stud_id) as total_students from students


group by city;
+-------------+----------------+
| city | total_students |
+-------------+----------------+
| La Trinidad | 1 |
| Baguio | 3 |
| Manila | 1 |
+-------------+----------------+
3 rows in set (0.01 sec)

mysql> insert into students values(106, "Roy", 31, "M", "2016-11-23",


"Baguio");
Query OK, 1 row affected (0.01 sec)

mysql> select city, count(stud_id) as total_students from students


group by city;
+-------------+----------------+
| city | total_students |
+-------------+----------------+
| La Trinidad | 1 |
| Baguio | 4 |
| Manila | 1 |
+-------------+----------------+
3 rows in set (0.00 sec)

mysql> select * from students order by city;


+---------+------------------+------+--------+------------
+-------------+
| stud_id | stud_name | age | gender | dob | city
|
+---------+------------------+------+--------+------------
+-------------+
| 103 | Jose | 45 | M | 2016-11-23 | Baguio
|
| 104 | Tina | 30 | F | 2016-11-23 | Baguio
|
| 106 | Roy | 31 | M | 2016-11-23 | Baguio
|
| 10000 | tannnnnnnnn | 19 | M | 2005-04-15 | BAGUIO
|
| 102 | Jose | 22 | M | 2016-11-23 | La Trinidad
|
| 2300217 | My Database | 21 | F | 2005-04-13 | Manila
|
+---------+------------------+------+--------+------------
+-------------+
6 rows in set (0.00 sec)

mysql> select * from students order by age;


+---------+------------------+------+--------+------------
+-------------+
| stud_id | stud_name | age | gender | dob | city
|
+---------+------------------+------+--------+------------
+-------------+
| 10000 | tannnnnnnnn | 19 | M | 2005-04-15 | BAGUIO
|
| 2300217 | My Database | 21 | F | 2005-04-13 | Manila
|
| 102 | Jose | 22 | M | 2016-11-23 | La Trinidad
|
| 104 | Tina | 30 | F | 2016-11-23 | Baguio
|
| 106 | Roy | 31 | M | 2016-11-23 | Baguio
|
| 103 | Jose | 45 | M | 2016-11-23 | Baguio
|
+---------+------------------+------+--------+------------
+-------------+
6 rows in set (0.00 sec)

mysql> select * from students order by age desc;


+---------+------------------+------+--------+------------
+-------------+
| stud_id | stud_name | age | gender | dob | city
|
+---------+------------------+------+--------+------------
+-------------+
| 103 | Jose | 45 | M | 2016-11-23 | Baguio
|
| 106 | Roy | 31 | M | 2016-11-23 | Baguio
|
| 104 | Tina | 30 | F | 2016-11-23 | Baguio
|
| 102 | Jose | 22 | M | 2016-11-23 | La Trinidad
|
| 2300217 | My Database | 21 | F | 2005-04-13 | Manila
|
| 10000 | tannnnnnnnn | 19 | M | 2005-04-15 | BAGUIO
|
+---------+------------------+------+--------+------------
+-------------+
6 rows in set (0.00 sec)

mysql> select * from students order by stud_name desc;


+---------+------------------+------+--------+------------
+-------------+
| stud_id | stud_name | age | gender | dob | city
|
+---------+------------------+------+--------+------------
+-------------+
| 10000 | tannnnnnnnn | 19 | M | 2005-04-15 | BAGUIO
|
| 104 | Tina | 30 | F | 2016-11-23 | Baguio
|
| 106 | Roy | 31 | M | 2016-11-23 | Baguio
|
| 2300217 | My Database | 21 | F | 2005-04-13 | Manila
|
| 102 | Jose | 22 | M | 2016-11-23 | La Trinidad
|
| 103 | Jose | 45 | M | 2016-11-23 | Baguio
|
+---------+------------------+------+--------+------------
+-------------+
6 rows in set (0.00 sec)

mysql> select city, count(stud_id) as total_students group by city


having count(stud_id > 2);
ERROR 1054 (42S22): Unknown column 'city' in 'field list'

mysql> select upper(stud_name) from students;


+------------------+
| upper(stud_name) |
+------------------+
| JOSE |
| JOSE |
| TINA |
| ROY |
| tannnnnnnnn |
| MY DATABASE |
+------------------+
6 rows in set (0.00 sec)
mysql> select lcase(stud_name) from students;
+------------------+
| lcase(stud_name) |
+------------------+
| jose |
| jose |
| tina |
| roy |
| tannnnnnnnn |
| my database |
+------------------+
6 rows in set (0.00 sec)

mysql> select stud_name, length(stud_name) from students;


+------------------+-------------------+
| stud_name | length(stud_name) |
+------------------+-------------------+
| Jose | 4 |
| Jose | 4 |
| Tina | 4 |
| Roy | 3 |
| tannnnnnnnn | 16 |
| My Database | 11 |
+------------------+-------------------+
6 rows in set (0.00 sec)

mysql> select concat("Jich", "is", "my", "name");


+------------------------------------+
| concat("Jich", "is", "my", "name") |
+------------------------------------+
| Jichismyname |
+------------------------------------+
1 row in set (0.01 sec)

mysql> select stud_name, age, concat(stud_name, " ", age) from


students;
+------------------+------+-----------------------------+
| stud_name | age | concat(stud_name, " ", age) |
+------------------+------+-----------------------------+
| Jose | 22 | Jose 22 |
| Jose | 45 | Jose 45 |
| Tina | 30 | Tina 30 |
| Roy | 31 | Roy 31 |
| tannnnnnnnn | 19 | tannnnnnnnn 19 |
| My Database | 21 | My Database 21 |
+------------------+------+-----------------------------+
6 rows in set (0.00 sec)

mysql> select reverse(stud_name) from students;


+--------------------+
| reverse(stud_name) |
+--------------------+
| esoJ |
| esoJ |
| aniT |
| yoR |
| nnnnnnnnnat |
| esabataD yM |
+--------------------+
6 rows in set (0.00 sec)

mysql> select abs(age) from students;


+----------+
| abs(age) |
+----------+
| 22 |
| 45 |
| 30 |
| 31 |
| 19 |
| 21 |
+----------+
6 rows in set (0.00 sec)

mysql> select replace("Orange is a fruit", "fruit", "color");


+------------------------------------------------+
| replace("Orange is a fruit", "fruit", "color") |
+------------------------------------------------+
| Orange is a color |
+------------------------------------------------+
1 row in set (0.00 sec)

mysql> select length(" WORLD WAR Z


");
+--------------------------------------------------------------+
| length(" WORLD WAR Z ") |
+--------------------------------------------------------------+
| 50 |
+--------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> select rtrim(" WORLD WAR Z


");
+-------------------------------------------------------------+
| rtrim(" WORLD WAR Z ") |
+-------------------------------------------------------------+
| WORLD WAR Z |
+-------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> select ltrim(" WORLD WAR Z


");
+-------------------------------------------------------------+
| ltrim(" WORLD WAR Z ") |
+-------------------------------------------------------------+
| WORLD WAR Z |
+-------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> select length(ltrim(" WORLD WAR Z


"));
+---------------------------------------------------------------------+
| length(ltrim(" WORLD WAR Z ")) |
+---------------------------------------------------------------------+
| 22 |
+---------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> select position("Jich" in "My name is Jich");
+---------------------------------------+
| position("Jich" in "My name is Jich") |
+---------------------------------------+
| 12 |
+---------------------------------------+
1 row in set (0.00 sec)

mysql> select ascii('a');


+------------+
| ascii('a') |
+------------+
| 97 |
+------------+
1 row in set (0.00 sec)

mysql> select ascii(age) as ascii_age from students;


+-----------+
| ascii_age |
+-----------+
| 50 |
| 52 |
| 51 |
| 51 |
| 49 |
| 50 |
+-----------+
6 rows in set (0.00 sec)

mysql> select age, ascii(age) as ascii_age from students;


+------+-----------+
| age | ascii_age |
+------+-----------+
| 22 | 50 |
| 45 | 52 |
| 30 | 51 |
| 31 | 51 |
| 19 | 49 |
| 21 | 50 |
+------+-----------+
6 rows in set (0.00 sec)

You might also like