Você está na página 1de 19

MYSQL

COMMANDS
TO CREATE A DATABASE
Syntax: CREATE DATABASE databasename;

Example: CREATE DATABASE foycadet;
TO CREATE DATABASE COLUMNS
Syntax: CREATE TABLE tablename (
column1name description,
column2name description);

Example: CREATE TABLE users (
user_id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
first_name VARCHAR(20) NOT NULL,
last_name VARCHAR(40) NOT NULL,
email VARCHAR(60) NOT NULL,
pass CHAR(40) NOT NULL,
registration_date DATETIME NOT NULL,
PRIMARY KEY (user_id)
);
TO INSERT RECORDS (ROWS)
Syntax: INSERT INTO tablename (column1,
column2, column3)
VALUES (value1, value2,value3, )

Example: INSERT INTO users (user_id, first_name,
last_name, email, pass,
registration_date)
VALUES (NULL, 'Larry', 'Ullman',
'email@example.com',SHA1('mypass'), NOW());

NB: the function sha1() encrypts the password supplied while NOW()
generates the current time in the database
SELECTING DATA
Syntax: SELECT column1,column2,... FROM
tablename;

Example: SELECT first_name, last_name FROM
users;

NB: the * character is used to select every column in a table.
SELECT * FROM users;



SELECTING WITH CONDITIONS
Syntax: SELECT column1,column2,... FROM
tablename WHERE CONDITION(S);

Example: SELECT * FROM users
WHERE last_name = Yusuf';

// selects every column details of all data with
the last name Yusuf
USING LIKE AND NOTLIKE
The LIKE and NOTLIKE is used as conditions to compare
string characters. They are used with the _ to compare
single strings and % to compare multiple strings.

EXAMPLE: SELECT * FROM users
WHERE last_name LIKE Kola%';
// Select all of the records in which the last
name starts with Kola

SELECT first_name, last_name
FROM users WHERE
email NOT LIKE '%@authors.com';
// Select the firstname and last name of users without an
email address of @authors.com
MYSQL OPERATORS
Operator Meaning
= Equals
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
!= (also <>) Not equal to
IS NOT NULL Has a value
IS NULL Does not have a value
BETWEEN Within a range
NOT BETWEEN Outside of a range
IN Found within a list of values
OR (also ||) Where one of two conditionals is true
AND (also &&) Where both conditionals are
true
NOT (also !) Where the condition is not true
SORTING QUERY RESULTS
Syntax: SELECT * FROM tablename ORDER BY
column;
SELECT * FROM tablename WHERE
conditions ORDER BY column;

Example: SELECT first_name, last_name FROM
users ORDER BY last_name ASC,
first_name ASC;

// retrieves the first name and last name from a
query and sorts in alphabetically ascending order
(ASC). To sort in descending order, (DESC) is used.
LIMITING QUERY RESULT
Syntax: SELECT * FROM tablename LIMIT x;
// only the first x records is returned.

SELECT * FROM tablename LIMIT x,y;
//only records within the range x and y is
returned.

NB: LIMIT can be used with conditions and
sorting discussed earlier

UPDATING DATA
Syntax: UPDATE tablename SET
column1=valueA, column5=valueB;

UPDATE tablename SET column2=value
WHERE column5=value;

Example: UPDATE users SET
email='mike@authors.com'
WHERE user_id = 18 LIMIT 1
// updates the email address of the row with the
user id 18
DELETING RECORD
Syntax: DELETE FROM tablename;
DELETE FROM tablename WHERE condition;

Example: DELETE FROM users
WHERE user_id = 8 LIMIT 1;

TRUNCATE TABLE tablename //to empty a table
DROP TABLE tablename //to delete a table
DROP DATABASE databasename // to delete a database
TEXT FUNCTIONS
Function Usage Returns
CONCAT() CONCAT(t1, t2, ...) A new string of the form t1t2.
CONCAT_WS() CONCAT(S, t1, t2, ...) A new string of the form t1St2S
LENGTH() LENGTH(t) The number of characters in t.
LEFT() LEFT(t, y) The leftmost y characters from t.
RIGHT() RIGHT(t, x) The rightmost x characters from t.
TRIM() TRIM(t) t with excess spaces from the
beginning and end removed.
UPPER() UPPER(t) t capitalized.
LOWER() LOWER(t) t in all-lowercase format.
SUBSTRING() SUBSTRING(t, x, y) y characters from t beginning with x
(indexed from 0).

