Hur man skapar en databas i MySQL (Skapa MySQL tabeller)

โšก Smart sammanfattning

Skapa en databas i MySQL follows two proven paths: executing a CREATE DATABASE statement, or generating physical schemas from an ER model through MySQL Workbench forward engineering. Both approaches produce identical, production-ready tables.

  • ๐Ÿ—„๏ธ Database Creation: Run CREATE DATABASE movies; or CREATE SCHEMA, which MySQL treats as a synonym.
  • ๐Ÿ›ก๏ธ Safe Re-Runs: Add IF NOT EXISTS so a repeated script skips creation instead of raising a duplicate-name error.
  • ๐ŸŒ Teckenuppsรคttning: Choose utf8mb4 with utf8mb4_0900_ai_ci for multilingual data; latin1 with latin1_swedish_ci suits legacy English-only schemas.
  • ๐Ÿงฑ Table Creation: CREATE TABLE defines each field name, data type, PRIMARY KEY, and the storage engine, normally InnoDB.
  • ๐Ÿ”ข Datatyper: Column types fall into numeric, text, and date or time families, plus ENUM, SET, BOOL, and binary variants.
  • โš™๏ธ Forward Engineering: MySQL Workbench converts an approved ER model into executable SQL scripts and commits them to a live server.

Steg fรถr att skapa databas i MySQL

A database in MySQL is a named container for tables, views, and related objects. You can create one in two ways:

1) Genom att kรถra en enkel SQL-frรฅga

2) Genom att anvรคnda forward engineering i MySQL Arbetsbรคnk

As SQL nybรถrjare, lรฅt oss fรถrst titta pรฅ frรฅgemetoden.

Hur man skapar en databas i MySQL

Sรฅ hรคr skapar du en databas i MySQL:

CREATE DATABASE รคr SQL-kommandot som anvรคnds fรถr att skapa en databas i MySQL.

Imagine you need to create a database with the name โ€œmoviesโ€. You can create a database in MySQL by executing the following SQL command.

CREATE DATABASE movies;

Note: You can also use the command CREATE SCHEMA instead of CREATE DATABASE.

The statement works only once. Running it again throws an error, so letโ€™s improve the query with more parameters.

OM INTE FINNS

En enda MySQL server can hold many databases. When several people share that server, you may try to create a database with the name of an existing one.

OM INTE FINNS instructs the MySQL server to check for a database with the same name before creating it. The database is created only if the name is free; without this clause, MySQL ger ett fel.

CREATE DATABASE IF NOT EXISTS movies;

Once the database name is safe, the next decision is how MySQL should store and compare the text inside it.

Sortering och teckenuppsรคttning

A teckenuppsรคttning decides which characters a column can store, while a tione รคr uppsรคttningen av rules used in comparison and sorting. Both can be defined at four levels: server, database, table, and column.

The collation you choose depends on the character set. For instance, the latin1 character set uses the latin1_swedish_ci collation, which is the Swedish case-insensitive order.

CREATE DATABASE IF NOT EXISTS movies CHARACTER SET latin1 COLLATE latin1_swedish_ci;

For local languages such as Arabic or Chinese, select the Unicode utf8mb4 character set, which stores every Unicode character, including emoji. In MySQL 8.0 utf8mb4 is the default character set and utf8mb4_0900_ai_ci the default collation.

CREATE DATABASE IF NOT EXISTS movies CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;

Du kan hitta listan รถver alla sorteringar och teckenuppsรคttningar hรคr..

You can see the list of existing databases by running the following SQL command.

SHOW DATABASES;

With the database in place, you can now add the tables that will actually hold the records.

Hur man skapar en tabell i MySQL

The CREATE TABLE command is used to create tables in a database.

Skapa tabell i MySQL

As the diagram shows, every table belongs to one database. Tables are created with the SKAPA BORD statement, which has the following syntax.

CREATE TABLE [IF NOT EXISTS] `TableName` (`fieldname` dataType [optional parameters]) ENGINE = storage Engine;

Hร„R

  • โ€œCREATE TABLEโ€ is responsible for the creation of the table in the database.
  • โ€œ[IF NOT EXISTS]โ€ is optional and only creates the table if no matching table name is found.
  • โ€œ`fieldName`โ€ is the name of the field, and โ€œdata Typeโ€ defines the nature of the data stored in it.
  • โ€œ[optional parameters]โ€ is extra information about a field, such as โ€œAUTO_INCREMENTโ€ or NOT NULL.
  • โ€œstorage Engineโ€ manages the table, normally InnoDB, which supports transactions and foreign keys.

