Oracle SQL Query - Age - sql

So I have the following table in my Oracle Database:
create table FilmStar (
filmStarID char(25) not null,
filmStarName char(50) not null,
birthplace char(50) not null,
yearBorn char(25) not null,
yearDied char(25),
primary key (filmStarID)
);
insert into FilmStar values ('0001','Tim Robbins','California, United States','1958',null);
insert into FilmStar values ('0005','Marlon Brando','Nebraska, United States','1924','2004');
I need to complete the following query: List the unique numbers, names, and ages of all film stars who are deceased.
I believe that I need to
select * from FilmStar where yearDied is not null
but how to find out the age?

I prefer to be explicit about type conversions:
select . . .,
(cast(yearDied as int) - cast(yearBorn as int) ) as approximate_age
from FilmStart
where yearDied is not null;
Relying on implicit conversions can result in very hard to find errors. Storing numbers as strings just exacerbates this problem.
Note: in Oracle, one is inclined to use to_number() rather than cast() for this purpose.

Related

Constraint not working as desired for my INSERT?

I am creating a Table named "Cliente" with some constraints on it as it follows:
CREATE TABLE public."Cliente" (
"K_CODCLIENTE" numeric(5) NOT NULL,
"N_NOMBRE1" varchar(15) NOT NULL,
"N_NOMBRE2" varchar(15) NOT NULL,
"N_APELLIDO1" varchar(15) NOT NULL,
"N_APELLIDO2" varchar(15),
"N_DIRECCION" varchar(50) NOT NULL,
"Q_TELEFONO" numeric(10) NOT NULL,
"K_CODREF" numeric(5),
"I_TIPOID" varchar(2) NOT NULL,
"Q_IDENTIFICACION" varchar(10) NOT NULL,
CONSTRAINT "PK_Cliente" PRIMARY KEY ("K_CODCLIENTE"),
CONSTRAINT "UQ_ID_TIPOID_CLIENTE" UNIQUE ("I_TIPOID","Q_IDENTIFICACION"),
CONSTRAINT "CK_CODCLIENTE" CHECK ("K_CODCLIENTE" >= 100),
CONSTRAINT "CK_Q_IDENTIFICACION" CHECK ("Q_IDENTIFICACION" IN ('CC', 'PA', 'CE', 'NI', 'OT'))
);
When I try to insert some values on it:
INSERT INTO "Cliente"
VALUES ('101','Juan','Felipe','Ortiz','Rojas','AK 15 no. 28-05','3101125507',null,'CC','51111111');
I get the following error (in PostgreSQL 14, on Fedora):
[23514] ERROR: new row for relation "Cliente" violates check constraint "CK_Q_IDENTIFICACION"
Detail: Failing row contains (101, Juan, Felipe, Ortiz, Rojas, AK 15 no. 28-05, 3101125507, null, CC, 51111111).
I am trying to restrict the "Q_IDENTIFICACION" column so it can only be filled with 'CC', 'PA', 'CE, 'NI' or 'OT'.
Maybe I'm doing something wrong when declaring the constraint "CK_Q_IDENTIFICACION"?
Seems like you messed up the mapping of values and are trying to insert '51111111' to "Q_IDENTIFICACION".
Consider this more revealing variant with a formatted list of target columns:
INSERT INTO "Cliente"
("K_CODCLIENTE", "N_NOMBRE1", "N_NOMBRE2", "N_APELLIDO1", "N_APELLIDO2", "N_DIRECCION" , "Q_TELEFONO", "K_CODREF", "I_TIPOID", "Q_IDENTIFICACION")
VALUES ('101' , 'Juan' ,'Felipe' , 'Ortiz' , 'Rojas' , 'AK 15 no. 28-05', '3101125507', NULL , 'CC' , '51111111'); -- !
Maybe you want to switch the last two column names in the table definition - and (not) adapt the VALUES list in the INSERT accordingly? (varchar(2) vs. varchar(10) seems switched as well.)
For persisted code, it's generally advisable to spell out target columns in an INSERT command in any case.
Asides:
Reconsider all these pesky double-quoted upper case identifiers. See:
Are PostgreSQL column names case-sensitive?
Consider plain type text instead of varchar(n) with strikingly tight character limits. See:
Any downsides of using data type "text" for storing strings?

ORA-01858 FOR BEGINNER

