Home >Database >Mysql Tutorial >How Do I Insert or Select Values with Apostrophes in SQL?
Insert a value containing single quotes in SQL
Users may encounter errors when trying to insert values containing single quotes into a SQL database. This is because single quotes are special characters in SQL that indicate the beginning and end of a string.
Solution:
To insert a value containing single quotes, it must be escaped using double single quotes (''). For example:
<code class="language-sql">INSERT INTO Person (First, Last) VALUES ('Joe', 'O''Brien')</code>
Escape single quotes in SELECT queries:
The same principle applies to SELECT queries. To retrieve a value containing a single quote, it must be escaped:
<code class="language-sql">SELECT First, Last FROM Person WHERE Last = 'O''Brien'</code>
Understanding single quotes in SQL
Single quotes are used to separate string literals in SQL. To include a single quote in a string, it must be escaped to distinguish it from the delimiter.
Best Practices:
It is generally recommended to avoid manually editing data using raw SQL as it increases the risk of SQL injection attacks. Modern frameworks and techniques handle special character escaping efficiently and prevent such vulnerabilities.
The above is the detailed content of How Do I Insert or Select Values with Apostrophes in SQL?. For more information, please follow other related articles on the PHP Chinese website!