MySQL Skapa tabellexempel

Nedan fรถljer en MySQL example to create a table in a database:

CREATE TABLE IF NOT EXISTS `MyFlixDB`.`Members` (
  `membership_number` INT AUTO_INCREMENT ,
  `full_names` VARCHAR(150) NOT NULL ,
  `gender` VARCHAR(6) ,
  `date_of_birth` DATE ,
  `physical_address` VARCHAR(255) ,
  `postal_address` VARCHAR(255) ,
  `contact_number` VARCHAR(75) ,
  `email` VARCHAR(255) ,
  PRIMARY KEY (`membership_number`) )
ENGINE = InnoDB;

Obs: den korrekta MySQL keyword is AUTO_INCREMENT with an underscore. AUTOINCREMENT tillhรถr SQLite and raises a syntax error in MySQL.

Every column carries a data type, so choose carefully: neither underestimate nor overestimate the range of data you expect.

MySQL Datatyper

Data types define the nature of the data that can be stored in a particular column of a table.

MySQL har 3 main categories of data types, namely:

  1. Numerisk
  2. text
  3. Datum Tid

Numeriska datatyper

Numeric data types are used to store numeric values. It is very important to make sure the range of your data is between the lower and upper boundaries of the numeric data type you pick.

TINYINT( ) -128 till 127 normal
0 till 255 OSIGNERAD.
SMALLINT( ) -32768 till 32767 normal
0 till 65535 OSIGNERAD.
MEDIUMINT( ) -8388608 till 8388607 normal
0 till 16777215 OSIGNERAD.
INT( ) -2147483648 till 2147483647 normal
0 till 4294967295 OSIGNERAD.
BIGINT( ) -9223372036854775808 till 9223372036854775807 normal
0 till 18446744073709551615 OSIGNERAD.
FLOTTร–R Ett litet ungefรคrligt tal med en flytande decimalkomma.
DUBBEL( , ) Ett stort tal med en flytande decimalkomma.
DECIMAL( , ) A DOUBLE stored as a string, allowing for a fixed decimal point. Choice for storing currency values.

Textdatatyper

As the data type category name implies, these are used to store text values. Always make sure the length of your textual data does not exceed the maximum length of the column.

CHAR( ) En fast sektion frรฅn 0 till 255 tecken lรฅng.
VARCHAR( ) En variabel sektion frรฅn 0 till 255 tecken lรฅng.
TINYTEXT En strรคng med en maximal lรคngd pรฅ 255 tecken.
TEXT En strรคng med en maximal lรคngd pรฅ 65535 tecken.
KLICK En strรคng med en maximal lรคngd pรฅ 65535 tecken.
MEDELTEXT En strรคng med en maximal lรคngd pรฅ 16777215 tecken.
MEDELBLร…TT En strรคng med en maximal lรคngd pรฅ 16777215 tecken.
Lร…NGTEXT En strรคng med en maximal lรคngd pรฅ 4294967295 tecken.
Lร…NGBLOB En strรคng med en maximal lรคngd pรฅ 4294967295 tecken.

Date and Time Data Types

Date and time data types store calendar and clock values in a fixed format, which keeps sorting and comparison reliable.

DATUM ร…ร…ร…ร…-MM-DD
Datum Tid ร…ร…ร…ร…-MM-DD HH: MM: SS
TIDSSTร„MPEL YYYYMMDDHHMMSS
TID HH: MM: SS

Andra datatyper

Apart from the above, there are some other data types in MySQL.

ENUM To store a text value chosen from a list of predefined text values
Godkรคnn Detta anvรคnds ocksรฅ fรถr att lagra textvรคrden valda frรฅn en lista med fรถrdefinierade textvรคrden. Det kan ha flera vรคrden.
BOOL Synonym fรถr TINYINT(1), anvรคnds fรถr att lagra booleska vรคrden
Binary Similar to CHAR; the difference is that texts are stored in binary format.
VARBINร„R Similar to VARCHAR; the difference is that texts are stored in binary format.

Now letโ€™s see a query for creating a table which uses all the data types. Study it and identify how each data type is defined in the below create table MySQL exempel.

