MySQL table snippets and fixes to common problems

MySQL table snippets?

Yes, there are quite a few of them in this article. But before we get to that, what is MySQL? Let’s start with the MySQL definition. MySQL is an Oracle-backed open source relational database management system (RDBMS) based on Structured Query Language (SQL).

Applications that use the MySQL database include TYPO3, MODx, Joomla, WordPress, Simple Machines Forum, phpBB, MyBB, and Drupal. MySQL is also used in many high-profile, large-scale websites, including Google (though not for searches), Facebook, Twitter, Flickr, and YouTube.

And after all that intro, you realize that MySQL is bigger than you initially thought. Unless you’ve been around for a while in the industry. If you are a newcomer, however, and you want to learn more about MySQL, the easiest way to do it is with MySQL table snippets. You’ll most likely need a good SQL tool for them.

MySQL table snippets

Match a string at the beginning of string

SELECT 'Test' REGEXP '^The'; -- 0
SELECT 'The Test' REGEXP '^The'; -- 1

If a name is not prefixed with ‘The ‘ then add it

UPDATE [table]
SET Name = CONCAT('The ', TRIM(Name))

Copy a column from one table to another

INSERT INTO [table] ([column]) SELECT [column] FROM [table]

Remove all whitespace

UPDATE [table] SET [column] = REPLACE([column], ' ', '')

(this is BASH) drop all tables in a database

mysqldump -u[USERNAME] -p[PASSWORD] --add-drop-table --no-data [DATABASE] | grep ^DROP | mysql -u[USERNAME] -p[PASSWORD] [DATABASE]

Change to collation of a table and all of its existing columns

alter table [table] convert to character set utf8 collate utf8_general_ci;

MySQL Find and Replace

UPDATE files SET filepath = REPLACE(filepath,'path/to/search','path/to/replace');

Selecting a Random Row In MySQL

SELECT column FROM table

Create CSV from MySQL


Find duplicate records

SELECT id, COUNT(*) as n
FROM my_table
HAVING n >1;

Correcting wrong character encoding in MySQL data

UPDATE table SET column=CONVERT(CONVERT(CONVERT(column USING latin1) USING binary) using utf8);

Load CSV back into mySQL

LOAD DATA local INFILE 'unique.csv' INTO TABLE tablename
(col1, col2, col3)

Drupal 6.x Find PHP code in database

select nid, vid from node_revisions where format in (select format from filters where module = 'php' and delta = 0);
select cid, nid from comments where format in (select format from filters where module = 'php' and delta = 0);
select bid, info from boxes where format in (select format from filters where module = 'php' and delta = 0);

Generate random string in MySQL


Calculate Age from Date Of Birth


Find & Replace

UPDATE table_name SET column_name = REPLACE(column_name, 'http:\/\/', 'http:\/\/');

Select between two dates

SELECT * FROM files LEFT JOIN (dates) ON files.uploaded_id = WHERE date BETWEEN '2009-01-01' AND '2009-12-31'

Backup MySQL Database to SQL File with mysqldump

mysqldump --user=username --password=password --opt --add-drop-database --databases databasename > ~/path/to/file.sql

how to calculate last 7 days


mysql dump

mysqldump -u [username] -p [password] [databasename] > [backupfile.sql]

Mysql replace

# Replace string in all records from a table
UPDATE table_name SET column_name = REPLACE( column_name, '/dev', '' );
# Display a modified record set
SELECT REPLACE( column_name, '/dev', '' ) FROM table_name;

Convert timezone to local

SELECT CONVERT_TZ(mydatefield,'US/Pacific','CET') FROM mytable;

Search and Replace on Multiple Rows in SQL

UPDATE wp_posts SET post_content = REPLACE(post_content, '', '');

How to Save results from MySQL into an external file

echo "SELECT columns FROM table_name WHERE whatever='something'" | /path/to/mysql -uUSERNAME -pPASSWORD DATABASENAME > /tmp/outfile.txt;

Insert or update if unique key already exist

INSERT INTO `tableName`
VALUES (?,?,?,'-1',?,'0')
UPDATE `id` = ?, `foo` = ?, `bar` = ?

mySQL – database backup commands

-- dump mySQL database to file:
VAR=$(date +�%y-%m-%d�); mysqldump -v -uUSERNAME -pPASSWORD -hlocalhost DATABASENAME > /BACKUPDIR/$VAR-DATABASENAME.sql ;

-- dump mySQL database to file and then move it:

MySql import

mysql -u [username] -p [dbname] < [filename].sql

find duplicate records

select address, count(address) as cnt
from mailing_list
group by address
having cnt > 1
order by cnt;

MySQL Find and Replace

