My database table structure is
mysql> desc webhotel.`first`;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| one | varchar(45) | NO | PRI | NULL | |
+-------+-------------+------+-----+---------+-------+
1 row in set (0.19 sec)
I want to add ('Harshal') as field value for one
mysql> select * from webhotel.`first`;
+-------------+
| one |
+-------------+
| ('Harshal') |
+-------------+
1 row in set (0.00 sec)
I want this output
My problem is that i don't know how to insert a string containing single quotes into the database. I can use the IDE to do it, but i want an insert query.
Are you looking for this?
INSERT INTO first (one) VALUES ('(''Harshal'')');
^^ ^^
Outcome:
| ONE |
|-------------|
| ('Harshal') |
Here is SQLFiddle demo
If the value contains single quotes, you can use double quotes in MySQL to enter the string:
INSERT INTO first (one)
VALUES ("('Harshal')");
or you can escape the quotes:
INSERT INTO first (one)
VALUES ('(\'Harshal\')');
depending on the server side software you are using, you should look into 'prepared statements'. here's the link for PHP, which provides easy to follow code. while the other answers technically work, prepared statements were created to specifically address this problem, and will help alleviate some of the issues the other answers will give you.
Below are the two ways you can use insert query.
INSERT into tablename values ('colValue1', 'colValue2')
INSERT into tablename (`colname1`, `colname2`) values ('colValue1', 'colValue2')
Visit http://www.w3schools.com/sql/sql_insert.asp for more sql tutorials
Related
I'm trying to practice sql using w3resource's sample activities. They gave an answer to that activity but they do not have further explanation on to why they used a specific script, and I want to know what would be the difference when I would do this.
Write a SQL statement to create the structure of a table dup_countries similar to countries.
Answer:
CREATE TABLE IF NOT EXISTS dup_countries LIKE countries;
Output:
mysql> DESC dup_countries;
+--------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+---------------+------+-----+---------+-------+
| COUNTRY_ID | varchar(2) | YES | | NULL | |
| COUNTRY_NAME | varchar(40) | YES | | NULL | |
| REGION_ID | decimal(10,0) | YES | | NULL | |
+--------------+---------------+------+-----+---------+-------+
3 rows in set (0.03 sec)
Write a SQL statement to create a duplicate copy of countries table including structure and data by name dup_countries.
Answer:
CREATE TABLE IF NOT EXISTS dup_countries AS SELECT * FROM countries;
Output:
mysql> DESC dup_countries;
+--------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+---------------+------+-----+---------+-------+
| COUNTRY_ID | varchar(2) | YES | | NULL | |
| COUNTRY_NAME | varchar(40) | YES | | NULL | |
| REGION_ID | decimal(10,0) | YES | | NULL | |
+--------------+---------------+------+-----+---------+-------+
3 rows in set (0.11 sec)
You can of course check the documentation (CREATE TABLE ... LIKE Statement, CREATE TABLE ... SELECT Statement) but there're two main differences:
CREATE TABLE LIKE creates an empty table, while CREATE TABLE SELECT inserts selected rows.
CREATE TABLE LIKE copies source table definitions, indexes included, while
CREATE TABLE SELECT figures out column types from actual data found (you don't necessarily have a source table to begin with, it can be any kind of dynamically generated result-set) and also allows you set the types manually.
We can Clone Table using two ways:
using Like
using As Select * from TableName.
1st Way:
CREATE TABLE new_table AS SELECT * FROM original_table;
It inherits only basic definitions,null settings and default values.
But doesnt inherit indexes and auto increment definitions.
It copy just structure and data.
2nd Way:
CREATE TABLE new_table LIKE original_table;
Inherit all table definitions without Data.
If we wants Data,we can use
INSERT INTO new_table SELECT * FROM original_table;
CREATE TABLE IF NOT EXISTS dup_countries LIKE countries;
is not equal to
CREATE TABLE IF NOT EXISTS dup_countries AS SELECT * FROM countries;
The main difference - 2nd query adds rows into newly created table whereas 1nd one creates empty table.
You may eliminate this difference by adding a condition to 2nd query:
CREATE TABLE IF NOT EXISTS dup_countries AS SELECT * FROM countries WHERE FALSE;
Both 1st and 3rd query produces the same result - empty table.
But the differences exists nevertheless. And they may be critical.
1st query copies a lot of constructions into the table-copy. Indices. Constraints (including NOT NULL, PRIMARY KEY...). Comments. And so on... And even generated columns definitions.
Whereas 2nd and 3rd queries creates "cleared" structure - only base properties are reproduced.
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=7bbebd3667bd333f1ca55edfeac04ae8
PS. And none query copies foreign keys and triggers.
Insert into the App.settings table the following values:
(99, DEFAULT, "horizontal", "2015-09-15 04:01:04")
I have a DATABASE called App with a settings table. I am trying to insert into the table but I can not seem to get it right.
My statement:
INSERT INTO App.settings
VALUES(99, DEFAULT, "horizontal", "2015-09-15 04:01:04");
Am I doing it right? It says my answer is wrong.
mysql> DESC App.settings;
+-----------------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+---------------------+------+-----+---------+-------+
| user_id | int(7) | NO | | NULL | |
| email_frequency | tinyint(2) unsigned | YES | | NULL | |
| layout | varchar(70) | YES | | NULL | |
| updated_at | datetime | YES | | NULL | |
+-----------------+---------------------+------+-----+---------+-------+
4 rows in set (0.01 sec)
When you use insert, always list the columns in the table. Second, the default string delimiter is the single quote in SQL rather than the double quote.
So I would expect to see:
INSERT INTO App.settings (col1, col3, col4) -- your real column names here
VALUES (99, 'horizontal', '2015-09-15 04:01:04');
Note that col2 was removed from the INSERT and the VALUES because you seem to want a DEFAULT value. Not all databases support that syntax.
you are sure that all the fields of the tuple are there and if so, they are in the correct order if you are not entering all the fields of the tuple you should use the following form: INSERT INTO App.settings(value, config, position, date ) VALUES(99, "DEFAULT", "horizontal", "2015-09-15 04:01:04");
In the same order
this is only an example i dont know the fields names you must be change for the you are using
Like #GordonLinoff said, you should include the columns in your query. That way, you can also skip entering the DEFAULT value for email_frequency.
As for the mistake, it's most likely the double quotes that you're currently using instead of single quotes.
Try the following:
INSERT INTO App.settings (user_id, layout, updated_at)
VALUES (99, 'horizontal', '2015-09-15 04:01:04');
I want to copy a table, including its indexes and triggers, from one database to another. This is not as straightforward as I had hoped. Here is a minimal working example (MWE) to demonstrate. First, my MariaDB version:
$ mysql --version
mysql Ver 15.1 Distrib 10.0.29-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2
Next, the first table:
CREATE DATABASE db1;
USE db1;
CREATE TABLE tb1 (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
word VARCHAR(50) NOT NULL);
INSERT INTO tb1 (word) VALUES ('foo');
DELETE FROM tb1 WHERE word='foo';
DELIMITER $$
CREATE TRIGGER before_word_insert BEFORE INSERT ON tb1 FOR EACH ROW
BEGIN
SET NEW.word=TRIM(NEW.word);
IF NOT (NEW.word REGEXP '^[[:alpha:]]+$') THEN
SIGNAL SQLSTATE '12345' SET MESSAGE_TEXT = 'Invalid word';
END IF;
END$$
DELIMITER ;
INSERT INTO tb1 (word) VALUES ('foo');
DESCRIBE tb1;
SHOW TRIGGERS;
SHOW INDEX FROM tb1;
These last three lines give:
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| word | varchar(50) | NO | | NULL | |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
+--------------------+--------+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------+--------+---------+----------+----------------+----------------------+----------------------+--------------------+
| Trigger | Event | Table | Statement | Timing | Created | sql_mode | Definer | character_set_client | collation_connection | Database Collation |
+--------------------+--------+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------+--------+---------+----------+----------------+----------------------+----------------------+--------------------+
| before_word_insert | INSERT | tb1 | BEGIN SET NEW.word=TRIM(NEW.word); IF NOT (NEW.word REGEXP '^[[:alpha:]]+$') THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Invalid word'; END IF; END | BEFORE | NULL | | root#localhost | utf8 | utf8_general_ci | latin1_swedish_ci |
+--------------------+--------+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------+--------+---------+----------+----------------+----------------------+----------------------+--------------------+
1 row in set (0.04 sec)
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| tb1 | 0 | PRIMARY | 1 | id | A | 3 | NULL | NULL | | BTREE | | |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
1 row in set (0.00 sec)
So far, so good. Now, to copy tb1 to another database (on the same server):
CREATE DATABASE db2;
USE db2;
CREATE TABLE db2.tb1 AS SELECT * FROM db1.tb1;
DESCRIBE tb1;
SHOW TRIGGERS;
SHOW INDEX FROM tb1;
I had hoped these last three lines would give identical output as they did for db1, but they don't:
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | int(11) | NO | | 0 | |
| word | varchar(50) | NO | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
Empty set (0.00 sec)
Empty set (0.00 sec)
In other words, CREATE TABLE db2.tb1 AS SELECT * FROM db1.tb1;:
copied the table contents;
copied the column types;
did not copy the "Key" property;
did not copy the "Default" property;
did not copy the "Extra" property;
did not copy the triggers; and
did not copy the indexes.
My question: what would be a concise equivalent to CREATE TABLE db2.tb1 AS SELECT * FROM db1.tb1; that would copy all of those missing items?
CREATE TABLE newTable LIKE oldTable
should include the indexes and setup, although not the data and triggers.
After that, you need to copy the data:
INSERT INTO newTable SELECT * FROM oldTable
The triggers are not directly part of the table but rather part of the script management.
You can find the triggers in information_schema.triggers. There you can query every trigger set for your table. But I strongly recommend not to mess around with that table manually.
Instead, you can read the definition there and create a new trigger using SHOW CREATE TRIGGER and CREATE TRIGGER. That involves either dynamic sql or a client able to manipulate the sql (which should apply to every client).
If there is a client connected to the source database and to the target database, you can do something like that:
SELECT `TRIGGER_NAME` FROM information_schema.triggers WHERE `TRIGGER_SCHEMA` = database() AND `EVENT_OBJECT_TABLE` = oldTableName
As you stated in the comments, you can also use
SHOW TRIGGERS WHERE `Table` = "oldTable"
instead of reading the triggers table. As a side note, these backticks around Table are important, because Table is a reserved word which is used here in a manner like a column name.
With the trigger names, for each trigger you cast a
SHOW CREATE TRIGGER triggerNameFromQueryAbove
This gives you the create statement you can use to create the trigger in the new database. But careful: There might be the database name included and the definer, which may not exist in the new database, so you have to strip out that information manually.
For more information on the "triggers" table, read the mysql manual (which also should apply to mariadb): https://dev.mysql.com/doc/refman/5.7/en/triggers-table.html
I'm looking at this question, because I have the same question. I'm a bit dismayed, if there really are no more concise commands to do this. I want to point out a (perhaps obvious) procedure that will also work. You could dump the database to a file ("dumpdb1.sql", for example) which is already handy if you're using mysqldump for backups. You could then of course make a copy of just the relevant text out of dumpdb1.sql that creates tb1, sets its constraints and indexes, and adds its triggers and data, placing this excerpt into a file "buildtb1.sql". Finally, just run this latter file on db2 and you should get a perfect full copy of tb1 there.
Also, I see in the MariaDB documentation at: Tutorialspoint MariaDB Table Cloning they point out the usefulness of the SHOW CREATE TABLE statement in this regard. It will give a CREATE TABLE statement you can copy and use during this process. I'm just mentioning this as an alternative to the mysqldump approach, if you don't want to use that. Of course SHOW CREATE TABLE will not describe triggers, so you would still need to perform a SHOW TRIGGERS process to capture and reproduce those.
I'm using MySQL on a CentOS server from a website running Apache and Perl. I'm seeing this behavior (mocked up):
mysql> describe product;
+-------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(10) | YES | | NULL | |
+-------+------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
mysql> insert into product (name) values ('Widget');
Query OK, 1 row affected (0.00 sec)
mysql> insert into product (name) values ('Thing');
Query OK, 1 row affected (0.00 sec)
mysql> select * from product;
+----+--------+
| id | name |
+----+--------+
| 1 | Widget |
| 2 | Widget |
| 3 | Thing |
+----+--------+
3 rows in set (0.00 sec)
My theory is that the Perl CGI script may be executed concurrently (perhaps due to double click, browser refresh, etc.) so the insert gets performed twice. This is fairly rare but causes problems when it happens.
In cases where this happens, all columns except 'id' have identical values. Other than column 'id' duplicate values are allowed.
Is there a way to prevent this behavior?
If you installed Perl, Apache, and MySQL from CentOS repositories and didn't make any radical configuration changes, it's highly unlikely you've found a bug in the platform. Are you using mod_perl or PSGI or is it definitely CGI? Have you installed any Perl modules from CPAN sources or has everything been installed through yum?
A stupid solution you might consider implementing is generating some kind of nonce (one-time-use string or number) in your script, adding a column for it and a unique index on that column to your table, and inserting it along with the rest of the form data. If you catch a duplicate key error, just disregard it. That won't explain what's happening but it will prevent it from happening.
How can I get just the table comment from a mysql table? I tried the following, but they didn't work for various reasons. I want to figure out how to get just the string 'my comment' (ideally via perl =)
Any help?
-- Abbreviated output for convenience.
SHOW TABLE STATUS WHERE Name="foo"
+------+--------+---------+------------+------+----------------+---------------+
| Name | Engine | Version | Row_format | Rows | Create_options | Comment |
+------+--------+---------+------------+------+----------------+---------------+
| foo | MyISAM | 10 | Fixed | 0 | | my comment |
+------+--------+---------+------------+------+----------------+---------------+
and
SHOW CREATE TABLE foo;
+-------+------------------------------------------------------------------------------+
| Table | Create Table |
+-------+------------------------------------------------------------------------------+
| fooo | CREATE TABLE `fooo` (`id` int(11) NOT NULL PRIMARY KEY) COMMENT='my comment' |
+-------+------------------------------------------------------------------------------+
Based on the answer by OMG Ponies, but using INFORMATION_SCHEMA.TABLES instead of INFORMATION_SCHEMA.COLUMNS. When looking around on the web, all I could find was info on the columns' comments, but never on the table's. This is how to get a table's comment.
SELECT table_comment
FROM INFORMATION_SCHEMA.TABLES
WHERE table_schema='my_cool_database'
AND table_name='user_skill';
+--------------------------+
| table_comment |
+--------------------------+
| my awesome comment |
+--------------------------+
If you don't want to have both database name and table name in the query, you can use :
SHOW TABLE STATUS WHERE Name='table_name';
and then pick up the "Comment" key of the result (you have to use an associative function like mysqli_fetch_assoc() in php).