Example: SELECT CONCAT_WS(' ', first, middle,last) AS Name FROM tablename
NUMERIC FUNCTIONS
Function Usage Returns
ABS() ABS(n) The absolute value of n.
CEILING() CEILING(n) The next-highest integer based upon.
the value of n
FLOOR() FLOOR(n) The integer value of n.
FORMAT() FORMAT(n1, n2) n1 formatted as a numberwith n2 decimal
commas inserted every three spaces.
places and
MOD() MOD(n1, n2) The remainder of dividing n1 by n2
POW() POW(n1, n2) n1 to the n2 power.
RAND() RAND() A random number between 0 and 1.0

ROUND() ROUND(n1, n2) n1 rounded to n2 decimal places.

SQRT() SQRT(n) The square root of n.


Example: SELECT CONCAT('$', FORMAT(5639.6, 2)) AS cost;


TIME AND DATE FUNCTIONS
Function Usage Returns
HOUR() HOUR(dt) The hour value of dt.
MINUTE() MINUTE(dt) The minute value of dt.
SECOND() SECOND(dt) The second value of dt.
DAYNAME() DAYNAME(dt) The name of the day for dt.
DAYOFMONTH() DAYOFMONTH(dt) The numerical day value of dt.
MONTHNAME() MONTHNAME(dt) The name of the month of dt.
MONTH() MONTH(dt) The numerical month value of dt.
YEAR() YEAR(column) The year value of dt.
CURDATE() CURDATE() The current date.
CURTIME() CURTIME() The current time.
NOW() NOW() The current date and time.
UNIX_TIMESTAMP() UNIX_TIMESTAMP(dt) The number of seconds since the
epoch until the current
moment or until the date
specified.
Example: SELECT DATE(registration_date) AS
Date FROM users ORDER BY
registration_date DESC LIMIT 1;
*_FORMAT() Parameters
Term Usage Exampl e
%e Day of the month 1-31
%d Day of the month, 01-31
%D Day with suffix 1st-31st
%W Weekday name Sunday-Saturday
%a Abbreviated Sun-Sat weekday name
%c Month number 1-12
%m Month number, 01-12
%M Month name January-December
%b Month name, Jan-Dec
%Y Year 2002
%y Year 02
%l Hour 1-12
%h Hour, two digit 01-12
%k Hour, 24-hour clock 0-23
%H Hour, 24-hour clock, 00-23
%i Minutes 00-59
%S Seconds 00-59
%r Time 8:17:02 PM
%T Time, 24-hour clock 20:17:02
%p AM or PM AM or PM

Example : SELECT DATE_FORMAT (NOW(),'%M %e, %Y %l:%i'); //Month DD, YYYY - HH:MM
PERFORMING INNER JOINS
Syntax: SELECT * FROM table1 INNER JOIN table2 ON table1.table2_id =
table2.table2_id WHERE (conditionals);
SELECT * FROM messages INNER JOIN forums ON messages.forum_id =
forums.forum_id WHERE forums.name = 'kindling
SELECT * FROM messages, forums WHERE messages.forum_id =
forums.forum_id AND forums.name = 'kindling
SELECT * FROM messages INNER JOIN forums USING (forum_id) WHERE
forums.name = 'kindling

Example: SELECT m.message_id, m.subject, f.name FROM users AS u INNER
JOIN
messages AS m USING (user_id) INNER JOIN forums AS f
USING (forum_id) WHERE u.username = 'troutster'; //Retrieves the
message ID, subject, and forum name for every message posted by the user
troutster

SELECT m.subject, DATE_FORMAT(m.date_entered, '%M %D, %Y') AS Date
FROM users AS u INNER JOIN messages AS m USING (user_id) WHERE
u.username = 'funny man'; // Retrieve the subject and date entered value
for every message posted by the user funny man

PERFORMING OUTER JOIN
Unlike inner join that merges tables together
with condition, outer join merges without
condition. There are 3 types left, right and full.
Inner join includes NOT NULL VALUES while
outer join includes NULL VALUES
EDITING TABLES
The ALTER clause is normally used to edit tables.
Clause Usage Meaning
ADD COLUMN ALTER TABLE t ADD COLUMN c TYPE Adds a new column to the
end of the table.

CHANGE COLUMN ALTER TABLE t CHANGE COLUMN c c TYPE Allows you to change the
data type and properties of
a column.

DROP COLUMN ALTER TABLE t DROP COLUMN c Removes a column from a
table, including all
of its data.
ADD INDEX ALTER TABLE t ADD INDEX i (c) Adds a new index on c.

DROP INDEX ALTER TABLE t DROP INDEX i Removes an existing index.

RENAME AS ALTER TABLE t RENAME AS new_t Changes the name of a
table.
ENGINE TYPE ALTER TABLE tablename ENGINE = MYISAM changes table type to myisam
//innodb

Você também pode gostar