Skip to content
Advertisement

Can I combine parts of multiple columns in Oracle SQL

I’m a student in college and I’m working on a project with Oracle DB. I was wondering if it was possible to make a column value appear as concatenated parts of other columns when I Insert a line and use that column as PK ?

So on a table like this :

CREATE TABLE Cellphone (
    id          VARCHAR (8) PRIMARY KEY,
    maker       VARCHAR (20)   NOT NULL,
    range       VARCHAR (20)   NOT NULL,
    model       VARCHAR (10)   NOT NULL,
    ram         NUMBER (2)     NOT NULL,
    color       VARCHAR (5)    NOT NULL,
    quantity    NUMBER (3)     DEFAULT 0
);

So when I insert a line I’d like the id to be set automatically to a concatenated value of the first 3 character of the maker, the first 3 of the range, the first 3 of the model, the ram and the color.

For example :

INSERT INTO Cellphone (id, maker, range, model, ram, color, quantity)
VALUES (*The code I am looking for*, "SAMSUNG", "GALAXY", "S10",32,"BLK",56);

The id that would be generated is SAMGALS1032BLK.

Is it possible to do that? If not is there something that could look like that, maybe with a SELECT statement when I want to show the table?

Advertisement

Answer

You can try this:

CREATE TABLE Cellphone (
    id          AS (substr(maker,0,3)||substr(range,0,3)||model||ram||color) PRIMARY KEY,
    maker       VARCHAR (20)   NOT NULL,
    range       VARCHAR (20)   NOT NULL,
    model       VARCHAR (10)   NOT NULL,
    ram         NUMBER (2)     NOT NULL,
    color       VARCHAR (5)    NOT NULL,
    quantity    NUMBER (3)     DEFAULT 0
);

INSERT INTO Cellphone (maker, range, model, ram, color, quantity)
VALUES ('SAMSUNG', 'GALAXY', 'S10',32,'BLK',56);

select * from Cellphone;

https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=954fb222fba8a2b49c3937c47e9f4726

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement