Use signed or unsigned BIGINT for storing UNIX timestamps.
The WHERE Clause |
SELECT prod_name, prod_price FROM Products WHERE prod_price = 3.49; |
Range of Values |
SELECT prod_name, prod_price FROM Products WHERE prod_price BETWEEN 5 AND 10; |
Checking For No Value |
SELECT prod_name FROM Products WHERE prod_price IS NULL |
The AND Operator |
SELECT prod_id, prod_price, prod_name FROM Products WHERE vend_id = 'DLL01' AND prod_price <= 4; |
The OR Operator |
SELECT prod_id, prod_price, prod_name FROM Products WHERE vend_id = 'DLL01' OR vend_id = 'BRS01'; |
Order of Evaluation |
SELECT prod_name, prod_price FROM Products WHERE (vend_id = 'DLL01' OR vend_id = 'BRS01') AND prod_price >= 10; |
The IN Operator |
SELECT prod_name, prod_price FROM Products WHERE vend_id IN ('DLL01','BRS01') ORDER BY prod_name; |
The NOT Operator |
SELECT prod_name FROM Products WHERE NOT vend_id = 'DLL01' ORDER BY prod_name; |
The LIKE Operator - % |
SELECT prod_id, prod_name FROM Products WHERE prod_name LIKE '%bean bag%'; |
The LIKE Operator - _ |
SELECT prod_id, prod_name FROM Products WHERE prod_name LIKE '__ inch teddy bear'; |
The LIKE Operator - [ ] (containes range) |
SELECT cust_contact FROM Customers WHERE cust_contact LIKE '[JM]%' ORDER BY cust_contact; |
The LIKE Operator - [^ ] (does not containe range) |
SELECT cust_contact FROM Customers WHERE cust_contact LIKE '[^JM]%' ORDER BY cust_contact; |
The DISTINCT Clause (allows only unique values) |
SELECT DISTINCT date from `trollz_skus` WHERE sku='sku0001' AND vendor='ImpTech'; |
ASCII(str) | Returns the ASCII code value of the leftmost character of the string str. Returns 0 if str is the empty string. Returns NULL if str is NULL |
ORD(str) | If the leftmost character of the string str is a multi-byte character, returns the code of multi-byte character by returning the ASCII code value of the character in the format of: ((first byte ASCII code)*256+(second byte ASCII code))[*256+third byte ASCII code...]. If the leftmost character is not a multi-byte character, returns the same value as the like ASCII() function does |
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 base 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 |
CHAR(N,...) | CHAR() interprets the arguments as integers and returns a string consisting of the characters given by the ASCII code values of those integers. NULL values are skipped |
CONCAT(str1,str2,...) | Returns the string that results from concatenating the arguments. Returns NULL if any argument is NULL. May have more than 2 arguments. A numeric argument is converted to the equivalent string form |
CONCAT_WS(separator, str1, str2,...) | CONCAT_WS() stands for CONCAT With Separator and is a special form of CONCAT(). The first argument is the separator for the rest of the arguments. The separator can be a string as well as the rest of the arguments. If the separator is NULL, the result will be NULL. The function will skip any NULLs and empty strings, after the separator argument. The separator will be added between the strings to be concatenated |
LENGTH(str) SQL | Returns the length of the string str |
LOCATE(substr,str[,pos]) | 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 |
LPAD(str,len,padstr) | Returns the string str, left-padded with the string padstr until str is len characters long. If str is longer than len' then it will be shortened to len characters. |
RPAD(str,len,padstr) | Returns the string str, right-padded with the string padstr until str is len characters long. If str is longer than len' then it will be shortened to len characters. |
LEFT(str,len) SQL | Returns the leftmost len characters from the string str |
RIGHT(str,len) SQL | Returns the rightmost len characters from the string str |
SUBSTRING(str,pos[,len]) or SUBSTRING(str FROM pos FOR len) SQL | Returns a substring len characters long from string str, starting at position pos. The variant form that uses FROM is ANSI SQL92 syntax |
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 |
LTRIM(str) SQL | Trims white space from left of str |
RTRIM(str) SQL | Trims white space from right of str |
TRIM([[BOTH | LEADING | TRAILING] [remstr] FROM] str) SQL | Returns the string str with all remstr prefixes and/or suffixes removed. If none of the specifiers BOTH, LEADING or TRAILING are given, BOTH is assumed. If remstr is not specified, spaces are removed. |
SOUNDEX(str) SQL | Retruns a strings SOUNDEX value of str |
SPACE(N) | Returns a string consisting of N space characters. |
REPLACE(str,from_str,to_str) | Returns the string str with all all occurrences of the string from_str replaced by the string to_str |
REPEAT(str,count) | Returns a string consisting of the string str repeated count times. If count <= 0, returns an empty string. Returns NULL if str or count are NULL |
REVERSE(str) | Returns the string str with the order of the characters reversed |
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 |
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() |
FIELD(str,str1,str2,str3,...) | Returns the index of str in the str1, str2, str3, ... list. Returns 0 if str is not found. FIELD() is the complement of ELT() |
FIND_IN_SET(str,strlist) | Returns a value 1 to N if the string str is in the list strlist consisting of N substrings. A string list is a string composed of substrings separated by , characters. If the first argument is a constant string and the second is a column of type SET, the FIND_IN_SET() function is optimised to use bit arithmetic! Returns 0 if str is not in strlist or if strlist is the empty string. Returns NULL if either argument is NULL. This function will not work properly if the first argument contains a , |
MAKE_SET(bits,str1,str2,...) | Returns a set (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, etc. NULL strings in str1, str2, ... are not appended to the result |
EXPORT_SET(bits,on,off,[separator,[number_of_bits]]) | Returns a string where for every bit set in 'bit', you get an 'on' string and for every reset bit you get an 'off' string. Each string is separated with 'separator' (default ',') and only 'number_of_bits' (default 64) of 'bits' is used |
LOWER(str) SQL | Converts string to lowercase |
UPPER(str) SQL | Converts string to uppercase |
LOAD_FILE(file_name) | Reads the file and returns the file contents as a string. The file must be on the server, you must specify the full pathname to the file, and you must have the file privilege. The file must be readable by all and be smaller than max_allowed_packet |
ABS(X) | Returns the absolute value of X |
SIGN(X) SQL | Returns the sign of the argument as -1, 0, or 1, depending on whether X is negative, zero, or positive |
MOD(N,M) | Modulo (like the % operator in C). Returns the remainder of N divided by M |
FLOOR(X) SQL | Returns the largest integer value not greater than X |
CEILING(X) SQL | Returns the smallest integer value not less than X |
ROUND(X[,D]) | Returns the argument X, rounded to a number with D decimals. If D is 0, the result will have no decimal point or fractional part |
EXP(X) SQL | Returns the value of e (the base of natural logarithms) raised to the power of X |
LOG(X) | Returns the natural logarithm of X |
LOG10(X) | Returns the base-10 logarithm of X |
POW(X,Y) or POWER(X,Y) | Returns the value of X raised to the power of Y |
SQRT(X) SQL | Returns the non-negative square root of X |
PI() SQL | Returns the value of PI. The default shown number of decimals is 5, but MySQL internally uses the full double precession for PI |
COS(X) SQL | Returns the cosine of X, where X is given in radians |
SIN(X) SQL | Returns the sine of X, where X is given in radians |
TAN(X) SQL | Returns the tangent of X, where X is given in radians |
ACOS(X) | Returns the arc cosine of X, that is, the value whose cosine is X. Returns NULL if X is not in the range -1 to 1 |
ASIN(X) | Returns the arc sine of X, that is, the value whose sine is X. Returns NULL if X is not in the range -1 to 1 |
ATAN(X) | Returns the arc tangent of X, that is, the value whose tangent is X |
ATAN(Y,X) or ATAN2(Y,X) | Returns the arc tangent of the two variables X and Y. It is similar to calculating the arc tangent of Y / X, except that the signs of both arguments are used to determine the quadrant of the result |
COT(X) | Returns the cotangent of X |
RAND([N]) | Returns a random floating-point value in the range 0 to 1.0. If an integer argument N is specified, it is used as the seed value |
LEAST(X,Y,...) | With two or more arguments, returns the smallest (minimum-valued) argument. The arguments are compared using the following rules:
- If the return value is used in an INTEGER context, or all arguments are integer-valued, they are compared as integers.
- If the return value is used in a REAL context, or all arguments are real-valued, they are compared as reals.
- If any argument is a case-sensitive string, the arguments are compared as case-sensitive strings.
- In other cases, the arguments are compared as case-insensitive strings
|
GREATEST(X,Y,...) | Returns the largest (maximum-valued) argument. The arguments are compared using the same rules as for LEAST |
DEGREES(X) | Returns the argument X, converted from radians to degrees |
RADIANS(X) | Returns the argument X, converted from degrees to radians |
TRUNCATE(X,D) | Returns the number X, truncated to D decimals. If D is 0, the result will have no decimal point or fractional part: |
DAYOFWEEK(date) | Returns the weekday index |
WEEKDAY(date) | Returns the weekday index for date (0 = Monday, 1 = Tuesday, ... 6 = Sunday) |
DAYOFMONTH(date) | Returns the day of the month for date, in the range 1 to 31 |
DAYOFYEAR(date) | Returns the day of the year for date, in the range 1 to 366 |
MONTH(date) | Returns the month for date, in the range 1 to 12 |
DAYNAME(date) | Returns the name of the weekday for date |
MONTHNAME(date) | Returns the name of the month for date |
QUARTER(date) | Returns the quarter of the year for date, in the range 1 to 4 |
WEEK(date,first) | With a single argument, returns the week for date, in the range 0 to 53. With the two-argument form you can specify whether the week starts on Sunday or Monday. Sunday = 0. Monday = 1 |
YEAR(date) | Returns the year for date, in the range 1000 to 9999 |
YEARWEEK(date,first) | Returns year and week for a date. The second arguments works exactly like in WEEK(). Note that the year may be different from the year in the date argument for the first and the last week of the year |
HOUR(time) | Returns the hour for time, in the range 0 to 23 |
MINUTE(time) | Returns the minute for time, in the range 0 to 59 |
SECOND(time) | Returns the second for time, in the range 0 to 59 |
PERIOD_ADD(P,N) | Adds N months to period P (in the format YYMM or YYYYMM). Returns a value in the format YYYYMM |
PERIOD_DIFF(P1,P2) | Returns the number of months between periods P1 and P2. P1 and P2 should be in the format YYMM or YYYYMM |
DATE_ADD(date,INTERVAL expr type) and DATE_SUB(date,INTERVAL expr type) |
date is a DATETIME or DATE value specifying the starting date.
expr is an expression specifying the interval value to be added or subtracted from the starting date.
expr is a string; it may start with a - for negative intervals.
type is a keyword indicating how the expression should be interpreted.
type value Expected expr format
SECOND SECONDS
MINUTE MINUTES
HOUR HOURS
DAY DAYS
MONTH MONTHS
YEAR YEARS
MINUTE_SECOND "MINUTES:SECONDS"
HOUR_MINUTE "HOURS:MINUTES"
DAY_HOUR "DAYS HOURS"
YEAR_MONTH "YEARS-MONTHS"
HOUR_SECOND "HOURS:MINUTES:SECONDS"
DAY_MINUTE "DAYS HOURS:MINUTES"
DAY_SECOND "DAYS HOURS:MINUTES:SECONDS"
|
EXTRACT(type FROM date) | The EXTRACT() function uses the same kinds of interval type specifiers as DATE_ADD() or DATE_SUB(), but extracts parts from the date rather than performing date arithmetic. |
TO_DAYS(date) | Given a date date, returns a daynumber (the number of days since year 0) |
FROM_DAYS(N) | Given a daynumber N, returns a DATE value |
DATE_FORMAT(date,format) | Formats the date value according to the format string. The following specifiers may be used in the format string:
Specifier Description
%M Month name (January..December)
%W Weekday name (Sunday..Saturday)
%D Day of the month with English suffix (1st, 2nd, 3rd, etc.)
%Y Year, numeric, 4 digits
%y Year, numeric, 2 digits
%X Year for the week where Sunday is the first day of the week, numeric, 4 digits, used with '%V'
%x Year for the week, where Monday is the first day of the week, numeric, 4 digits, used with '%v'
%a Abbreviated weekday name (Sun..Sat)
%d Day of the month, numeric (00..31)
%e Day of the month, numeric (0..31)
%m Month, numeric (01..12)
%c Month, numeric (1..12)
%b Abbreviated month name (Jan..Dec)
%j Day of year (001..366)
%H Hour (00..23)
%k Hour (0..23)
%h Hour (01..12)
%I Hour (01..12)
%l Hour (1..12)
%i Minutes, numeric (00..59)
%r Time, 12-hour (hh:mm:ss [AP]M)
%T Time, 24-hour (hh:mm:ss)
%S Seconds (00..59)
%s Seconds (00..59)
%p AM or PM
%w Day of the week (0=Sunday..6=Saturday)
%U Week (0..53), where Sunday is the first day of the week
%u Week (0..53), where Monday is the first day of the week
%V Week (1..53), where Sunday is the first day of the week. Used with '%X'
%v Week (1..53), where Monday is the first day of the week. Used with '%x'
%% A literal %.
|
TIME_FORMAT(time,format) | This is used like the DATE_FORMAT() function above, but the format string may contain only those format specifiers that handle hours, minutes, and seconds. Other specifiers produce a NULL value or 0. |
CURRENT_DATE() | Returns today's date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or numeric context. |
CURRENT_TIME() | Returns the current time as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or numeric context. |
NOW() or SYSDATE() or CURRENT_TIMESTAMP() | 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 numeric context |
UNIX_TIMESTAMP(date) | If called with no argument, returns a Unix timestamp (seconds since '1970-01-01 00:00:00' GMT) 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' GMT. date may be a DATE string, a DATETIME string, a TIMESTAMP, or a number in the format YYMMDD or YYYYMMDD in local time |
FROM_UNIXTIME(unix_timestamp) | 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 numeric context |
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 |
TIME_TO_SEC(time) | Returns the time argument, converted to seconds |
WHERE Clause Join (Inner Join) |
SELECT vend_name, prod_name, prod_price FROM Vendors, Products; |
INNER JOIN |
SELECT vend_name, prod_name, prod_price
FROM Vendors INNER JOIN Products ON vendors.vend_id = products.vend_id; |
Joining Multiple Tables |
SELECT prod_name, vend_name, prod_price, quantity
FROM OrderItems, Products, Vedors
WHERE Products.vend_id = Vendors.vend_id
AND OrderItems.prod_id = Products.prod_id
AND order_num = 20007; |
Using Table Aliases |
SELECT cust_name, cust_contact
FROM Customers AS C, Orders AS O, OrderItems AS OI
WHERE C.cust_id = O.cust_id
AND OI.order_num - O.order_num
AND prod_id = 'RGAN01'; |
Self Joins |
SELECT c1.cust_id, c1.cust_name, c1.cust_contact
FROM Customers AS c1, Customers AS c2
WHERE c1.cust_name = c2.cust_name
AND c2.cust_contact = 'Jim Jones'; |
Natural Joins |
SELECT C.*, O.order_num, O.order_date, OI.prod_id, OI._quantity, OI.item_price
FROM Customers AS C, Orders AS O, OrderItems AS OI
WHERE C.cust_id = O.cust_id
AND OI.order_num = O.order_num
AND prod_id = 'RGAN01'; |
Outer Join (Left) |
SELECT Customers.cust_id, Orders.order_num
FROM Customers, Orders
WHERE Customers.cust_id *= Orders.cust_id; |
SELECT Customers.cust_id, Orders.order_num
FROM Customers LEFT OUTER JOIN Orders
WHERE Customers.cust_id = Orders.cust_id; |
Full Outer Join |
SELECT Customers.cust_id, Orders.order_num
FROM Orders FULL OUTER JOIN Customers
ON Orders.cust_id = Customers.cust_id; |
Using UNION |
SELECT cust_name, cust_contact, cust_email FROM Customers
WHERE cust_state IN ('IL','IN','MI')
UNION
SELECT cust_name, cust_contact, cust_email FROM Customers
WHERE cust_name = 'Fun4All'; |
Including Duplicate Rows |
SELECT cust_name, cust_contact, cust_email FROM Customers
WHERE cust_state IN ('IL','IN','MI')
UNION ALL
SELECT cust_name, cust_contact, cust_email FROM Customers
WHERE cust_name = 'Fun4All'; |
Sorting Combined Quiry Results |
SELECT cust_name, cust_contact, cust_email FROM Customers
WHERE cust_state IN ('IL','IN','MI')
UNION
SELECT cust_name, cust_contact, cust_email FROM Customers
WHERE cust_name = 'Fun4All'
ORDER BY cust_name, cust_contact; |
Inserting Complete Rows |
INSERT INTO Customers(
cust_id,
cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country,
cust_contact,
cust_email)
VALUES('1000000006',
'Toy Land',
'123 Any Street',
'New York',
'NY',
'11111',
'USA',
NULL,
NULL); |
Inserting Partial Rows |
INSERT INTO Customers(
cust_id,
cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country)
VALUES('1000000006',
'Toy Land',
'123 Any Street',
'New York',
'NY',
'11111',
'USA'); |
Inserting Retrieved Data |
INSERT INTO Customers(
cust_id,
cust_contact,
cust_email,
cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country)
SELECT cust_id,
cust_contact,
cust_email,
cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country
FROM CustNew; |
Table Copying |
SELECT * INTO CustCopy FROM Customers; |
Creating A "Join" View |
CREATE VIEW ProductCustomers AS
SELECT cust_name, cust_contact, prod_id
FROM Customers, Orders, OrderItems
WHERE Customers.cust_id = Orders.cust_id
AND OrderItems.order_num = Orders.order_num |
Using Views to Reformat Retrieved Data |
CREATE VIEW CustomerMailingLables AS
SELECT cust_name,
cust_address AS cust_address1,
RTRIM(cust_city) + ', ' + RTRIM(cust_state) + ' ' + RTRIM(cust_zip) AS cust_address2,
cust_country AS cust_address3
FROM Customers |
SELECT * FROM CustomerMailingLables; |
Views with Filters |
CREATE VIEW CustomerMailingLables AS
SELECT cust_name,
cust_address AS cust_address1,
RTRIM(cust_city) + ', ' + RTRIM(cust_state) + ' ' + RTRIM(cust_zip) AS cust_address2,
cust_country AS cust_address3
FROM Customers
WHERE NOT cust_address IS NULL
AND NOT cust_city IS NULL
AND NOT cust_state IS NULL
AND NOT cust_zip IS NULL
AND NOT cust_country IS NULL; |
Views with Calculated Fields |
CREATE VIEW OrderItemsExpanded AS
SELECT order_num,
prod_id,
quantity,
item_price,
quantity*item_price AS expanded_price
FROM OrderItems; |
SELECT * FROM OrderItemsExpanded WHERE order_num = 20008; |