In Oracle, How to handle NULL values when inserted to a Table - sql

I have one table, which has a filed. When I insert in that table with the Empty value like '' or null, it should get converted to 'DUMMY-VALUE'.
--Have one table;
CREATE TABLE TEST ( FIELD1 VARCHAR2(50) );
--When I insert ''
INSERT INTO TEST(FIELD1) VALUES('');
SELECT * FROM TEST
--Expected Result 'DUMMY-VALUE' but not NULL
I can apply NVL('','DUMMY-VALUE') in INSERT statement but I am allowed to change CREATE statement only.
For Now, I am handing this with TRIGGER but , wondering if there is any alternative in 11g however I know about DEFAULT ON NULL for oracle 12c.

You can do like this:
create table TEST (FIELD1 VARCHAR2(50) default 'DUMMY-VALUE' );
and when you want to insert
you should insert without that field if the values is NULL or empty

Try this:
CREATE TABLE TEST (FIELD1 VARCHAR2(50) DEFAULT 'DUMMY-VALUE');
then use the DEFAULT keyword in the INSERT statement:
INSERT INTO TEST (FIELD1) VALUES (DEFAULT);
SQLFiddle here
Share and enjoy.

Related

Trigger ON Table which fire INSERT into another table which has NOT NULL constraint

CREATE TRIGGER logaction ON temployeelog
AFTER INSERT
AS
BEGIN
INSERT INTO TABLE temployee(ename, experience)
SELECT ename,experience FROM INSERTED
END
The structure of temployee
CREATE TABLE temployee
(
ename VARCHAR(20),
experience INT NOT NULL
)
ALTER TABLE temployeeADD DEFAULT (0) FOR experience
When I don't pass data in the experience column WHILE INSERT I get an error.
Cannot insert the value NULL into column 'experience', table
'temployee'; column does not allow nulls. INSERT fails. The statement
has been terminated.
I wanted to pass NULL Values temployeelog table AND wanted those situation to be handled by 'DEFAULT VALUES kept in temployee'
How can I achieve that?
The table default only comes into play if you don't insert it, so split the insert into one which handles a non-null experience and one which handles a null experience
INSERT INTO TABLE temployee (ename, experience)
SELECT ename, experience
FROM INSERTED
WHERE experience IS NOT NULL;
INSERT INTO TABLE temployee (ename)
SELECT ename
FROM INSERTED
WHERE experience IS NULL;

How to insert null value to NOT NULL column using the DEFAULT Constraint

