Create a table for following condition - sql

condition for the problem to be solved:
The code i tried to do is
create table article (
ArCode CHAR(5),
ArName VARCHAR(30) NOT NULL ,
Rate Number(8,2) ,
Quantity NUMBER(4) CHECK (Quantity>0) DEFAULT 0 ,
Class CHAR(1)
);
I couldn't solve the first condition and so i am getting right parenthesis missing for final condition

I would translate your requirement as follows:
CREATE TABLE article (
ArCode CHAR(5) PRIMARY KEY CHECK(ArCode like 'A%'),
ArName VARCHAR(30) NOT NULL,
Rate NUMERIC(8,2),
Quantity NUMERIC(4) DEFAULT 0 CHECK (Quantity >= 0),
Class CHAR(1) CHECK(Class in ('A', 'B', 'C'))
);
Changes to your original code:
you want NUMERIC rather than NUMBER
ArCode must be declared as PRIMARY KEY, and needs a check constraint to enfore the "Must begin with A" requirement
the check constraint on Quantity should allow 0 value (that's the default!)
Class needs a check constraint on the list of allowed values

Related

Make CONSTRAINT with string and integer in SQL

I am a beginner. I created a query on PostgreSQL. I want to make CONSTRAINT with string and integer. It was successfully running but when I insert the data, it gave me an error
CREATE TABLE customer
(
id_customer char(5) PRIMARY KEY NOT NULL,
CONSTRAINT cek_id_customer CHECK ((left(id_customer,2) in ('CU'))
and substring(id_customer,3) LIKE '%[0-9]%'),
nama_customer varchar(30) NOT NULL,
gender_customer varchar(15) NOT NULL,
CONSTRAINT cek_gender_customer CHECK(gender_customer = 'Male' OR gender_customer = 'Female')
);
INSERT INTO customer
VALUES ('CU001', 'Sayaa', 'Male')
The message
ERROR: new row for relation "customer" violates check constraint "cek_id_customer"
DETAIL: Failing row contains (CU001, Sayaa, Male).
SQL state: 23514
To enforce the matching pattern you want you can use a regular expression matching rule in the constraint, like id_customer ~ '^CU[0-9]*$'.
For example:
CREATE TABLE customer (
id_customer char(5) PRIMARY KEY NOT NULL,
CONSTRAINT cek_id_customer CHECK (id_customer ~ '^CU[0-9]*$'),
nama_customer varchar(30) NOT NULL,
gender_customer varchar(15) NOT NULL,
CONSTRAINT cek_gender_customer CHECK(
gender_customer = 'Male' OR
gender_customer = 'Female'
)
);
INSERT INTO customer (id_customer, nama_customer, gender_customer)
VALUES ('CU001', 'Sayaa', 'Male'); -- succeeds
INSERT INTO customer (id_customer, nama_customer, gender_customer)
VALUES ('CU1X', 'Sayaa', 'Male'); -- fails!
See running example at DB Fiddle.

ORA-00907: "missing right parenthesis"

First of all, I apologize for asking the same question again but the information on the old topics did not work in my oraclesql code and secondly there may be some syntax errors, I learned mysql in school last semester, but now we are learning oraclesql with old mysql information in the lesson, so i am a bit confused.
So my question is i want to create 3 related table (movie-casts-actor) but i am getting missing right parenthesis. trying to connect casts table to movie table with foreign key and actor table to casts table. what am i doing wrong? how spagetti is it?
CREATE TABLE Movie (
movie_id NUMBER(7) NOT NULL,
movie_name varchar2(50) NOT NULL ,
movie_director varchar2(50) NOT NULL ,
movie_year INT(4) NOT NULL ,
movie_duration INT(3) ,
movie_language varchar2(15) ,
movie_rating number(4,2) ,
PRIMARY KEY(movie_id),
CONSTRAINT is_unique UNIQUE(movie_id),
CONSTRAINT movie_id_checker CHECK(movie_id>0 and movie_id<=9999999)
);
CREATE TABLE Casts (
movie_id_fk INT(7) FOREIGN KEY REFERENCES Movie(movie_id) ,
cast_id INT(7) NOT NULL,
actor_fullname varchar2(50) NOT NULL ,
actor_role varchar2(50) ,
PRIMARY KEY(cast_id),
CONSTRAINT is_unique UNIQUE(cast_id),
CONSTRAINT cast_id_checker CHECK(cast_id>0 and cast_id<=9999999)
);
CREATE TABLE Actor (
cast_id_fk INT(7) FOREIGN KEY REFERENCES Casts(cast_id) ,
actor_id INT(7) NOT NULL,
actor_name CHAR(30) ,
actor_surname CHAR(25) ,
actor_gender CHAR(5) ,
actor_age CHAR(3) CONSTRAINT real_age_check CHECK(actor_age>0 AND actor_age<=150),
PRIMARY KEY(actor_id),
CONSTRAINT is_unique UNIQUE(actor_id),
CONSTRAINT actor_id_checker CHECK(actor_id>0 and actor_id<=9999999)
)
The errors are:
INT or NUMBER(4,0) and not INT(4)
You cannot have a unique key and a primary key on the same column.
An inline foreign key just need the REFERENCES keyword and does not need FOREIGN KEY.
Other issues:
You probably don't want actor name/surname as fixed-length CHAR strings and want to us variable-length VARCHAR2.
You probably want gender to be a code from a fixed list (which can be as long or as short as you find appropriate to describe the actors) rather than as a string.
You probably don't want to have an AGE column as that will be out of date as soon as the first birthday of an actor occurs; instead have a DATE_OF_BIRTH column that is a DATE data type and then you can calculate the age as and when necessary.
Using the table name as a prefix for every column is a waste of key strokes; you would be better to just name the columns for what they are without the prefix. Similar with fk as a suffix.
If you are using a NUMBER(7,0) for id values then you don't need to check that it is less than or equal to 9999999 as it is impossible to be a greater value; however, you can have zero or negative values so the check constraint for the lower bound may still be valid.
If you are using Oracle 12c or later then you should probably be using an IDENTITY column for the id values unless you are taking the id values from a 3rd party.
CREATE TABLE Movie (
id NUMBER(7,0) NOT NULL,
name varchar2(50) NOT NULL ,
director varchar2(50) NOT NULL ,
year NUMBER(4,0) NOT NULL ,
duration NUMBER(3,0),
language varchar2(15) ,
rating number(4,2) ,
PRIMARY KEY(id),
CONSTRAINT movie_id_checker CHECK(id>0)
);
CREATE TABLE Casts (
movie_id INT REFERENCES Movie(id) ,
id NUMBER(7,0) NOT NULL,
fullname varchar2(50) NOT NULL ,
role varchar2(50) ,
PRIMARY KEY(id),
CONSTRAINT cast_id_checker CHECK(id>0)
);
CREATE TABLE Actor (
cast_id NUMBER(7,0) REFERENCES Casts(id) ,
id NUMBER(7,0) NOT NULL,
name VARCHAR2(30) ,
surname VARCHAR2(25) ,
gender CHAR(1)
CHECK ( gender IN ( 'M', 'F', 'X', 'Y', 'Z' ) ),
date_of_birth DATE
CONSTRAINT real_age_check CHECK(date_of_birth >= DATE '1870-01-01' ),
PRIMARY KEY(id),
CONSTRAINT actor_id_checker CHECK(id>0)
);
db<>fiddle here

Its tell missing right parenthessis

CREATE TABLE CHARGES
(
ChrgCode CHAR(7) PRIMARY KEY,
ChrgDescription NVARCHAR(80) NOTNULL,
Duration NUMBER(2) NOTNULL (DURATION <= 60),
HourlyRate NUMBER(3) (HourlyRate <= 399)
)
This one should work,
CREATE TABLE CHARGES (
ChrgCode CHAR(7) PRIMARY KEY,
ChrgDescription NVARCHAR(80) NOT NULL,
Duration NUMBER(2) NOT NULL check (Duration <=60),
HourlyRate NUMBER(3) check(HourlyRate <=399)
)
The reason that it has syntax error in OP's case is that the missing check keyword. (I assume the missing blank between NOT and NULL are copy / paste errors).
As pointed out in the comment, yes, varchar2 and nvarchar2 should be preferred these days.

beginner sql missing keyword and invalid identifier

CREATE table Book
(
book_title varchar (100) not null ,
book_genre char(60) not null,
Date_of_publish date not null,
user_code char(7) not null ,
book_id char (7) primary key not null ,
constraint writer__id_fk foreign key (writer_id),
constraint publisher__id_fk foreign key (publisher_id)
);
I'm getting
[ORA-00905: missing keyword]
in publisher table
CREATE table publisher
(
publisher_id char (7) primary key not null,
publisher_name char(20) not null,
publisher_number char(10) not null,
publisher_email varchar2(60) not null,
publisher_address varchar2(60) not null,
);
I'm getting
[ORA-00904: : invalid identifier]
The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders" table is created:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
Refer this link for more details
https://www.w3schools.com/sql/sql_foreignkey.asp
Hope this helps.
Welcome to the wonderful world of SQL! :-)
General remark:
Please tell us what kind of DBMS you're using. MySQL? SQL Server? Oracle? SQlite? Different systems use different kinds of syntaxes.
First statement:
The problem seems to be in the FOREIGN KEY-portion.
Usually, you'll state something like:
CONSTRAINT [constraint_name] FOREIGN KEY([column_in_this_table]) REFERENCES OTHER_TABLE([column_in_other_table])
edit (added):
The [column_in_this_table] has to exist in your DDL (CREATE TABLE-statement), like so:
CREATE TABLE Book ( book_title ... etc., publisher_id INT, CONSTRAINT FK_publ_id FOREIGN KEY(publisher_id) REFERENCES publisher(publisher_id));
Here, you'll have a 'original' column called 'publisher_id', in the 'publisher'-table. You refer to it from within the 'Book'-table, by first having a 'publisher_id' column in the 'Book'-table (which should have the same DDL as the original column by the way). Next, you'll add a FOREIGN KEY to the 'Book'-table, that is imposed on the Book(publisher_id) column. Note, that you could also name the column in your 'Book'-table differently -- like, say, 'Spongebob' or 'Patrick'. But for future use, you'd like naming conventions that tell what you might expect to find in a column. So you'd name columns for what they contain.
Second statement:
The problem is with the last portion of your statement, where there's a comma after the NOT NULL portion for column publisher_address.
(Part of) your statement:
publisher_address varchar2(60) not null, );
Try replacing that with:
publisher_address VARCHAR2(60) NOT NULL);
edit (note to self):
VARCHAR2 turns out to be a valid datatype in Oracle databases (see:
Oracle documentation)
For your first table, the Foreign Keys do not reference any table. For your second table, I would imagine that comma after your last column isn't helping anything.
So this is the answer.
CREATE table Book
(
book_title varchar (100) not null ,
book_genre char(60) not null,
Date_of_publish date not null,
user_code char(7) not null ,
publisher_id char (7) not null,
writer_id char(7) not null,
book_id char (7) primary key not null ,
CONSTRAINT book_writer_id_fk FOREIGN KEY(writer_id) REFERENCES writer(writer_id),
CONSTRAINT book_publisher_id_fk FOREIGN KEY(publisher_id) REFERENCES publisher(publisher_id)
);
CREATE table publisher
(
publisher_id char (7) primary key not null,
publisher_name char(20) not null,
publisher_number char(10) not null,
publisher_email varchar2(60) not null,
publisher_address varchar2(60) not null
);

