NULL constraint after attribute in CREATE TABLE? - sql

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

Related

How to insert null or empty value to decimal column in oracle?

If it is a string column, I can insert null or empty value with '', but what about the decimal column, Null or -99999? Thanks so much for any advice.
You can insert null values into the table with a column type integer. Empty_string and null is the same in oracle.
Eg:
create table t(x int)
insert into t values('')
insert into t values(null)
select count(*),count(x)
from t
https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=e7653cf554a9e19a8ae47f1c101218ff
NULL is nothing but the value that is missing or not available.
You can insert null in any null-allowed column in database regardless of its data type. For string '' (empty value) is considered as null. There is no such stuff for number.
Create table test
(id number,
Name varchar2(10),
Address clob,
Zip integer);
Insert into test
Values(NULL, NULL, NULL, NULL)
Cheers!!
You cannot insert empty value ('') which will throw the error following error, instead you can insert NULL values.
converting data type varchar to numeric.
INSERT INTO TBL (DeciClm) VALUES(NULL)

Possible to assign a default value on a NULL against table column in sql

I am wondering if there is a way that when creating a table that you can assign a default value to a column if the value is null.
I understand that you can use the syntax DEFAULT however this is only for when the value is absent. Is there a way similar to this that you can say when NULL it will add the default without using a trigger.
CREATE TABLE DBO.TESTS
(
TEST VARCHAR(100) DEFAULT(ISNULL('test',NULL)),
NUM INT
)
This is a test and the kind of thing i was looking at?
UPDATE:
Example input
INSERT INTO TESTS (TEST,NUM)
VALUES (NULL,1)
Where the "NULL" is i would like that to enter the value "test". But also if i was to do the following
INSERT INTO TESTS (NUM)
VALUES (1)
This would also enter the value of "test" into the column "TEST".
I hope this helps.
Yes, there is a way to do what you want. It is called a trigger. You would have to define a trigger that sets the value when a NULL is inserted into the column.
If you use an INSTEAD OF trigger, then you can still declare the column as NOT NULL. The trigger will take care of assigning a value so the constraint is not violated.
So, you can do this. Why you would want to do it is another question. Perhaps you are not familiar with the DEFAULT keyword that allows default values to be inserted using a VALUES() clause. This is explained in the documentation for INSERT.
You can add a default constraint to your table which will automatically add a set value for the column if the insert does not have a value for it:
CREATE TABLE DBO.TESTS
(
TEST VARCHAR(100),
NUM INT
)
ALTER TABLE [DBO].[TESTS] ADD CONSTRAINT [DF_TESTS_TEST] DEFAULT (N'default_value_goes_here') FOR [TEST]
INSERT INTO [DBO].[TESTS] VALUES (NULL, 1)
INSERT INTO [DBO].[TESTS] (num) VALUES (2)
Results
NULL 1
'default_value_goes_here' 2
If you want to check during an insert you can use COALESCE
DECLARE #insertValue VARCHAR(100)
SET #insertValue = NULL
INSERT INTO DBO.TESTS VALUES (COALESCE (#insertValue, 'defaultValue'), 1);
The bottom line is that the column should be non-nullable with a default value.
It's possible to replace null values with default values in a trigger for insert/update, but that doesn't make any sense - first because it means every update/insert will have to do that extra work, and second, because that would make it impossible to insert null to the column (unless the triggers are disabled) so why allow nulls in the first place? It's a mistake that will only be confusing for anyone attempting to use that table.
Think about it from the user side - when you send null to a nullable column, you expect it to be null, you don't expect it to contain a value.
If you run this insert statement:
INSERT INTO TESTS (TEST,NUM)
VALUES (NULL,1)
You expect the table to contain a row where Test is null and num = 1.
You do not expect the Test column to contain the default value.
When providing a value for a column, including NULL, that value will be used. NULL is still a value, just an unknown value. A DEFAULT value will only be used if no value is passed (which, as I just said, NULL is a value so doesn't count).
If you don't want a NULL in your table, then instead stop people supplying them by setting your column as NOT NULL:
CREATE TABLE dbo.TestTable (ID int, String varchar(100) NOT NULL DEFAULT 'test')
GO
--INSERT is successful, String has a value of 'test'
INSERT INTO dbo.TestTable (ID)
VALUES(1);
GO
--INSERT fails, String cannot have a value of NULL
INSERT INTO dbo.TestTable (ID,
String)
VALUES(2,NULL);
GO
SELECT *
FROM dbo.TestTable;
GO
DROP TABLE dbo.TestTable;
GO

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

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

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.

SQL Column definition: default value and not null redundant?

I've seen many times the following syntax which defines a column in a create/alter DDL statement:
ALTER TABLE tbl ADD COLUMN col VARCHAR(20) NOT NULL DEFAULT "MyDefault"
The question is: since a default value is specified, is it necessary to also specify that the column should not accept NULLs? In other words, doesn't DEFAULT render NOT NULL redundant?
DEFAULT is the value that will be inserted in the absence of an explicit value in an insert / update statement. Lets assume, your DDL did not have the NOT NULL constraint:
ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT 'MyDefault'
Then you could issue these statements
-- 1. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B) VALUES (NULL, NULL);
-- 2. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B, col) VALUES (NULL, NULL, DEFAULT);
-- 3. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B, col) DEFAULT VALUES;
-- 4. This will insert NULL into tbl.col
INSERT INTO tbl (A, B, col) VALUES (NULL, NULL, NULL);
Alternatively, you can also use DEFAULT in UPDATE statements, according to the SQL-1992 standard:
-- 5. This will update 'MyDefault' into tbl.col
UPDATE tbl SET col = DEFAULT;
-- 6. This will update NULL into tbl.col
UPDATE tbl SET col = NULL;
Note, not all databases support all of these SQL standard syntaxes. Adding the NOT NULL constraint will cause an error with statements 4, 6, while 1-3, 5 are still valid statements. So to answer your question: No, they're not redundant.
Even with a default value, you can always override the column data with null.
The NOT NULL restriction won't let you update that row after it was created with null value
My SQL teacher said that if you specify both a DEFAULT value and NOT NULLor NULL, DEFAULT should always be expressed before NOT NULL or NULL.
Like this:
ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT "MyDefault" NOT NULL
ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT "MyDefault" NULL
I would say not.
If the column does accept null values, then there's nothing to stop you inserting a null value into the field. As far as I'm aware, the default value only applies on creation of a new row.
With not null set, then you can't insert a null value into the field as it'll throw an error.
Think of it as a fail safe mechanism to prevent nulls.
In other words, doesn't DEFAULT render NOT NULL redundant ?
No, it is not redundant. To extended accepted answer. For column col which is nullable awe can insert NULL even when DEFAULT is defined:
CREATE TABLE t(id INT PRIMARY KEY, col INT DEFAULT 10);
-- we just inserted NULL into column with DEFAULT
INSERT INTO t(id, col) VALUES(1, NULL);
+-----+------+
| ID | COL |
+-----+------+
| 1 | null |
+-----+------+
Oracle introduced additional syntax for such scenario to overide explicit NULL with default DEFAULT ON NULL:
CREATE TABLE t2(id INT PRIMARY KEY, col INT DEFAULT ON NULL 10);
-- same as
--CREATE TABLE t2(id INT PRIMARY KEY, col INT DEFAULT ON NULL 10 NOT NULL);
INSERT INTO t2(id, col) VALUES(1, NULL);
+-----+-----+
| ID | COL |
+-----+-----+
| 1 | 10 |
+-----+-----+
Here we tried to insert NULL but get default instead.
db<>fiddle demo
ON NULL
If you specify the ON NULL clause, then Oracle Database assigns the DEFAULT column value when a subsequent INSERT statement attempts to assign a value that evaluates to NULL.
When you specify ON NULL, the NOT NULL constraint and NOT DEFERRABLE constraint state are implicitly specified.
In case of Oracle since 12c you have DEFAULT ON NULL which implies a NOT NULL constraint.
ALTER TABLE tbl ADD (col VARCHAR(20) DEFAULT ON NULL 'MyDefault');
ALTER TABLE
ON NULL
If you specify the ON NULL clause, then Oracle Database assigns the
DEFAULT column value when a subsequent INSERT statement attempts to
assign a value that evaluates to NULL.
When you specify ON NULL, the NOT NULL constraint and NOT DEFERRABLE
constraint state are implicitly specified. If you specify an inline
constraint that conflicts with NOT NULL and NOT DEFERRABLE, then an
error is raised.