How to insert data into a table using SQL? - mysql

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');

Related

INSERT INTO error in mysql (desc included)

I got tables like below and I am trying to INSERT data.
mysql> desc subscribers
-> ;
+---------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+----------------+
| id | smallint(6) | NO | PRI | NULL | auto_increment |
| email | varchar(32) | NO | | NULL | |
| comment | text | NO | | NULL | |
+---------+-------------+------+-----+---------+----------------+
Data insert
INSERT INTO `subscribers` VALUES (1, ‘someone#gmail.com’, ‘thanks’);
But It gives me an error.
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '#gmail.com’, ‘ thanks’)' at line 1
Does anybody see an error??
You are surrounding your strings to be inserted with some sort of apostrophe instead of a single quote. Use this instead (and copy it verbatim from this answer):
INSERT INTO `subscribers`
VALUES (1, 'someone#gmail.com', 'thanks');
Your problem is the curly single quote. But, to prevent future errors, you should always include the column list in the insert:
INSERT INTO `subscribers`(id, email, comment)
VALUES (1, 'someone#gmail.com', 'thanks');
In fact, a natural way to create the table is using an auto-incremented id. If you did then, then the INSERT would look like:
INSERT INTO `subscribers`(email, comment)
VALUES ('someone#gmail.com', 'thanks');
The id would be assigned automatically.

Insert random string into field with MySQL UNI key

The task is to fill the table with N rows of random unique data.
I have the next MySQL table structure:
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| username | varchar(20) | NO | UNI | NULL | |
+----------+--------------+------+-----+---------+----------------+
Username field has string type but if the script will insert numbers its OK.
Theres is dirty solution with INSERT IGNORE, that can make 1000 random rows with endless cycle.
INSERT IGNORE INTO table (id,username) VALUES ('', 1 + ceil(rand() * 1000));
Also, I can use ON DUPLICATE KEY structure, but this 2 solutions are not OK.
I want to make the query, that generate unique username which will be unique and will be inserted from the first time.
So, I tell the script to add 1m of rows and it will insert 1m of unique data without any infelicities.
Any ideas? Thanks.
You can use UUID() which will give you a random string which would fit in your field, guaranteed to be unique with slim chance of collisions.

Drop default constraint

I have a tableA with following output from desc tableA command:
+---------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(50) | NO | | | |
| city | varchar(50) | YES | | NULL | |
| state | char(2) | YES | | NULL | |
| country | varchar(30) | YES | | NULL | |
| notes | longtext | YES | | NULL | |
| type | varchar(50) | NO | | NULL | |
+---------+-------------+------+-----+---------+----------------+
Now there are 3 columns with NOT NULL constraints:
id
name
type
For columns id and type, I need to remove the default constraint. Basically I want Default: None. I do not want to use the workarounds eg . setting default to '' for a varchar.
The difference between NULL, NONE, and '' is made more clear from this discussion Default-values-for-varchar-and-int-mysql-data-types
I tried using the command:
alter table tableA alter column type drop default;
The query runs fine, but no rows are affected. And no change in Default value is shown when I run describe command.
If I set the default value to '' I run into different issue - the database allows the entry of empty string in the db. For me that is equivalent to inserting NULL for a column's value, and I do not want to allow that.
I need some guidance on how to handle Default values in this situation where I cannot allow empty strings as data in the db. I want to mention that I am planning to put validations in the code to check if the incoming data is an empty string or NULL. But just in case that validation is not working etc, I want to make sure the DB can refuse to add such data.
Any help is really appreciated.
If the column can be then null, then either default or null are the same.
So Allowed Null, Default null is effectively irrelevant except when doing say
Insert (name,city,type) Values ('Fred',DEFAULT,'Caucasian')
Null isn't an empty string. Given you are allowing null in the table but interpreting it as empty string in your application, you have an irritating flaw in your design.
If you don't want empty strings in there, normally you'd use a check constraint which as far as I know still isn't implemented in mysql. Apparently this lack is usually solved with an insert trigger.
So you'd check the value in the trigger and then fail the insert for empty strings.
PS it doesn't solve the integrity problem, but if you did want a way to put nulls in when a straing was empty so you would not have to distinguish between empty string and null.
Then have a look at the nullif function.

MySQL Insert data to table using column number not name

Do I have to know the name of the column so to be able to insert data ? because I need to insert data using column number (first column is 1...)
Instead of using this :
insert into my_table (column1, column2)
values (value1, value2)
Just use that :
insert into my_table values (value1, value2)
i.e. don't specify the list of columns.
Of course, this will only work if you pass data for the columns in the order they are defined in the table, though.
if you have a table like (for example) :
CREATE TABLE test (
id INT(10),
field1 VARCHAR(16),
field2 TINYINT(1)
);
you can execute the query
INSERT INTO test VALUES (1, 'field1 value', 0);
The insert values must be in the same order as the declared columns. And as Galz mentioned it, you must set all fields, even the nullable or the auto incrementing ones. In fact, for the latter, you have to pass a null value.
For example, if id were to be a primary key set to "auto_increment", this query
INSERT INTO test VALUES (null, 'foo', 1);
SELECT * FROM test;
Would return
+----+--------------+--------+
| id | field1 | field2 |
+----+--------------+--------+
| 1 | field1 value | 0 |
| 2 | foo | 1 |
+----+--------------+--------+
On another subject, if you don't know beforehand what is the order of the fields, you can execute this query :
show columns from <table name>;
which, in this case would return
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| id | int(10) | YES | | NULL | |
| field1 | varchar(16) | YES | | NULL | |
| field2 | tinyint(1) | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
Thus telling you that id is the first field, field1 is the second, and field2 is third.

How can I ensure that there is one-and-only-one row in DB table?

I would like to ensure that my MySQL table named "myTable" has one-and-only-one row.
So I need to be able to do Update on this row but obviously Insert and Remove should be not possible.
I am asking this question because of this Stack Overflow answer
Thanks!
CREATE TABLE `myTable` (
`id` enum('1') NOT NULL,
`MyValue1` int(6) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='The ENUM(''1'') construct as primary key is used to prevent that more than one row can be entered to the table';
Two suggestions for you, one or both which may work depending on the particulars of the data you're trying to store:
See if the ENUM or SET constraints will work for you; note that they offer differing levels of enforcement based on SQL mode (e.g., strict). See more info:
http://dev.mysql.com/doc/refman/5.0/en/constraint-invalid-data.html
AND/OR
Implement INSERT, UPDATE, and DELETE triggers to control access on the data (you may want to populate the data initially before you create these; again, it depends on your scenario)
http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html
The easiest approach is to create a column that only has one legal value, then to declare it not null unique.
This forces the table to have no more than one row, but still allows zero rows. If you need to prevent the removal of the only row, use the trigger approach given in a different answer.
create table example(
enforce_one_row enum('only') not null unique default 'only',
... your columns ....
);
Try this:
CREATE TABLE foo (x INT NOT NULL PRIMARY KEY CHECK (x = 1), col1 INT NOT NULL, col2 INT NOT NULL);
You can make use on tables privileges (assuming once you have set the relevant privileges to block insert/delete, and you should not update the privileges anymore, however, any user has the privileges can override the privileges again)
insert the one-and-only-one record first
then add in the privileges by disable INSERT, UPDATE, DROP in column table_priv
mysql> desc tables_priv;
+-------------+-------------------------------------------------------------------------------------------------------------------------+------+-----+-------------------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------------------------------------------------------------------------------------------------------------------+------+-----+-------------------+-------+
| Host | char(60) | NO | PRI | | |
| Db | char(64) | NO | PRI | | |
| User | char(16) | NO | PRI | | |
| Table_name | char(64) | NO | PRI | | |
| Grantor | char(77) | NO | MUL | | |
| Timestamp | timestamp | NO | | CURRENT_TIMESTAMP | |
| Table_priv | set('Select','Insert','Update','Delete','Create','Drop','Grant','References','Index','Alter','Create View','Show view') | NO | | | |
| Column_priv | set('Select','Insert','Update','References') | NO | | | |
+-------------+-------------------------------------------------------------------------------------------------------------------------+------+-----+-------------------+-------+
8 rows in set (0.00 sec)
If your database is set to 'strict' mode, you can create a table like this one:
create table foo (id enum('SYSROW') not null, (other column definitions) primary key (id));
create table if not exists myTable (
ID int not null
) engine=innodb;
select 'create trigger tbi_myTable';
drop trigger if exists tbi_myTable;
delimiter //
create trigger tbi_myTable
before insert on myTable
for each row
begin
if (select count(1) from myTable) > 0 then
-- Signal is only in 5.6 and above use another way to raise an error: if less than 5.6
SIGNAL SQLSTATE '50000' SET MESSAGE_TEXT = 'Cannot insert into myTable only one row alowed!';
end if;
END //
delimiter ;
insert into myTable values (1);
-- This will generate an error
insert into myTable values (2);
-- This will only have one row with "1"
select * from myTable;
You can check in mySQL using IF statement.
IF (SELECT count(*) FROM myTable) = 1
//your SQL code here.