SQL: Missing Parenthesis

I have tried editing the command and looking at other questions in order to answer this question, but I still get the dreaded
ORA-00907: missing right parenthesis.
Here is my code. Is there any key word that I may need to drop here? Thanks
CREATE TABLE Loan
(
LoanID INT IDENTITY ( 1, 1 ) UNIQUE,
BranchID INT NOT NULL REFERENCES Branch(BranchID) ON DELETE CASCADE,
LoanNumber CHAR(20) NOT NULL UNIQUE,
LoanType VARCHAR(30) NOT NULL,
Amount MONEY NOT NULL,
ModifiedDate DATETIME DEFAULT (getdate()),
PRIMARY KEY ( LoanID )
);
The following ddl is syntactically correct. Of course, you have to check whether that statement really produces what you want ( in particular the IDENTITY keyword in your original statement is not accounted for ):
CREATE TABLE Loan
(
LoanID INTEGER NOT NULL PRIMARY KEY
, BranchID INTEGER NOT NULL CONSTRAINT tl_fk_branchid REFERENCES Branch(BranchID) ON DELETE CASCADE
, LoanNumber CHAR(20) NOT NULL CONSTRAINT tl_u_loannumber UNIQUE
-- right padded to length of 20 with blanks
, LoanType VARCHAR2(30) NOT NULL
, Amount Number(*,4) NOT NULL
-- cf. http://stackoverflow.com/a/29014422, changed per #BobJarvis' comment
, ModifiedDate DATE DEFAULT SYSDATE
);
The syntax deviations are as follows:
IDENTITYkeyword
inline constraint specification
datatype to represent date and time
datatype for string content
stand-in for money datatype
current datetime