CREATE TABLE `all_data_types` (
    `varchar` VARCHAR( 20 )  ,
    `tinyint` TINYINT  ,
    `text` TEXT  ,
    `date` DATE  ,
    `smallint` SMALLINT  ,
    `mediumint` MEDIUMINT  ,
    `int` INT  ,
    `bigint` BIGINT  ,
    `float` FLOAT( 10, 2 )  ,
    `double` DOUBLE  ,
    `decimal` DECIMAL( 10, 2 )  ,
    `datetime` DATETIME  ,
    `timestamp` TIMESTAMP  ,
    `time` TIME  ,
    `year` YEAR  ,
    `char` CHAR( 10 )  ,
    `tinyblob` TINYBLOB  ,
    `tinytext` TINYTEXT  ,
    `blob` BLOB  ,
    `mediumblob` MEDIUMBLOB  ,
    `mediumtext` MEDIUMTEXT  ,
    `longblob` LONGBLOB  ,
    `longtext` LONGTEXT  ,
    `enum` ENUM( '1', '2', '3' )  ,
    `set` SET( '1', '2', '3' )  ,
    `bool` BOOL  ,
    `binary` BINARY( 20 )  ,
    `varbinary` VARBINARY( 20 )
) ENGINE = MYISAM;

Bรคsta metoder fรถr att skapa en MySQL Databas

A few conventions keep your scripts readable:

  • Use upper case letters for SQL keywords, i.e. โ€œDROP SCHEMA IF EXISTS `MyFlixDB`;โ€
  • End all your SQL commands using semicolons.
  • Avoid using spaces in schema, table, and field names. Use underscores instead to separate schema, table, or field names.
  • Prefer InnoDB over MyISAM for new tables, because InnoDB supports transactions, row-level locking, and foreign keys.

The query method is complete. The second route reaches the same database from a visual model instead of hand-written SQL.

Hur man skapar MySQL Workbench ER Diagram Forward Engineering

MySQL Arbetsbรคnk har verktyg som stรถder forward engineering. Forward engineering is the technical term that describes the process of translating a logical model into a physical implementation automatically.

Vi skapade en ER-diagram i vรฅr ER-modellering lesson. We will now use that ER model to generate the SQL scripts that will create our database.

Skapar MyFlix-databasen frรฅn MyFlix ER-modellen

Step 1) Open the ER model of the MyFlix database som du skapade tidigare.

Steg 2) Vรคlj forward engineer

Click on the Database menu and select Forward Engineer.

Select forward engineer in MySQL Arbetsbรคnk

Step 3) Connection options

The next window allows you to connect to an instance of MySQL server. Click on the stored connection drop-down list and select local host. Click Execute.

Connection options in the forward engineer wizard

Step 4) Select the options shown below

Select the options shown below in the wizard that appears. Click Next.

Forward engineer options for the MyFlix database

Step 5) Keep the selections default and click Next

The next screen shows the summary of objects in our EER diagram. Our MyFlix DB has 5 tables. Keep the selections default and click Next.

Summary of objects in the MyFlix EER diagram

Steg 6) Revse SQL-skriptet

The window below previews the SQL script that creates our database. Save the script to a *.sql file or copy it to the clipboard, then click Next.

Preview of the generated SQL script

Step 7) Commit progress

The window below appears once the database is created on the selected MySQL server instance. The tables from the ER model now exist physically on the server.

Forward engineering commit progress window

The database along with dummy data is attached. We will use this DB in the lessons that follow. Simply import it in MySQL Workbench to get started.

Klicka hรคr fรถr att ladda ner MyFlixDB

Vanliga frรฅgor

There is no difference in MySQL. CREATE SCHEMA is an alias for CREATE DATABASE, and both build the same object. In other systems, such as Oracle, a schema and a database remain separate concepts.

Run DROP DATABASE IF EXISTS movies; from the client or from MySQL Arbetsbรคnk. The command permanently deletes the database and every table inside it, so take a backup first.

The account needs the CREATE privilege at the global level. Administrators grant it with GRANT CREATE ON *.* TO โ€˜userโ€™@โ€™localhostโ€™;. Without that privilege, the server returns an access denied error.

Yes. AI assistants turn a plain description of your entities into CREATE TABLE scripts with keys and data types. Always review the generated types, lengths, and constraints before running the script on a production server.

AI features in modern database clients read your ER-diagram or query history and suggest normalization fixes, index candidates, and data type corrections. The suggestions speed up design reviews, but a human still approves every change.

Sammanfatta detta inlรคgg med: