MySQL Quick Reference – Functions

MySQL Quick Reference – Functions

Tested on MySQL 5.5

SQL Aggregate Functions

SQL aggregate functions return a single value, calculated from values in a column.


/* SELECT AVG(column_name) FROM table_name */
SELECT AVG(column_name) FROM table_name

/* The COUNT() function returns the number of rows that matches a specified criteria */
SELECT COUNT(column_name) FROM table_name;

/* The COUNT(*) function returns the number of records in a table */
SELECT COUNT(*) FROM table_name;

/* The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified column */
SELECT COUNT(DISTINCT column_name) FROM table_name;

/* The FIRST() function returns the first value of the selected column */
/* MySQL not support FIRST() but you can use: */
SELECT column_name FROM table_name
ORDER BY column_name ASC
LIMIT 1;

/* The LAST() function returns the first value of the selected column */
/* MySQL not support LAST() but you can use: */
SELECT column_name FROM table_name
ORDER BY column_name DESC
LIMIT 1;

/* The MAX() function returns the largest value of the selected column */
SELECT MAX(column_name) FROM table_name;

/* The MIN() function returns the smallest value of the selected column */
SELECT MIN(column_name) FROM table_name;

/* The SUM() function returns the total sum of a numeric column */
SELECT SUM(column_name) FROM table_name;

/* The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns */
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;

/* The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions */
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value;

SQL Scalar functions

SQL scalar functions return a single value, based on the input value.


/* The UCASE() function converts the value of a field to uppercase */
SELECT UCASE(column_name) FROM table_name;

/* The LCASE() function converts the value of a field to lowercase */
SELECT LCASE(column_name) FROM table_name;

/* The MID() function is used to extract characters from a text field */
SELECT MID(column_name,start[,length]) AS some_name FROM table_name;

/* The LEN() function returns the length of the value in a text field */
SELECT LEN(column_name) FROM table_name;

/* The FORMAT() function is used to format how a field is to be displayed */
SELECT FORMAT(column_name,format) FROM table_name;

By |MySQL, Web Design|Commenti disabilitati su MySQL Quick Reference – Functions

MySQL Quick Reference – Dates

MySQL Quick Reference – Dates

Tested on MySQL 5.5

Date Data Types

DATE – format YYYY-MM-DD
DATETIME – format: YYYY-MM-DD HH:MM:SS
TIMESTAMP – format: YYYY-MM-DD HH:MM:SS
YEAR – format YYYY or YY

Date Functions

NOW() Returns the current date and time
CURDATE() Returns the current date
CURTIME() Returns the current time

DATE() Extracts the date part of a date or date/time expression
EXTRACT() Returns a single part of a date/time
DATE_ADD() Adds a specified time interval to a date
DATE_SUB() Subtracts a specified time interval from a date
DATEDIFF() Returns the number of days between two dates
DATE_FORMAT() Displays date/time data in different formats

Syntax Examples:


/* Example ######################### */

CREATE TABLE Orders
(
... you want to do ...

OrderDate datetime NOT NULL DEFAULT NOW(),

OrderDate datetime NOT NULL DEFAULT CURDATE(),

OrderDate datetime NOT NULL DEFAULT CURTIME(),

... you want to do ...
)

/* Example ######################### */

SELECT ProductName, DATE(OrderDate) AS OrderDate
FROM Orders
WHERE OrderId=1

/* Example ######################### */

SELECT EXTRACT(YEAR FROM OrderDate) AS OrderYear,
EXTRACT(MONTH FROM OrderDate) AS OrderMonth,
EXTRACT(DAY FROM OrderDate) AS OrderDay,
FROM Orders
WHERE OrderId=1

/* Example ######################### */
/* Now we want to add 45 days to the "OrderDate", to find the payment date */

SELECT OrderId,DATE_ADD(OrderDate,INTERVAL 45 DAY) AS OrderPayDate
FROM Orders

/* Example ######################### */
/* Now we want to subtract 5 days from the "OrderDate" date. */

SELECT OrderId,DATE_SUB(OrderDate,INTERVAL 5 DAY) AS SubtractDate
FROM Orders

/* Example ######################### */
/* The result is -1 */

SELECT DATEDIFF('2008-11-29','2008-11-30') AS DiffDate

/* Example ######################### */

DATE_FORMAT(NOW(),'%b %d %Y %h:%i %p')
DATE_FORMAT(NOW(),'%m-%d-%Y')
DATE_FORMAT(NOW(),'%d %b %y')
DATE_FORMAT(NOW(),'%d %b %Y %T:%f')

/* The Result:

Nov 04 2008 11:45 PM
11-04-2008
04 Nov 08
04 Nov 2008 11:45:34:243 */

By |MySQL, Web Design|Commenti disabilitati su MySQL Quick Reference – Dates

MySQL Quick Reference – Basic

MySQL Quick Reference – Basic

Tested on MySQL 5.5

Syntax

1. Open phpMyAdmin and select a database
2. TOP MENU> localhost> lucedigi_test
3. TOP LABELS> SQL
4. BOTTOM MENU ‘SELECT*’ button

Input:

SELECT * FROM `Persons`;

– SQL ARE NOT CASE SENSITIVE
– USE SEMICOLON ‘;’ to to separate each SQL statement
– `Persons` is not ‘Persons’ -> ` is dfifferent of ‘

FROM MySQL to PHP MYSQL

1. Open phpMyAdmin and select a database
2. TOP MENU> localhost> lucedigi_test
3. TOP LABELS> SQL
4. Input your code
5. BOTTOM RIGHT ‘Esegui’ Button
6. In the next window on the right [Crea codice PHP]

SELECT

Table name: Persons
Columns: PID, First Name, Last Name, Age.


/* Comments */ 

/* Select All */ 
SELECT * FROM `Persons`;

/* Select only specified columns */ 
SELECT `PID`, `FirstName`, `LastName`, `Age` FROM `Persons`;

/* In a table, a column may contain many duplicate values; and sometimes you only want to list the different (distinct) values. */ 
SELECT DISTINCT `FirstName`, `LastName`
FROM Persons;

SELECT … WHERE


/* The WHERE clause is used to extract only those records that fulfill a specified criterion. */ 
/* Operators = <> > < >= <= BETWEEN LIKE IN */ 
SELECT * FROM Persons
WHERE FirstName='Erica';

/* Operators for multiple values START */ 
/* ################################### */

SELECT * FROM Persons
WHERE FirstName='Erica'
AND LastName='Tonin';

SELECT * FROM Persons
WHERE FirstName='Erica'
OR LastName='Tonin';

SELECT * FROM Persons
WHERE FirstName='Erica'
AND (LastName='Tonin' OR LastName='Santato');

SELECT * FROM Customers
WHERE City IN ('Paris','London');

SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;

SELECT * FROM Products
WHERE (Price BETWEEN 10 AND 20)
AND NOT CategoryID IN (1,2,3);

SELECT * FROM Products
WHERE ProductName BETWEEN 'C' AND 'M';

SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'C' AND 'M';

SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/04/1996# AND #07/09/1996#;

/* ################################### */
/* Operators for multiple values END */ 

ORDER


/* The ORDER BY keyword is used to sort the result-set */ 
/* Default is ASC - ascending */ 
SELECT * FROM Persons
ORDER BY LastName; 

/* DESC - descending */
SELECT * FROM Persons
ORDER BY LastName DESC;

/* In ordine avremo Erica Santato poi Erica Tonin - a parità di FirstName si classifica con il LastName */
SELECT * FROM Persons
ORDER BY FirstName,LastName;

INSERT – UPDATE


/* Insert New Records in a table */ 
INSERT INTO Persons (FirstName, LastName)
VALUES ('Ivan', 'Danko');

/* Update records in a table */ 
/* ATTENZIONE!!!!  Se si omette WHERE tutti i record saranno sovrascritti! */ 
UPDATE Persons
SET FirstName='Sylvester', LastName='Stallone'
WHERE FirstName='Ivan';

DELETE


/* Delete records */ 
/* ATTENZIONE!!!!  Se si omette WHERE tutti i record saranno cancellati! */ 
DELETE FROM Persons
WHERE FirstName='Sylvester' AND LastName='Stallone';

/* Delete ALL DATA */
DELETE FROM Persons;

LIMIT


/* LIMIT Specifies the number of records to return */
SELECT LastName
FROM Persons
LIMIT 3;

Wildcards

A wildcard character can be used to substitute for any other character(s) in a string.


/* LIKE searches for a specified pattern in a column */
/* The Result is Tonin - Zonin - Ponin - Conin etc... */
SELECT * FROM Persons
WHERE LastName LIKE '%oni%';

/* The Result is Tonin - Tonib - Toniv - Tonis etc... */
SELECT * FROM Persons
WHERE LastName LIKE 'Toni%';

/* The following SQL statement selects all customers with a City 
starting with any character, followed by "erlin": */
SELECT * FROM Customers
WHERE City LIKE '_erlin';

/* The following SQL statement selects all customers with a City starting with "L", 
followed by any character, followed by "n", followed by any character, followed by "on" */
SELECT * FROM Customers
WHERE City LIKE 'L_n_on';

/*The following SQL statement selects all customers with a City starting with "b", "s", or "p":*/
SELECT * FROM Customers
WHERE City LIKE '[bsp]%';

/*The following SQL statement selects all customers with a City starting with "a", "b", or "c":*/
SELECT * FROM Customers
WHERE City LIKE '[a-c]%';

/*The following SQL statement selects all customers with a City NOT starting with "b", "s", or "p":*/
SELECT * FROM Customers
WHERE City LIKE '[!bsp]%';

INNER JOINT

SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;

Il render sarà:

1.Tabella Orders -> OrderID
2.Tabella Customers -> CustomerName -> al verificarsi della condizione -> Orders.CustomerID=Customers.CustomerID
3.Tabella -> OrderDate

UNION

/* UNION operator combines the result of two or more SELECT statements 
(only distinct values) */
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;

/* UNION ALL operator combines the result of two or more SELECT statements 
(duplicate values also) */
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;

/* With WHERE */
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;

SELECT INTO – INSERT INTO (create a copy)

The SELECT INTO statement copies data from one table and inserts it into a new table.

MySQL does not support SELECT INTO statement!!!

You can fix the problem:


/* Create a new table, with same structure, where you want to take backup */
CREATE TABLE destination_table_name LIKE source_table_name;

/* After then you can use this command to copy those data */
INSERT INTO destination_table_name 
SELECT * FROM source_table_name;

/* If you already have previous data in your Destination table , Firstly you can use this command */
TRUNCATE TABLE destination_table_name;

/* Copy only the columns FirstName, LastName */
INSERT INTO PersonsBackUp (FirstName, LastName)
SELECT FirstName, LastName FROM Persons;

CREATE DB

NOTICE: if you work with shared hosting services, the best way is CPanel Admin to create new Databases

CREATE DATABASE dbname;

CREATE TABLE

phpMyAdmin> LEFT COLUMN> ‘Crea tabella’

or


CREATE TABLE Persons
(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

INDEX

Indexes allow the database application to find data fast; without reading the whole table.

Note: Updating a table with indexes takes more time than updating a table without (because the indexes also need an update). So you should only create indexes on columns (and tables) that will be frequently searched against.


CREATE INDEX PIndex
ON Persons (LastName)

CREATE INDEX PIndex
ON Persons (LastName, FirstName)

DROP

It removes indexes, tables, and databases


/* Delete index */
ALTER TABLE table_name DROP INDEX index_name

/* Delete table */
DROP TABLE table_name

/* Delete database */
DROP DATABASE database_name

/* Delete table content only, preserve table */
TRUNCATE TABLE table_name

ALTER

The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.

Statement:
ALTER TABLE table_name
MODIFY COLUMN column_name datatype


ALTER TABLE Persons
ALTER COLUMN DateOfBirth year

ALTER TABLE Persons
DROP COLUMN DateOfBirth

AUTO INCREMENT

Very often we would like the value of the primary key field to be created automatically every time a new record is inserted.

By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record.


CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
)

/* Let the AUTO_INCREMENT sequence start with another value */
ALTER TABLE Persons AUTO_INCREMENT=100

By |MySQL, Web Design|Commenti disabilitati su MySQL Quick Reference – Basic

MySQL – Constraints

MySQL – Constraints

Tested on MySQL 5.5

Constraint: NOT NULL

The NOT NULL constraint enforces a field to always contain a value. This means that you cannot insert a new record, or update a record without adding a value to this field.


CREATE TABLE PersonsNotNull
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

Constraint: UNIQUE

The UNIQUE constraint uniquely identifies each record in a database table
A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it


/* Create new table */
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
UNIQUE (P_Id)
)

/* Create new table */
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
)

/* Modify an existing table */
ALTER TABLE Persons
ADD UNIQUE (P_Id)

/* Modify an existing table */
ALTER TABLE Persons
ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)

/* Drop constraint */
ALTER TABLE Persons
DROP INDEX uc_PersonID

Constraint: PRIMARY KEY

The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain unique values.
A primary key column cannot contain NULL values.
Each table should have a primary key, and each table can have only ONE primary key.


/* Create new table */
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)

/* Create new table */
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
)

/* Modify an existing table */
ALTER TABLE Persons
ADD PRIMARY KEY (P_Id)

/* Modify an existing table */
ALTER TABLE Persons
ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)

/* Drop constraint */
ALTER TABLE Persons
DROP PRIMARY KEY

Constraint: FOREIGN KEY

A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
It is used to prevent actions that would destroy links between tables.

Example:
“Persons” table: P_Id LastName FirstName Address City
“Orders” table : O_Id OrderNo P_Id

Note that the “P_Id” column in the “Orders” table points to the “P_Id” column in the “Persons” table.


/* Create new table */
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
)

/* Create new table */
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
)

/* Modify an existing table */
ALTER TABLE Orders
ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)

/* Modify an existing table */
ALTER TABLE Orders
ADD CONSTRAINT fk_PerOrders
FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)

/* Drop constraint */
ALTER TABLE Orders
DROP FOREIGN KEY fk_PerOrders

Constraint: CHECK

The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a single column it allows only certain values for this column.
If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.


/* Create new table */
/* "P_Id" must only include integers greater than 0 */
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CHECK (P_Id>0)
)

/* Create new table */
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')
)

/* Modify an existing table */
ALTER TABLE Persons
ADD CHECK (P_Id>0)

/* Modify an existing table */
ALTER TABLE Persons
ADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')

/* Drop constraint */
ALTER TABLE Persons
DROP CHECK chk_Person

Constraint: DEFAULT

The default value will be added to all new records, if no other value is specified.


/* Create new table */
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'Sandnes'
)

/* Create new table */
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
OrderDate date DEFAULT GETDATE()
)

/* Modify an existing table */
ALTER TABLE Persons
ALTER City SET DEFAULT 'SANDNES'

/* Drop constraint */
ALTER TABLE Persons
ALTER City DROP DEFAULT

By |MySQL, Web Design|Commenti disabilitati su MySQL – Constraints

WordPress – MySQL Snippets – Super Utili

WordPress – MySQL Snippets – Super Utili

Una pratica molto professionale consiste nell’accedere e modificare direttamente i dati nel Database di WordPress utilizzando i comandi di MySQL.
Il modo più facile per utilizzare i comandi MySQL è farlo da phpMyAdmin.


# Change Siteurl & Homeurl
UPDATE wp_options SET option_value = replace(option_value, 'http://www.oldsiteurl.com', 'http://www.newsiteurl.com') WHERE option_name = 'home' OR option_name = 'siteurl';

# Change GUID
UPDATE wp_posts SET guid = REPLACE (guid, 'http://www.oldsiteurl.com', 'http://www.newsiteurl.com');

# Change URL in Content
UPDATE wp_posts SET post_content = REPLACE (post_content, 'http://www.oldsiteurl.com', 'http://www.newsiteurl.com');

# Change Image Path Only
UPDATE wp_posts SET post_content = REPLACE (post_content, 'src="http://www.oldsiteurl.com', 'src="http://yourcdn.newsiteurl.com');
UPDATE wp_posts SET  guid = REPLACE (guid, 'http://www.oldsiteurl.com', 'http://yourcdn.newsiteurl.com') WHERE post_type = 'attachment';

# Update Post Meta
UPDATE wp_postmeta SET meta_value = REPLACE (meta_value, 'http://www.oldsiteurl.com','http://www.newsiteurl.com');

# Change Default "Admin" Username
UPDATE wp_users SET user_login = 'Your New Username' WHERE user_login = 'Admin';

# Reset Password
UPDATE wp_users SET user_pass = MD5( 'new_password' ) WHERE user_login = 'your-username';

# Assign all articles by Author B to Author A
UPDATE wp_posts SET post_author = 'new-author-id' WHERE post_author = 'old-author-id';

# Delete Revision
DELETE a,b,c FROM wp_posts a LEFT JOIN wp_term_relationships b ON (a.ID = b.object_id) LEFT JOIN wp_postmeta c ON (a.ID = c.post_id) WHERE a.post_type = 'revision'

# Delete Post Meta
DELETE FROM wp_postmeta WHERE meta_key = 'your-meta-key';

# Export all Comment Emails with no Duplicate
SELECT DISTINCT comment_author_email FROM wp_comments;

# Delete all Pingbacks
DELETE FROM wp_comments WHERE comment_type = 'pingback';

# Delete all Spam Comments
DELETE FROM wp_comments WHERE comment_approved = 'spam';
#     * 0 = Comment Awaiting Moderation
#     * 1 = Approved Comment
#     * spam = Comment marked as Spam

# Identify Unused Tags
SELECT * From wp_terms wt INNER JOIN wp_term_taxonomy wtt ON wt.term_id=wtt.term_id WHERE wtt.taxonomy='post_tag' AND wtt.count=0;

By |MySQL, Web Design, WordPress|Commenti disabilitati su WordPress – MySQL Snippets – Super Utili