Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL create database if not exist

Tags:

I have a T-SQL query which create database if it does not exist yet:

IF (NOT EXISTS (SELECT name                  FROM master.dbo.sysdatabases                  WHERE ('[' + 'DBName' + ']' = 'DBName'                    OR name = 'DBName'))) BEGIN      CREATE DATABASE DBName      PRINT 'DATABASE_CREATED'  END  ELSE      PRINT 'DATABASE_EXIST' 

When I want use this in MySQL I get an error:

'IF' is not valid input at this postion

I change this script as

IF(SELECT COUNT(*) FROM SCHEMA_NAME     FROM INFORMATION_SCHEMA.SCHEMATA     WHERE SCHEMA_NAME = 'DBName') > 0) THEN BEGIN      CREATE DATABASE DBName      PRINT 'DATABASE_CREATED' ELSE      PRINT 'DATABASE_EXIST'` 

but it still doesn't work

How can I create this query in MySQL?

like image 536
Szymson Avatar asked Oct 30 '16 20:10

Szymson


People also ask

Which clause is used to create a database only if it doesn't already exist?

6. To create a database only if it doesn't already exist, which clause is used? Explanation: The 'CREATE DATABASE' statement supports many optional values. To create a database named 'my_db' only if it doesn't already exist, we write 'CREATE DATABASE IF NOT EXISTS my_db'.

How do I create a new database in MySQL?

Using a GUIOpen the MySQL Workbench as an administrator (Right-click, Run as Admin). Click on File>Create Schema to create the database schema. Enter a name for the schema and click Apply. In the Apply SQL Script to Database window, click Apply to run the SQL command that creates the schema.


1 Answers

I'm not sure exactly how you'd check, but if you just want to create it if it doesn't exist, then you can do

CREATE DATABASE IF NOT EXISTS DBname 
like image 98
Dec Sander Avatar answered Oct 11 '22 00:10

Dec Sander