Skip to content
Related Articles

Related Articles

Improve Article

SQL | ENCRYPT Function

  • Last Updated : 31 Oct, 2019
Geek Week

The SQL Encrypt function is used to encrypt a string using UNIX crypt(). The function is based on Unix crypt() system call, hence it returns NULL on Windows systems. The Encrypt function accepts two parameters which are the string and the salt to be encrypted.
The Encrypt function returns a binary string.

Syntax:

ENCRYPT(string, salt)

Parameters Used:

  • string – It is used to specify the plain text string that is to be encrypted using UNIX crypt().
  • salt – It is used to specify a string that is at least 2 characters long and cab be used in the encryption process. If salt is not provided, the ENCRYPT function uses a random value.

Return Value:
The Encrypt function in SQL returns a binary string.

The Encrypt function returns null in the following cases:



  • If salt is less than 2 characters in length, then the Encrypt function returns NULL.
  • If the string is NULL, then the Encrypt function returns NULL.
  • If UNIX crypt() is not available on the system, then the Encrypt function returns NULL.

Supported Versions of MySQL:

  • MySQL 5.7
  • MySQL 5.6
  • MySQL 5.5
  • MySQL 5.1
  • MySQL 5.0
  • MySQL 4.1

Example-1: Implementing Encrypt function on a string.

SELECT 
ENCRYPT('xyz'); 

Output:

sf3Le/pz2ApNY 

Example-2: Implementing Encrypt function on a bigger string.

SELECT 
ENCRYPT('geeksforgeeks'); 

Output:

.mblNS3yOZxb2 

Example-3: Implementing Encrypt function on a string by passing both the arguments.

SELECT 
ENCRYPT('geeksforgeeks', '123'); 

Output:

12SrVMQf0pwFU 

Example-4: Implementing Encrypt function on a string by passing less than 2 characters in the salt argument.

SELECT 
ENCRYPT('geeksforgeeks', '2'); 

Output:

NULL 

Since the salt argument is less than 2 characters in length, the Encrypt function returns NULL.

Example-5: Implementing Encrypt function on a NULL string.

SELECT 
ENCRYPT(NULL); 

Output:

NULL 

Attention reader! Don’t stop learning now. Learn SQL for interviews using SQL Course  by GeeksforGeeks.

My Personal Notes arrow_drop_up
Recommended Articles
Page :