update TABLE_NAME set FIELD_NAME = replace(FIELD_NAME, 'find this string', 'replace found string with this string');

Change Drupal file directory path

UPDATE FILES SET filepath = REPLACE(filepath, 'sites/default/files/old/','sites/default/files/new/');

Find all tables in MySQL database containing specific column names

WHERE COLUMN_NAME IN ('columnA','ColumnB')
AND TABLE_SCHEMA='YourDatabase';

Find values that occur exactly once in table

SELECT email
FROM users
GROUP BY email
HAVING ( COUNT(email) = 1 )

MySql script to find invalid email addresses

SELECT * FROM people WHERE email NOT LIKE '%_@__%.__%'

MySQL Age Calculation

DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(DOB, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(DOB, '00-%m-%d')) >= 65

Left Joins to link three or more tables

select * from (bdg left join res on = left join dom on res.rid = dom.rid where dom.rid is NULL;

MySQL REGEX match comma-delimitted list

WHERE id REGEXP '(,|^){$this->id}(,|$)'

Get random record based on weight

SELECT * FROM Table ORDER BY Rand( ) * ( 1 / Weight

FAQs about MySQL table snippets

1. What is a MySQL table snippet, and how does it differ from a regular table?

A table snippet in MySQL is a portion of a table that only contains a particular set of data. It features columns and rows, much like a typical table, however, it only contains a subset of the data from the original database.

A SELECT statement that defines the desired columns and rows from the original table is used to construct a snippet. This method allows you to extract specific data for analysis or reporting, making it a valuable technique for dbt testing and data management.

2. Can I use snippets to extract specific data from a MySQL table?

Absolutely, relevant data can be extracted from a MySQL table using snippets. You can generate a snippet that only contains the information you require by defining the desired columns and rows in a SELECT statement. When you only need to work with a tiny portion of data from a larger table, this can be helpful.

3. How do I create a snippet of a MySQL table in a database?

You can use a SELECT query to extract a portion of a MySQL table by specifying the appropriate columns and rows in the original table. For instance, you could use the following SQL statement to construct a portion of a table called “customers” that just has the “name” and “email” columns: SELECT customer name, email FROM. You can use the snippet like you would any other table in your database once it has been created.

4. Can snippets be used to join multiple MySQL tables together?

Indeed, you may join different MySQL tables together using snippets. You can extract portions of the tables you want to join, then merge them with a JOIN statement. You may use a JOIN statement to merge two database snippets, for instance, if you have a snippet of a table called “customers” and a snippet of a table called “orders” based on a common column, such as customer ID.

5. Is it possible to modify a MySQL table snippet, and if so, how?

No, you cannot directly alter a MySQL table fragment. Snippets can only be read; they cannot be edited, removed, or added to. A new snippet must be created and the original table modified if the data in a snippet has to be changed.

6. How can I export a MySQL table snippet to another database or server?

Use the command-line tool mysqldump to export a portion of a MySQL table to another database or server. With the help of this tool, you may make a backup of an entire database, including all of its tables and excerpts. The mysql command-line tool can then be used to import the backup onto another database or server.

7. Can I delete a MySQL table snippet without affecting the original table?

Yes, a MySQL table snippet can be deleted without impacting the original table. Snippets are distinct database objects that can be deleted without having any negative effects on the parent table. You can use the DROP TABLE statement and the snippet’s name to delete a snippet.

8. Are there any limitations to using MySQL table snippets, such as size or performance?

True, using MySQL table snippets has its restrictions. The amount of memory that can be used by your system determines how big a snippet may be, therefore creating a big snippet might affect performance. Snippets are read-only, thus they might not be appropriate for all use scenarios.

9. How can I ensure that the data in a MySQL table snippet is up-to-date with the original table?

When changes are made to the original table in MySQL, the table snippets are not immediately updated. You will need to recreate the snippet on a regular basis to make sure the data is current. A SELECT statement can be used to accomplish this manually, or you can use a script to automate the process.

10. Is it possible to create a snippet of a MySQL table with only specific columns?

Yes, it is possible to extract a portion of a MySQL table that contains only particular columns. Use a SELECT statement from the original table that specifies the necessary columns to accomplish this.

For instance, if your “employees” database contains columns for “name,” “address,” and “phone number,” you could use the following SQL query to produce a snippet that just contains those columns: FROM employees: SELECT name, phone number. You may deal with a more condensed and limited subset of the data by doing this to create a snippet that just includes the information from those two columns.


We hope that these MySQL table snippets are the thing you were looking for. We will update this article with other MySQL snippets that we come across in the future, so make sure to bookmark it.

If you enjoyed reading this article about MySQL table snippets, you should also read these:

Sanja Pajic
Sanja Pajic

Full Stack Web Developer

Articles: 40