Check constraint when table is created with default value? - sql

I am using oracle 11g. i am creating a table which has few columns. One of the column should have some default value. If no value is passed then DEFAULT must be considered. Can i do as below?
Column with default value:
ATTENDENT CHAR(1 BYTE) DEFAULT 'N'
Constraint:
CONSTRAINT "CC_ATTENDENT_CHECK" CHECK (attendent is not null and attendent in ('Y','N')) ENABLE
Thanks!

When you create / alter a table with a default value, like this:
Alter table table_test modify (foo varchar(3) NULL default 'bar');
... should be enough to set a default value when you insert a null

Yes You can,
eg:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'Sandnes'
)

Related

Why does it keep giving me te same errors?

So I wanted to put a sql file in a database (es_extended.sql) and it keeps giving me errors like: duplicate column name name etc. and
SQL error (1050): Table 'items' already exists
I have tried to change the names of columns and all but it keeps giving the same errors.
here is the code:
ALTER TABLE `users`
ADD COLUMN `money` VARCHAR(50) DEFAULT NULL,
ADD COLUMN `name` VARCHAR(50) NULL DEFAULT '' AFTER `money`,
ADD COLUMN `skin` LONGTEXT NULL AFTER `name`,
ADD COLUMN `job` VARCHAR(50) NULL DEFAULT 'unemployed' AFTER `skin`,
ADD COLUMN `job_grade` INT NULL DEFAULT 0 AFTER `job`,
ADD COLUMN `loadout` LONGTEXT NULL AFTER `job_grade`,
ADD COLUMN `position` VARCHAR(36) NULL AFTER `loadout`
;
CREATE TABLE `items` (
`name` varchar(50) NOT NULL,
`label` varchar(50) NOT NULL,
`limit` int(11) NOT NULL DEFAULT '-1',
`rare` int(11) NOT NULL DEFAULT '0',
`can_remove` int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (`name`)
);
CREATE TABLE `job_grades` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`job_name` varchar(50) DEFAULT NULL,
`grade` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`label` varchar(50) NOT NULL,
`salary` int(11) NOT NULL,
`skin_male` longtext NOT NULL,
`skin_female` longtext NOT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `job_grades` VALUES (1,'unemployed',0,'unemployed','Unemployed',200,'{}','{}');
CREATE TABLE `jobs` (
`name` varchar(50) NOT NULL,
`label` varchar(50) DEFAULT NULL,
PRIMARY KEY (`name`)
;
INSERT INTO `jobs` VALUES ('unemployed','Unemployed');
CREATE TABLE `user_accounts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`identifier` varchar(22) NOT NULL,
`name` varchar(50) NOT NULL,
`money` double NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
);
CREATE TABLE `user_inventory` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`identifier` varchar(22) NOT NULL,
`item` varchar(50) NOT NULL,
`count` int(11) NOT NULL,
PRIMARY KEY (`id`)
);
Sql databases are a way to implement the persistence layer: data that should be kept permanently or at least independently from sessions.
The error you're getting: SQL error (1050): Table 'items' already exists means that you've already created a table with the same name you're using to try and create a new table.
You do not need to recreate the table each time you try to add data to it. The table is persistent as long as you do not DROP (delete) it or the database it belongs to.
If you want to recreate the table (either because you need to change its schema or because you want to start over), you can run the command DROP TABLE items which will delete the table and all data in the table.
After dropping, you can run the CREATE TABLE items... command again.
If you don't want to delete the table, you can just run the INSERT INTO items... command to add data to the existing table.
The SQL Error (xxxx): duplicate column name 'name' error means you are trying to add a column that already exists in the table. If the users table already has a column called name, then you cannot run the command ALTER TABLE users ADD COLUMN 'name'... without an error.
If the column doesn't meet your needs anymore, you can use ALTER TABLE users ALTER COLUMN 'name'... to change the schema for the column.

Primary key not null

I am doing an Sql assignment in which I need to create a few tables. The assignment requires:
Make sure that you define NOT NULL constraints for the PK of each table
I don't get this. When we are defining a key as Primary Key, why should we write NOT NULL separately with it? Doesn't defining a key as PRIMARY KEY itself mean not null and unique?
Please explain!
Edit (copied from below):
CREATE TABLE Faculty(
FacNo char(11) not null,
FacFirstName varchar(30) not null,
FacLastName varchar(30) not null,
FacCity varchar(30) not null,
FacState char(2) not null,
FacZipCode char(10) not null,
FacRank char(4),
FacHireDate date,
FacSalary decimal(10,2),
FacSupervisor char(11),
FacDept char(6),
CONSTRAINT FacultyPK PRIMARY KEY (FacNo));
Is this correct? The FACNO column is not null plus it's also a primary key.
http://www.techonthenet.com/oracle/primary_keys.php
In Oracle, a primary key is a single field or combination of fields
that uniquely defines a record. None of the fields that are part of
the primary key can contain a null value. A table can have only one
primary key.
when you set PK for a table the column will be set to NOT NULL even if you specify it as nullable
-- Create table
create table t_test_pk(
col1 varchar2(5) null
);
SQL> desc t_test_pk
Name Type Nullable Default Comments
---- ----------- -------- ------- --------
COL1 VARCHAR2(5) Y
so... the column is nullable
then we set PK for the table:
SQL> alter table t_test_pk add constraint pk_1 primary key (COL1);
Table altered
and try to insert null into
SQL> insert into t_test_pk values (null);
insert into t_test_pk values (null)
ORA-01400: cannot insert NULL into ("T_TEST_PK"."COL1")
something was changed! check in SqlPlus - the column is not nullable - and get error... we cannot insert null into the column because it was used in PK
SQL> desc t_test_pk;
Name Type Nullable Default Comments
---- ----------- -------- ------- --------
COL1 VARCHAR2(5)
OK... try to set it to nullable
SQL> alter table t_test_pk modify col1 null;
alter table t_test_pk modify col1 null
ORA-01451: column to be modified to NULL cannot be modified to NULL
I imagine the reason your instructor asks for this is to make sure you write DDL that shows your intent clearly. Trusting auto conversion of null to not null does not help readability of DDL so I'd request all DDL to be written such that the create table statement shows the intended nullability of all columns.
Problem solved, with the following query
CREATE TABLE Faculty(
FacNo char(11) not null,
FacFirstName varchar(30) not null,
FacLastName varchar(30) not null,
FacCity varchar(30) not null,
FacState char(2) not null,
FacZipCode char(10) not null,
FacRank char(4),
FacHireDate date,
FacSalary decimal(10,2),
FacSupervisor char(11),
FacDept char(6),
CONSTRAINT FacultyPK PRIMARY KEY (FacNo) );

How to define table constraint to check non empty datetime?

While creating a table how to add table level constraint so as to check that a column with datatype datetime is not empty?
You would use something like this with NOT NULL:
CREATE TABLE [dbo].[MyTable](
[ID] [int] NOT NULL,
[MyField] [DATETIME] NOT NULL)
The NOT NULL constraint enforces a column to NOT accept NULL values.
The NOT NULL constraint enforces a field to always contain a value. This means that you cannot insert a new record, or update a record without adding a value to this field.
The following SQL enforces the "P_Id" column and the "LastName" column to not accept NULL values:
CREATE TABLE PersonsNotNull
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
If the date field has a point beyond which you know there will be no valid dates, you can set that as a lower boundary.
Date_Field date check( Date_Field > '2000-01-01' ),
If it is peoples birthdate, you will have to set it back to a more reasonable value. Now, now matter how the date is entered or what is is converted from, it must be within a reasonable range to be considered valid.

create table in Oracle BD but gives error

CREATE TABLE employees (
id INT NOT NULL auto_increment PRIMARY KEY (ID),
first_name VARCHAR(20) DEFAULT NULL,
last_name VARCHAR(20) DEFAULT NULL,
salary INT DEFAULT NULL);
I think this is correct query to create table in Oracle database.. but it gives the following error:
ORA-00907: missing right parenthesis
How to correct the statement?
You can validate your SQL using formatting tools such as http://www.dpriver.com/pp/sqlformat.htm
auto_increment seems like a proprietary MySQL extension, so it's not valid for Oracle.
also, "id int not null auto_increment primary key (id)" does not need the last "(id)"
Using Oracle, you shoud try something like this
CREATE SEQUENCE seq;
CREATE TABLE employees
(
id INTEGER NOT NULL PRIMARY KEY,
first_name VARCHAR2(20) DEFAULT NULL,
last_name VARCHAR2(20) DEFAULT NULL,
salary INTEGER DEFAULT NULL
);
INSERT INTO employees
VALUES (seq.NEXTVAL,
'name',
'last name',
1);
Sometimes, SQL is fancy, because even having a standard (ANSI), most DBMS vendors add their proprietary extensions to the SQL creating their own languages, so it's rare the situation where you can port one SQL from one DB into another without any changes.
Also, it's a pretty useless error message. It could at least say which position. (also, there's no missing parenthesis, but an unexpected token)
EDITED : New feature 12c
CREATE TABLE employees(
id NUMBER GENERATED ALWAYS AS IDENTITY,
first_name VARCHAR2(30)
etc.
);
Why would you do default null?
The VARCHAR datatype is synonymous with the VARCHAR2 datatype. To avoid possible changes in behavior, always use the VARCHAR2 datatype to store variable-length character strings.
Replace
id INT NOT NULL auto_increment PRIMARY KEY (ID),
with
id INT NOT NULL auto_increment PRIMARY KEY,
this is more efficient
CREATE TABLE EMPLOYEES_T(
ID NUMBER,
FIRST_NAME VARCHAR2(20) DEFAULT NULL,
LAST_NAME VARCHAR2(20) DEFAULT NULL,
SALARY INTEGER DEFAULT NULL,
CONSTRAINT PK_EMPLOYEES_T PRIMARY KEY(ID)
);

When I create a table in SQL, how do I set an attribute not null?

I wanna create a table in SQL, and if the I wanna set the attributes to NULL, how do I do it?
For example, I wanna create a table named Courses and its attributes "CourseNo" and "Title" must not be null. I created one below:
CREATE TABLE Courses(
CourseNo INTEGER CHECK(100<=CourseNo<=999) PRIMARY KEY,
Title VARCHAR(100),
)
ALTER TABLE Courses
ALTER COLUMN CourseNo INTEGER NOT NULL
ALTER COLUMN Title VARCHAR(100) NOT NULL
Is this correct?
whatever you wrote that one correct but good practice is to write not null at a time of defining table. do like this:
CREATE TABLE Courses(
CourseNo INTEGER CHECK(100<=CourseNo<=999) PRIMARY KEY,
Title VARCHAR(100) NOT NULL,
)
primary key is by default NOT NULL always, hence you no need to declare it as NOT NULL
NOT NULL in alter is used when u want to make change in column definations of table later
Change that Title VARCHAR(100) to Title VARCHAR(100) NOT NULL.