Replace into equivalent for postgresql and then autoincrementing an int - sql

Okay no seriously, if a PostgreSQL guru can help out I'm just getting started.
Basically what I want is a simple table like such:
CREATE TABLE schema.searches
(
search_id serial NOT NULL,
search_query character varying(255),
search_count integer DEFAULT 1,
CONSTRAINT pkey_search_id PRIMARY KEY (search_id)
)
WITH (
OIDS=FALSE
);
I need something like REPLACE INTO for MySQL. I don't know if I have to write my own procedure or something?
Basically:
check if the query already exists
if so, just add 1 to the count
it not, add it to the db
I can do this in my php code but I'd rather all that be done in postgres C engine

You have to add a unique constraint first.
ALTER TABLE schema.searches ADD UNIQUE (search_query);
The insert/replace command looks like this.
INSERT INTO schema.searches(search_query) VALUES ('a search query')
ON CONFLICT (search_query)
DO UPDATE SET search_count = schema.searches.search_count + 1;

Related

How to add Default SEQ.nextval() to PK-Column in SQL datamodeler

I'm dealing with one issue.
Using sql datamodeler I tried to add an autoincrementing primary key column.
In sql it looks like PK_ID NUMBER(10) default seq_pk_id.nextval().
But how can I tell sql datamodoler to do that?
There's an autoincrement option in the relational view but it just add the creation of the sequence to the DDL not the default option on the primary key column.
Anyone any idea?
you can use a trigger for this column:
CREATE OR REPLACE TRIGGER SET_PK_ID
BEFORE INSERT ON Table_Name
FOR EACH ROW
BEGIN
SELECT seq_pk_id.nextval
INTO :new.PK_ID
FROM dual;
END;

Validating json string using CHECK constraint in Postgres (sql)

I have a table with below schema :
CREATE TABLE tbl_name (
id bigserial primary key,
phone_info json
);
Sample json data for phone_info column is given below .
{
"STATUS":{"1010101010":"1","2020202020":"1"},
"1010101010":"OK",
"2020202020":"OK"
}
Now I need to add a check constraint on phone_info column so that all key for "STATUS" ie(1010101010,2020202020) should exist as a (key,value) pair of phone_info column where value would be "OK".
So above sample data would satisfy the check constraint as there are following key value pair exists in phone_info column.
"1010101010":"OK"
"2020202020,":"OK"
I have tried below solution but this has not worked because array_agg function is not supported with check constraints.
ALTER TABLE tbl_name
ADD CONSTRAINT validate_info CHECK ('OK' = ALL(array_agg(phone_info->json_object_keys(phone_info->'STATUS'))) );
Can someone please help me out , Can I write a SQL function and use the function in check constraint?
With something like this I think you'll want an SQL function.
CREATE TABLE tjson AS SELECT '{
"STATUS":{"1010101010":"1","2020202020":"1"},
"1010101010":"OK",
"2020202020":"OK"
}'::json AS col;
perhaps something like:
CREATE OR REPLACE FUNCTION my_json_valid(json) RETURNS boolean AS $$
SELECT bool_and(coalesce($1->>k = 'OK','f'))
FROM json_object_keys($1->'STATUS') k;
$$ LANGUAGE sql IMMUTABLE;
... but remember that while PostgreSQL will let you modify that function, doing so can cause previously valid rows to become invalid in the table. Never modify this function without dropping the constraint then adding it back again.

SQL Date option

I have a little doubt, I want to create a table that had a date that can't be bigger the 2012/12/31, i searched on google but only had exemples on SELECT. I'm gonna put an example:
CREATE TABLE example(
IDExample number (8) primary key,
DateExample date // Here i want to put that condition, is it possible?
);
If you're using SQL Server you can add check contraint on the column in the following way.
ALTER TABLE dbo.example ADD CONSTRAINT CK_DateExample
CHECK (DateExample < '20130101')
If you're using Oracle, the syntax is very similar:
ALTER TABLE dbo.example ADD CONSTRAINT CK_DateExample
CHECK (DateExample < DATE '2013-01-01')

SQL unique index without leading zeros

I have set-up a table using the following SQL script:
CREATE TABLE MY_TABLE (
ID NUMBER NOT NULL,
CODE VARCHAR2(40) NOT NULL,
CONSTRAINT MY_TABLE PRIMARY KEY (ID)
);
CREATE UNIQUE INDEX XUNIQUE_MY_TABLE_CODE ON MY_TABLE (CODE);
The problem is that I need to ensure that CODE does not have a leading zero for its value.
How do I accomplish this in SQL so that a 40-char value without a leading zero is stored?
CODE VARCHAR2 NOT NULL CHECK (VALUE not like '0%')
sorry - slight misread on the original spec
If you can guarantee that all INSERTs and UPDATEs to this table are done through a stored procedure, you could put some code there to check that the data is valid and return an error if not.
P.S. A CHECK CONSTRAINT would be better, except that MySQL doesn't support them.

Link a sequence with to an identity in hsqldb

In PostgreSql, one can define a sequence and use it as the primary key of a table. In HsqlDB, one can still accomplish creating an auto-increment identity column which doesn't link to any user defined sequence. Is it possible to use a user defined sequence as the generator of an auto-increment identity column in HsqlDB?
Sample sql in PostgreSql:
CREATE SEQUENCE seq_company_id START WITH 1;
CREATE TABLE company (
id bigint PRIMARY KEY DEFAULT nextval('seq_company_id'),
name varchar(128) NOT NULL CHECK (name <> '')
);
What's the equivalent in HsqlDB?
Thanks.
In version 2.0, there is no direct feature for this. You can define a BEFORE INSERT trigger on the table to do this:
CREATE TABLE company ( id bigint PRIMARY KEY, name varchar(128) NOT NULL CHECK (name <> '') );
CREATE TRIGGER trigg BEFORE INSERT
ON company REFERENCING NEW ROW AS newrow
FOR EACH ROW
SET newrow.id = NEXT VALUE FOR seq_company_id;
and insert without using any vlue for id
INSERT INTO company VALUES null, 'test'
Update for HSQLDB 2.1 and later: A feature has been added to support this.
CREATE SEQUENCE SEQU
CREATE TABLE company ( id bigint GENERATED BY DEFAULT AS SEQUENCE SEQU PRIMARY KEY, name varchar(128) NOT NULL CHECK (name <> '') );
See the Guide under CREATE TABLE http://hsqldb.org/doc/2.0/guide/databaseobjects-chapt.html#dbc_table_creation
In addition, 2.1 and later has a PostgreSQL compatibility mode in which it accepts the PostgreSQL CREATE TABLE statement that references the sequence in the DEFAULT clause and translates it to HSQLDB syntax.