There are two relations (bold keys are attributes):
Apartment(apartmentId,address,unit,sqft)
Own(name,apartmentId)
For the Own relation, I want to insert a tuple with the name 'Bob Smith' and apartmentId corresponding to an address of 100 East Green Street and unit of 204. I know you can do an SQL statement with "INSERT INTO R(A1,...,An) VALUES(V1,..,Vn). But is it possible for me to insert the tuple with the value of 'Bob Smith' and an apartmentId from a subquery?
Sure you can! It is a very basic query so you may want to read your source material a little more and it may provide your answer for you, but it would be something like:
INSERT INTO R(A1, … An) SELECT A1, … An FROM <table_name_goes_here>
You don’t use the VALUES keyword in the syntax when you are inserting the values from a query into a table.
EDIT based on your comment: if you want a hardcoded value, sure! Just add it to your selection, eg:
INSERT INTO Own ( Name, ApartmentID ) SELECT 'Bob Smith', ApartmentId FROM <some_table>
Related
Still learning sql, but I'm not understanding how all the data I'm putting in my tables are set to 0 or NULL ?
You need to split up the columns and VALUES into separate statements (also the id should get added automatically since you have it as an identity, so you don't need to explicitly use it).
Try this:
INSERT INTO users (email, name, forename, pwhash)
VALUES ('mail', 'name', 'blaa', 'befbf');
You can use this to insert multiple values at once if you need to
INSERT INTO users (email, name, forename, pwhash) VALUES
('mail', 'name', 'blaa', 'befbf'),
('mail2', 'another name', 'blaa2', 'befbf123'),
('mail3', '1 more name', 'blaa3', 'befbf456'),
('mail4', 'one final name', 'blaa4', 'befbf789');
(Etc.)
The correct command:
insert into users (email, name, forename, pwhash) values ('mail', name, 'blaa', 'befbf')
You are getting null as sql format is wrong. Id is 1 because that is auto incremented as defined by you. But other columns are null or 0.
Try
INSERT INTO users (email, name, forename, pwdssh)
VALUES ('email', 'name', 'blaa', 'befbf');
id should be autoincremented as a primary key so no need to specify it. If you want to do it inline as you have attempted, I don't think a hyphen is the right syntax, it would be an equals, as in email='email'
Explicitly listing the column names like this means you can specify the Column names followed by VALUES in any order. You could also miss out the column names and just say:
INSERT INTO users
VALUES ('email', 'name', 'blaa', 'befbf');
Where the values are listed in the order that the columns are defined. Doing it this way, the order becomes important.
You may find this quite useful
You don't need to specify "field={value}", just put in the values in the proper order.
INSERT INTO Table (Field1,..., FieldN)
VALUES ('Value1',....,'ValueN');
https://www.w3schools.com/mysql/mysql_insert.asp
I have mysql query to replace some records:
REPLACE INTO product_core
(id, title, description, category_id)
VALUES (2, 'new_title', 'new_description', 33)
Can I do the same, but not providing all needed values? Example:
REPLACE INTO product_core
(id, title, description, category_id)
VALUES (2, 'new_title', 'new_description') #no category_id
Got error wrong number of values here near
I want to bulk replace many records, but I do not want to query all fields before. In this example, I want to update category_id for some records, but not for all.
REPLACE INTO product_core
(id, title, description, category_id)
VALUES (2, 'new_title_2', 'new_description_2'), #no category_id
(3, 'new_title_3', 'new_description_3', 34) #with category_id
Is it real to do this? Replace some fields for one record and other fields for second record in one query.
Or if is it real to provide special variable meaning that some fields will be the same as before replace (category_id)?
VALUES (2, 'new_title_2', 'new_description_2', #category_id_same_as_before)
Can I do the same, but not providing all needed values? Example:
REPLACE INTO product_core (id, title, description, category_id) VALUES
(2, 'new_title', 'new_description') #no category_id
Yes, the correct query is:
REPLACE INTO product_core
(id, title, description)
VALUES (2, 'new_title', 'new_description') #no category_id
EDIT: As Tom commented below the above might be misleading as for the omitted columns default values will be used, not the ones set for the record which is being replaced.
Is it real to do this? Replace some fields for one record and other fields for second record in one query.
It's not possible in MySQL. The column list is common for all the values sets.
Or if is it real to provide special variable meaning that some fields
will be the same as before replace (category_id)?
It's perhaps possible, but not straightforward and not in all MySQL versions. In the docs they say: "You cannot refer to values from the current row and use them in the new row".
In MySQL > 8.0.19 perhaps VALUES(ROW) can help. Or you can perhaps write you own UDF which does it.
You can't omit these columns from a REPLACE command, unless it is the default value for the column.
According to the documentation:
Any missing columns are set to their default values. [...] You cannot refer to values from the current row and use them in the new row.
It may be better to use a standard UPDATE command instead, which can reference the current column value.
I understand how to do an insert into when all the input data is known, and I know how to do an insert into when all the data is dependent on a select, but I can't find how to do the in between. Where I'm at now:
INSERT INTO takes (stu_id, "CS-001", 1, "Autumn", 2009, null)
VALUES (SELECT id AS stu_id
FROM student
WHERE dept_name = "Comp. Sci.")
Thus I know all the other input data except the student's id, however MySQL just gives me a syntax error.
INSERT INTO takes (stu_id, col2, col3, col4, col5, col6)
SELECT id, 'CS-001', 1, 'Autumn', 2009, null
FROM student
WHERE dept_name = 'Comp. Sci.'
I don't know your destination column names - you have to replace them with the real ones in the query above.
Insert queries can be structured like this:
insert into table
(field1, field2, etc)
(value1, value2 etc)
or like this:
insert into table
(field1, field2, etc)
select this, that, etc
from etc
You tried to combine the two. That's one of the reasons you got an error.
juergen's answer is an example of the 2nd construct. His this and that is a combination of fields and constant values. That's perfectly ok. If you are getting syntax errors, it's in your details. His answer shows the right general idea.
It's often worthwhile to build your query step by step. Start with this:
insert into takes
(stu_id)
select id
from student
where dept_name = 'Comp. Sci'
If that works, add one field inside the brackets and whatever is appropriate to the select clause of your query. Keep going with these baby steps until you get it right. It's an approach I often take.
I have a table named student which consists of (rollno, name, sem, branch)
If I want to INSERT only one value (i.e only name has to be entered) what is the query?
To insert values into specific columns, you first have to specify which columns you want to populate. The query would look like this:
INSERT INTO your_table_name (your_column_name)
VALUES (the_value);
To insert values into more than one column, separate the column names with a comma and insert the values in the same order you added the column names:
INSERT INTO your_table_name (your_column_name_01, your_column_name_02)
VALUES (the_value_01, the_value_02);
If you are unsure, have a look at W3Schools.com. They usually have explanations with examples.
insert into student(name) values("The name you wan to insert");
Be careful not to forget to insert the primary key.
First, if the table is all empty, just wanna make the column 'name' with values, it is easy to use INSERT INTO. https://www.w3schools.com/sql/sql_insert.asp.
`INSERT INTO TABLE_NAME (COLUMN_NAME) VALUES ("the values")`
Second, if the table is already with some values inside, and only wanna insert some values for one column, use UPDATE. https://www.w3schools.com/sql/sql_update.asp
UPDATE table_name SET column1 = value1 WHERE condition;
insert into student (name)
select 'some name'
or
insert into student (name)
values ('some name')
Following works if other columns accept null or do have default value:
INSERT INTO Student (name) VALUES('Jack');
Further details can be found from the Reference Manual:: 13.2.5 INSERT Syntax.
Execute this query, if you want the rest of columns as "#", do insert # inside the single quote which is left blank in query.
Also, there is no need of defining column name in the query.
insert into student values('','your name','','');
Thanks...
I'm dealing with a relational table and I've been wondering if there's a way to lower the number of queries I need to make when inserting data to the tables..
Here are the queries I currently use:
I insert the "main" values.
INSERT INTO products
(title, description, status, url)
VALUES
('some title', 'description of doom', 1, 'some-title');
We make it insert the value only if it doesn't exist already.
INSERT IGNORE INTO values
(value)
VALUES
('example value');
Since I'm not sure if the query was actually inserted, I get the id..
SELECT id
FROM
values
WHERE
value = 'example value';
Where "?" is the ID I got from the last query.
INSERT INTO link
( id_product, id_catalog, id_value )
VALUES
( 33, 1, ? );
This means that each extra value I need to add will cost 3 queries. So my question is: Is there a more efficient way to do this?
You can do this to at least drop one of the queries:
INSERT INTO link
( id_product, id_catalog, id_value )
VALUES
( 33, 1, (SELECT id
FROM values
WHERE value = 'example value') );
I basically am replacing the '?' with a sub select of the second query to get the id.
"Is there a more efficient way to do this?"
No. Not really. Creating three things takes three inserts.
You should be able to tell whether the insert succeeded with the ROW___COUNT() function from inside MySQL. If calling from another language (e.g. PHP), the mysql_query or equivalent function will return the row count.
You could use an INSERT INTO ... ON DUPLICATE KEY UPDATE statement.
This does, however, require that the primary key be one of the values for the insert, so it doesn't work on tables with an auto-increment.