CREATE TABLE Pizza
(
pizza_id DECIMAL(12) NOT NULL PRIMARY KEY,
name VARCHAR(32) NOT NULL,
date_available DATE NOT NULL,
price DECIMAL(4,2) NOT NULL
);
CREATE TABLE Topping
(
topping_id DECIMAL(12) NOT NULL,
topping_name VARCHAR(64) NOT NULL,
pizza_id DECIMAL(12)
);
ALTER TABLE Topping
ADD CONSTRAINT topping_pk PRIMARY KEY(topping_id);
ALTER TABLE Topping
ADD CONSTRAINT Topping_pizza_fk
FOREIGN KEY(pizza_id) REFERENCES Pizza(pizza_id);
INSERT INTO pizza (pizza_id, name, date_available, price)
VALUES (1, 'Plain', CAST('27-Feb-2021' AS DATE), 6);
Error:
ORA-01858: a non-numeric character was found where a numeric was expected
I cannot figure out which part is wrong, I'm just a beginner for SQL, it seems related with date, can someone help me?
This works for me: SQL Fiddle. Don't use CAST to convert strings to dates. That's the only thing that looks off about your example. It may be using a different default date format than your string. Instead use TO_DATE( '27-Feb-2021', 'DD-Mon-YYYY') which converts a string to a date, or DATE '2021-02-27', which is a date literal and only takes the yyyy-mm-dd format.
Additionally, I'd suggest using NUMBER instead of DECIMAL just because it's more standard in the Oracle world. And always use VARCHAR2 instead of VARCHAR, which is officially discouraged.

Using like for numeric in a constraint

I am creating a table which is like this:
CREATE TABLE Peeps
(
Name VARCHAR(255) NOT NULL,
PhoneNum BIGINT NOT NULL,
CONSTRAINT PhoneNum_Check CHECK (PhoneNum LIKE '08%')
)
Every phone number has to start with 08. However when I tried insert there's an error because LIKE can't be used for numeric (or that's what my friend said). The alternative would be using VARCHAR for PhoneNum, but this is an assignment and we have to use numeric for the phone number.
If a phone number can start with a 0 then you need to use a string:
CREATE TABLE Peeps (
Name VARCHAR(255) NOT NULL,
PhoneNum VARCHAR(255) NOT NULL,
CONSTRAINT PhoneNum_Check CHECK (PhoneNum LIKE '08%')
);
Although you can use LIKE on a number, it is highly not recommended. What happens is that the number is converted to a string. However, that string will never start with a 0 -- well, at least never when the value is greater than 1.

Invalid identifier error but i can't see why

Started learning SQL and am having a go at creating a script. The code looks perfectly fine to me but I keep getting the invalid identifier error. I've checked the code over and over again but everything seems ok. I'm going mad here. I am using oracle by the way.
create table Products ( ID int not null, Item varchar(30) not null, Size
varchar(1) not null);
insert into Products values ( 321, 'T-shirt', 'M');
insert into Products values ( 211, 'Jeans', 'L');
Size is a reserved word in Oracle, try changing the column name to an unreserved word.
See here for the full list of reserved words
size is a reserved word in Oracle's SQL (not sure if it is according to the ANSI standard, but some databases, like MySQL, definitely allow it).
You could escape it by using double quotes ("):
CREATE TABLE Products (
ID INT NOT NULL,
Item VARCHAR(30) NOT NULL,
"Size" VARCHAR(1) NOT NULL
);
But it would be much easier to just choose a name that isn't a reserved word:
CREATE TABLE Products (
ID INT NOT NULL,
Item VARCHAR(30) NOT NULL,
ProductSize VARCHAR(1) NOT NULL
);

oracle error: not enough values

i have a table donor_master:
create table donor_master
(
donor_id number(10) primary key not null,
dob date not null,
age number(3) not null,
gender char(1) not null,
blood_group char(3),
contact_no number(10),
address varchar(50) not null,
city varchar(10) not null,
pin number(10) not null,
state varchar(10) not null,
branch_registration_id number(5) references branch_master(branch_id)
);
when i try to insert into the table in a procedure insert_donor_master, i get "not enough values" error on compilation.
this is the procedure:
create or replace procedure insert_donor_master(
vdob donor_master.dob%type,
vage donor_master.age%type,
vgender donor_master.gender%type,
vblood_group donor_master.blood_group%type,
vcontact_no donor_master.contact_no%type,
vaddress donor_master.address%type,
vcity donor_master.city%type,
vpin donor_master.pin%type,
vstate donor_master.state%type,
vbranch_registration_id donor_master.branch_registration_id%type
)
is
begin
insert into donor_master values (sq_donor_master.nextval, vdob, vage, vgender, vblood_group, vcontact_no, vaddress, vcity, vpin, vstate, vbranch_registration_id);
commit;
end;
What is the problem?
Thanks.
Oracle hurls ORA-00947 when we specify an INSERT statement which doesn't have a value for every column in the table.
Now, the CREATE TABLE statement you posted shows a table with eleven columns. And the stored procedure code you posted shows an insert statement with eleven values in the VALUES (...) clause.
So, the explanations are:
you have a configuration management issue, and you're running the wrong version of the stored procedure or the wrong version of the table
you have a configuration management issue, and the actual structure of the table isn't what you think it is (doesn't match your CREATE TABLE script)
you aren't really getting an ORA-00947 error
Note that if you don't want to populate every row you can specify a projection of the relevant columns before the VALUES clause. For instance, if you just wanted to populate the mandatory columns you would code this:
insert into donor_master
(donor_id, dob, age, gender, address, city, pin, state )
values (sq_donor_master.nextval, vdob, vage, vgender, vaddress, vcity, vpin, vstate)
All that matters is that the number of values matches the number of columns.
The complete syntax for INSERT statements is in the documentation. enter link description hereFind out more.