How to insert non duplicate names in SQL - sql

I want to add a new user in my table users
users
------
ID NAME
1 abc
2 cde
how could I use the syntax 'no exists' in this case if for example someone by mistake insert another user with the name 'abc' I dont want to enter with the same name user again.

You just need to make the column as UNIQUE
ALTER IGNORE TABLE users ADD UNIQUE (NAME);
This will prevent to have duplicates in the column NAME

Related

Making two columns in a table unique

I have a table that looks like this:
ID
email
alt_email
1
abc#gmail.com
123#gmail.com
2
def#gmail.com
ghi#gmail.com
Each user has an email and alternative email.
I want to make it so that when a user is added (or modified), the PSQL table does not allow duplicates, even between the two columns.
For example, this would not be allowed:
ID
email
alt_email
1
abc#gmail.com
def#gmail.com
2
def#gmail.com
ghi#gmail.com
Because def#gmail.com is duplicated. How can I accomplish this?
The easiest alternative - without changing the data model - would be to control it within a trigger function:
Declare the columns independently as UNIQUE, so that there are no duplicated e-mails in the same column:
CREATE TABLE t (
id int,
email text UNIQUE,
alt_email text UNIQUE
);
Create a function to check if the e-mails exists in another column:
CREATE OR REPLACE FUNCTION check_email()
RETURNS TRIGGER AS $$
BEGIN
IF (SELECT EXISTS
(SELECT 1 FROM t WHERE alt_email = NEW.email OR email = NEW.alt_email)) THEN
RAISE EXCEPTION 'E-mail already exists!';
ELSE
RETURN NEW;
END IF;
END; $$ LANGUAGE plpgsql;
And finally attach the trigger function to the table
CREATE TRIGGER tgr_check_email
BEFORE INSERT OR UPDATE ON t
FOR EACH ROW EXECUTE PROCEDURE check_email();
Demo: db<>fiddle
Neither unique index nor constraint will help you there.
You can:
Create a INSERT/UPDATE trigger that will check the emails. A locking mechanism must be implemented to disallow concurrent inserts/updates as checks are performed in different transactions - that may harm your performance.
Move your emails to separate table as this is a one-to-many relationship. On this new table (let's call it email) you can add a unique index or even have an email as a primary key. This is the right and most clean solution to your problem. You can create a view with a name and the columns the same as your current table to move with the change quicker.
Do both of 1 and 2: create the email table and add the trigger maintaining the records of it based on the email and alt_email values. You will have the email duplicates but you will not have to change anything in your application - all the changes go into DB schema.

alter table add column using %TYPE oracle

Can we add a column in a table using the datatype of a column from another table.
NO PLSQL. just a normal SQL query
eg as below
*Table ABC has 3 columns
name varchar2(50)
id number
dob Date
Table XYZ has 2 columns
id number
phone_number number(10)*
Now i want to add another column in Table XYZ With same datatype as NAME of column ABC.
but the below command is not working
alter table XYZ ADD MOTHERS_NAME ABC.NAME%TYPE;
Sorry that facility does not exist.
You could query USER_TAB_COLS to determine the data type of the source column and dynamically build the ALTER TABLE command, but that still does not do anything like keep them in sync. It would just be a syntactical convenience.

Check Duplicated records in a table

I have a table storing user's information, including SSN. Now I need to write a query to prevent, or to check, when there is person who start to insert some new record into the table, if the new records' SSN is the same with someone who currently in the system, then it return false, or reject the insert.
I know how to count same SSN in a table, but this is sort of before insert check, should I do this on the front end level?
Update: So I think through this again, I am asking about, how can I actually allow the insert, and also every time we do the insert, there will be a check, if the new insert have duplicate SSN with one of our current client, then there will be a new column called "DuplicatedSSN"=True. How can I achieve this?
Step 1 (DB): Add a UNIQUE constraint to the table to prevent duplicates.
Step 2 (program): Do a pre-check against the value and run your code from there.
Pseudocode would look like:
SELECT COUNT(*) LINES FROM MAIN_TABLE WHERE SSN = $attempted_entry
if(LINES <= 0){
--insert into MAIN_TABLE
} else {
--insert into POSSIBLE_FRAUD_CHECKS
}
I hope you are encrypting SSN information, but here's how you check if there's a duplicate already.. There's a couple ways.
First you should make the database column for SSN have a 'UNIQUE' value. This will prevent there ever being a duplicate.
With your query you should do the following:
INSERT IGNORE INTO table (column1, column2, etc, ssn_column)
VALUES (column1_value, column2_value, etc_value, ssn_value)
ON DUPLICATE KEY UPDATE ssn_column=ssn_column
Basically this says...
1) INSERT values into table
2) BUT if the ssn already exists...
3) Update the existing ssn to = ssn (aka do nothing)
This will only insert a new column if it doesn't exist already, but SSN column MUST be a UNIQUE column!
You can also do...
SELECT id FROM table WHERE ssn = ssn_value
if this returns a row... you know it exists...
if nothing exists...
INSERT INTO table (columns) VALUES (values)
Alex is correct here. A UNIQUE constraint will prevent duplicates entries in your database. In order to add the constraint, you will need to make sure there aren't any duplicates existing in your table. To add the constraint you could use something like the following
ALTER TABLE table1 ADD UNIQUE (SSN)
If you want to just set a field based on existing information, I think you can use a case statement in your insert.
INSERT INTO table 1 (SSN, DuplicatedSSN) VALUES (999-99-9999, CASE WHEN EXISTS (SELECT ID FROM orders where SSN = '999-99-9999') THEN 1 ELSE 0 END)

Access - Check if a value exists in another table after insert

I have a table with the field "Name" among the others. When I insert a new value in that field, I need a check to see if it exists in another table (same field, "Name"), and if it doesn't, I need that it creates a new row in this table with the value inserted
Example:
First Table Second Table
Name Cost Name Cost
John 1000€ John 1200€
John 200€ James 2000€
James 2000€
If I try to insert, for example, "Mark" in the first table, since it isn't in the second table, it adds a new row in the second, so the result is
Second Table
Name Cost
John 1200€
James 2000€
Mark 0€
The check is on the field "name"
Here is the actual database, but it is in italian. The Form "Commesse" has the button "aggiungi cliente" where I write a new name and then save it with "Salva cliente". I need that the other three tables and relative forms to have updated the "Nome_Cliente" field.
This is easy to do with an After Insert data macro on the first table:
For more information on data macros, see:
Create a data macro

Sql - create entry in table A for every entry in table B

I have table Users model with id. Now i create table(model) Settings which should store settings for every User form Users table. How can i create entry in table Settings for every exist User from Users table?
Column Users:
id ;some value ; someothervalue;
Column Settings:
id ; user_id ; message_1 ; message_2
I want to create entry in the table Settings for every User. Right now every new User have before_create filter but old users havent got entry in Settings table.
Insert TableSettings(list of ColNames ...)
Select [list of colnames ...]
From TableUsers
Just make sure that the list of colNames in tableSettings match (in the number of columns and datatype) the list of columns in tableUsers.
to start with just the UserId and message_1
Insert tableSettings(userID, message_1)
Select id, 'A message with someotherValue:' + someothervalue
from tableUsers