These is my example table definition:
CREATE TABLE [MyTable]
(
[ColumnName] [bit] NOT NULL
)
ALTER TABLE [MyTable] ADD DEFAULT ((0)) FOR [ColumnName]
I want to be able to pass a Null value to my stored procedure's #ColumnValue, something like:
#ColumnValue = null;
INSERT INTO [MyTable] ([ColumnName])
VALUES (#ColumnValue)
But I'm getting this error:
"Cannot insert the value NULL into column... INSERT fails with"
Why the DEFAULT constraints not working?
Solved:
as #J.D. Pace said: The default value will be inserted only if the value is not specified on the Insert statement.
so as #dotNET suggested, i have specified the default value in the INSERT query statement using the ISNULL:
ISNULL - The SQL Server ISNULL() function lets you return an alternative value when an expression is NULL:
#ColumnValue = null;
INSERT INTO [MyTable] (
[ColumnName]
)
VALUES (
ISNULL(#ColumnValue, 0)
)
A table with only one column of bit type with a default value seems to be a bad design. This stuff can almost certainly be stored in a different and better way. On the other hand, if there are other columns in the table that you didn't include in the post, just skip this particular column in your INSERT query and it will work fine. Lastly, you can specify the default value in your INSERT query too.

Prohibit Inserting Rows With Default Constraint

Is there any way of how to prevent inserting data in specified columns in table and use only the default (constraint) values?
E.g. I have columns:
LogInsert (DF GETDATE())
LogUser (DF ORIGINAL_LOGIN())
both defined with DEFAULT constraint. I do not want to allow users to insert into those columns, but use default values here instead when inserting new row.
This should raise an error.
INSERT INTO T1
( C1
,C2
,LogInsert
,LogUser
)
VALUES ( 'A'
,'B'
,'20160101 10:53'
,'domain\user'
);
User should be able to perform the following script without error.
INSERT INTO T1
( C1, C2 )
VALUES ( 'A', 'B' );
You could always give your users a view to work against instead of a table. You can then either choose to hide the columns completely or (as here) make them computed so that they cannot insert a value into the column, via the view:
create table dbo._T1 (
ID int IDENTITY(1,1) not null,
Inserted datetime2 constraint DF__T1_Inserted DEFAULT (SYSDATETIME()) not null,
ABC varchar(10) not null,
constraint PK__T1 PRIMARY KEY (ID)
)
go
create view dbo.T1
with schemabinding
as
select
ID,
COALESCE(Inserted,SYSDATETIME()) as Inserted,
ABC
from dbo._T1
go
insert into dbo.T1 (ABC) values ('abc')
go
insert into dbo.T1 (ABC,Inserted) values ('def',SYSDATETIME())
Results:
(1 row(s) affected)
Msg 4406, Level 16, State 1, Line 19
Update or insert of view or function 'dbo.T1' failed because it contains a derived or constant field.
All of the users queries continue to just use T1. It just happens to be a view rather than a table.
In the above, the view uses COALESCE(Inserted,SYSDATETIME()). It doesn't really matter what's used here, and it doesn't need to match e.g. the default definition. All that's important is that some computation is performed on the Inserted column so that it becomes a read-only column in the view.
You can create a Check Constraint on the table, for example the below
CREATE TABLE [dbo].[T1]
(
[C1] VARCHAR(50)
,[LogInsert] DATETIME DEFAULT GETDATE()
,[LogUser] VARCHAR(500) DEFAULT ORIGINAL_LOGIN()
)
ALTER TABLE [T1] WITH CHECK ADD CONSTRAINT [CK_T1_LogInsert] CHECK ([LogInsert] = GETDATE())
ALTER TABLE [T1] WITH CHECK ADD CONSTRAINT [CK_T1_LogUser] CHECK ([LogUser] = ORIGINAL_LOGIN())
INSERT INTO [dbo].[T1] ([C1]) VALUES ('A')
INSERT INTO [dbo].[T1] ([C1]) VALUES ('B')
INSERT INTO [dbo].[T1] ([C1]) VALUES ('C')
SELECT * FROM [dbo].[T1]
--Will Fail
INSERT INTO [dbo].[T1] ([C1],[LogInsert]) VALUES ('D','2016-11-11 00:00')
INSERT INTO [dbo].[T1] ([C1],[LogUser]) VALUES ('D','Not Your UserName')
OR
You can force the user to only insert using a stored procedure and not allow that as a parameter, this can be done with a table variable too for bulk inserts.

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

NULL constraint after attribute in CREATE TABLE?

I'm new to SQL and I'm trying to figure out what this NULL is doing. Here a simple example:
CREATE TABLE test (
bla VARCHAR NULL
);
So I tried to figure out wether this is set to be the default value, but it is null as default wether I put it there or not, right?
Also I wondered if it has to stay null (for whatever reason) but when I tried to insert a value it was possible anyway. So does it do anything?
From CREATE TABLE:
NULL
The column is allowed to contain null values. This is the default.
You could write:
INSERT INTO test(bla)
VALUES (NULL);
-- it holds NULL
INSERT INTO test(bla)
VALUES (default);
-- it holds NULL
INSERT INTO test(bla)
VALUES ('a');
-- it holds 'a'
You could also omit column:
CREATE TABLE test2(bla VARCHAR NULL, col2 INT NOT NULL);
INSERT INTO test2(col2) VALUES (1);
-- it contains NULL, 1
If you specify column as:
CREATE TABLE test(bla VARCHAR NOT NULL);
INSERT INTO test(bla) VALUES (NULL);
-- error
EDIT:
You don't have to specify NULL explicitly.
CREATE TABLE test(bla VARCHAR);
is the same as:
CREATE TABLE test (bla VARCHAR NULL);
You are parameterizing the column can be NULL