Inserting into table - sql

I have this table on an Oracle server with this structure:
Create table temp
(
input number(10),
str varchar(24),
constraint L_PK PRIMARY KEY(input, str)
)
I made one alteration on it:
alter table temp add userID number(10);
Now I am trying to do an insert:
insert into temp values (9, 7, 'sure.');
But I am getting a error saying:
ORA-01722: Invalid Number
Any ideas? I'm pretty sure its coming from the 'sure' but I can't say for sure.

Specify the column-names when you are inserting so the appropriate data is inserted into the columns.
insert into temp (input, userid, str)
values (9, 7, 'sure.');

So you created a table with two columns:
Create table temp(
input number(10),
str varchar(24),
constraint L_PK PRIMARY KEY(input,str),
Made one alteration to it:
alter table temp add userID number(10);
Which leaves you with a table with columns input, str, and userID in that order. You then try to insert
insert into temp values (9, 7, 'sure.');
which tries to insert 9 into input (fine), 7 into str (not fine), and sure into userID (again, not fine).
You need to either use the values in the proper order to match the column order:
insert into temp values (9, 'sure', 7);
or (much better and safer) specify the columns first, and then assign the values to match:
insert into temp (input, userID, str) values (7, 9, 'sure');

In your case:
insert into temp values (9, 7, 'sure.');
It means:
INSERT INTO temp (input, str, userId)
VALUES (9, 7, 'sure.');
As 'sure.' does not a number type, Oracle server certainly gets error.

If you don't change the insert order,you should change the alteration SQL:
alter table temp add userID number(10) after str;
Yes,'after str' is appended.
Or you could change the insert order like this:insert into temp values (9, 'sure', 7);
Whatever you must remember that column should match with the value,especially in datatype.

You added userID at the end of the table. Try
insert into temp values (9, 'sure.', 7);

After adding column,it is added at the end of the table
insert into temp values (9, 'sure.',7);
output:
input str userID
9 sure. 7

Related

How to add a BIT column in SQL

I want to add a BIT column to a table. I have provided the statement to do so, but an error declares the BIT in my statement as a invalid datatype. What would be the correct way to add a bit column?
ALTER TABLE Persons
ADD is_person BIT NULL
[You should specify database you use; this is Oracle example, see if it helps].
There's no such a datatype in Oracle, so you'd use NUMBER and constrain it:
SQL> create table persons
2 (id number,
3 bit number(1,0) check (bit in (0, 1)) --> this
4 );
Table created.
A few examples:
SQL> insert into persons (id, bit) values (1, 2);
insert into persons (id, bit) values (1, 2)
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.SYS_C008434) violated
SQL> insert into persons (id, bit) values (1, 1);
1 row created.
SQL> insert into persons (id, bit) values (1, 0);
1 row created.
SQL> insert into persons (id, bit) values (1, 10);
insert into persons (id, bit) values (1, 10)
*
ERROR at line 1:
ORA-01438: value larger than specified precision allowed for this column
SQL>
Or, if you'd want to add it (as table already exists), then
alter table persons add bit number(1, 0) check (bit in (0, 1));

Inserting into a table with datetime column

I'm trying to create and use a table with a timestamp field. I tried creating it like this.
CREATE TABLE testdb(timestamp DATETIME, value INT NOT NULL)
I tried inserting into the table with these commands, but they both fail.
INSERT INTO testdb(TIMESTAMP_NOW, 3)
INSERT INTO testdb(GETDATE(), 3)
How do I create a table with a field for a timestamp, and how do I insert into that table?
The correct syntax would have a column list and values:
INSERT INTO testdb (timestamp, value)
VALUES (GETDATE(), 3);

SQL - Inserting into postgresql table produces error on semi-colon

I'm trying to insert some test data into a table to check the functionality of a web servlet, however, using pgAdmin4 to do the insert, I am running into an issue I'm not sure how to rectify. What I want to see is the last value (an image byte stream) is null for this test info. Here is my insert statement:
INSERT INTO schema.tablename("Test Title", "Test Content", "OldWhovian", "2016-07-29 09:13:00", "1469808871694", "null");
I get back:
ERROR: syntax error at or near ";"
LINE 1: ...ldWhovian", "2016-07-29 09:13:00", "1469808871694", "null");
^
********** Error **********
ERROR: syntax error at or near ";"
SQL state: 42601
Character: 122
I've tried removing the semi-colon just for kicks, and it instead errors on the close parenthesis. Is it an issue related to the null? I tried doing this without putting quotations around the null and I get back the same error but on the null instead of the semi-colon. Any help is appreciated, I am new to DBA/DBD related activities.
Related: Using PostgreSql 9.6
The insert statement usually has first part where you specify into which columns you want to insert and second part where you specify what values you want to insert.
INSERT INTO table_name (column1, column2) VALUES (value1, value2);
You do not need to specify into which columns part only if you supply all values in the second part. If you have a table with seven columns you can omit the first part if in the second part you supply seven values.
INSERT INTO table_name VALUES (value1, value2, value3, ...);
Example:
drop table if exists my_table;
create table my_table (
id int not null,
username varchar(10) not null,
nockname varchar(10),
created timestamptz
);
INSERT INTO my_table (id, username) VALUES (1, 'user01');
You insert into columns id and username. The column created has default value specified so when you do not supply value in insert the default is used instead. Nickname and identification_number can accept null values. When no value is supplied NULL is used.
INSERT INTO my_table VALUES (2, 'user02', NULL, NULL, current_timestamp);
That is the same as the previous but here is omitted the fist part so you must supply values for all columns. If you did not you would get an error.
If you want insert multiple values you can use several statements.
INSERT INTO my_table (id, username, identification_number) VALUES (3, 'user03', 'BD5678');
INSERT INTO my_table (id, username, created) VALUES (4, 'user04', '2016-07-30 09:26:57');
Or you can use the postgres simplification for such inserts.
INSERT INTO my_table (id, username, nickname, identification_number) VALUES
(5, 'user05', 'fifth', 'SX59445'),
(6, 'user06', NULL, NULL),
(7, 'user07', NULL, 'AG1123');
At the beginning I have written that you can omit the first part (where you specify columns) only if you supply values for all columns in the second part. It is not completely true. In special cases when you have table that has nullable columns (columns that can contain NULL value) or you have specified DEFAUL values you can also omit the first part.
create sequence my_seq start 101;
create table my_table2 (
id int not null default nextval('my_seq'),
username varchar(10) not null default 'default',
nickname varchar(10),
identification_number varchar(10),
created timestamptz default current_timestamp
);
INSERT INTO my_table2 DEFAULT VALUES;
INSERT INTO my_table2 DEFAULT VALUES;
INSERT INTO my_table2 DEFAULT VALUES;
Result:
101 default NULL NULL 2016-07-30 10:28:27.797+02
102 default NULL NULL 2016-07-30 10:28:27.797+02
103 default NULL NULL 2016-07-30 10:28:27.797+02
When you do not specify values defaults are used or null. In the example above the id column has default value from sequence, username has default string "default", nickname and identification_number are null if not specified and created has default value current timestamp.
More information:
PostgreSQL INSERT

Simulating UPSERT in presence of UNIQUE constraints

Simulating UPSERT was already discusssed before. In my case though, I have PRIMARY KEY and additional UNIQUE constraint, and I want upsert semantic with respect to primary key - replacing existing row if it exists, while checking the unique constraint.
Here's an attempt using insert-or-replace:
drop table if exists test;
create table test (id INTEGER, name TEXT, s INTEGER,
PRIMARY KEY (id, s),
UNIQUE (name, s));
insert or replace into test values (1, "a", 0);
insert or replace into test values (1, "a", 0);
insert or replace into test values (2, "b", 0);
insert or replace into test values (2, "a", 0);
The last statement is replaces both rows. This is documented behavior of 'insert or replace', but not what I want.
Here is an attempt with "on conflict replace":
drop table if exists test;
create table test (id INTEGER, name TEXT, s INTEGER,
PRIMARY KEY (id, s) on conflict replace,
UNIQUE (name, s));
insert into test values (1, "a", 0);
insert into test values (1, "a", 0);
I get "UNIQUE constraint failed" right away. The problem disappears if don't share column between both primary key and unique constraint:
drop table if exists test;
create table test (id INTEGER, name TEXT,
PRIMARY KEY (id) on conflict replace,
UNIQUE (name));
insert into test values (1, "a");
insert into test values (1, "a");
insert into test values (2, "b");
insert into test values (2, "a");
Here, I get constraint violation on the very last statement, which is precisely right. Sadly, I do need to share a column between constraints.
Is this something I don't understand about SQL, or SQLite issue, and how do I get the desired effect, except for first trying insert and then doing update on failure?
Can you try to apply the ON CONFLICT REPLACE clause to the UNIQUE constraint also?
create table test (id INTEGER, name TEXT,
PRIMARY KEY (id) on conflict replace,
UNIQUE (name) on conflict replace);
SQLite is an embedded database without client/server communication overhead, so it is not necessary to try to do this in a single statement.
To simulate UPSERT, just execute the UPDATE/INSERT statements separately:
c.execute("UPDATE test SET s = ? WHERE id = ? AND name = ?", [0, 1, "a"])
if c.rowcount == 0:
c.execute("INSERT INTO test(s, id, name) VALUES (?, ?, ?)", [0, 1, "a"])
Since SQLite 3.24.0, you can just use UPSERT.

Conditional composite key in MySQL?

So I have this table with a composite key, basically 'userID'-'data' must be unique (see my other question SQL table - semi-unique row?)
However, I was wondering if it was possible to make this only come into effect when userID is not zero? By that I mean, 'userID'-'data' must be unique for non-zero userIDs?
Or am I barking up the wrong tree?
Thanks
Mala
SQL constraints apply to every row in the table. You can't make them conditional based on certain data values.
However, if you could use NULL instead of zero, you can get around the unique constraint. A unique constraint allows multiple entries that have NULL. The reason is that uniqueness means no two equal values can exist. Equality means value1 = value2 must be true. But in SQL, NULL = NULL is unknown, not true.
CREATE TABLE MyTable (id SERIAL PRIMARY KEY, userid INT, data VARCHAR(64));
INSERT INTO MyTable (userid, data) VALUES ( 1, 'foo');
INSERT INTO MyTable (userid, data) VALUES ( 1, 'bar');
INSERT INTO MyTable (userid, data) VALUES (NULL, 'baz');
So far so good, now you might think the following statements would violate the unique constraint, but they don't:
INSERT INTO MyTable (userid, data) VALUES ( 1, 'baz');
INSERT INTO MyTable (userid, data) VALUES (NULL, 'foo');
INSERT INTO MyTable (userid, data) VALUES (NULL, 'baz');
INSERT INTO MyTable (userid, data) VALUES (NULL, 'baz');