Home What is the best way to check for unique (SQL)
Reply: 0

What is the best way to check for unique (SQL)

user1499
1#
user1499 Published in April 26, 2018, 1:43 pm

I have a simple MVC application in Java with db (Postgres) and table named users with the following columns:

name,email,age,birthday

One of the function: to register, the user should provide name and email. Both Fields must be unique in table (unique name and unique email)

To validate user input i use the following sql

select * from users where email = ? or name = ?

If the query return one column then user's data is not unique.

With help of JavaMelody I have noticed that this query is the longest one among others (11 ms) How can i speed up this?

BTW

From official docs, Postgres doesn't recommend to create index with multiple columns.

EDIT() in answers I have seen that i should to add unique constraint add catch exception if this exist, but using my query i can check which parameter is not unique

Example:

public Optional<String> isUnuque(final Users user) {
        final Users dbUser = this.repository.findByEmailOrName(user.getEmail(), user.getName(),user.getSteamId());
        if (dbUser != null) {
            if (user.getEmail().equals(dbUser.getEmail())) {
                return Optional.of("Email is not unique");
            }else if(user.getName().equals(dbUser.getName())) {
                return Optional.of("Name is not unique");
            }
        }
        return Optional.empty();
    }
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.393255 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO