SQL SQL Tutorial SQL Database



SQL Syntax

Structured Query Language (SQL) is a standard language used to manage and manipulate relational databases. SQL syntax is the set of rules and guidelines that define how SQL statements are written and executed. SQL syntax is used to create, modify, and retrieve data from databases.

SQL syntax is divided into several categories, including Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), and Transaction Control Language (TCL).

Data Definition Language (DDL)

DDL is used to define the structure of a database. It includes commands such as CREATE, ALTER, and DROP. The CREATE command is used to create a new database, table, or view. The ALTER command is used to modify the structure of an existing database object. The DROP command is used to delete a database object.

Example:

<?php
// Create a new table
CREATE TABLE users (
    id INT(11) NOT NULL AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) NOT NULL,
    PRIMARY KEY (id)
);
?>

Data Manipulation Language (DML)

DML is used to manipulate data in a database. It includes commands such as SELECT, INSERT, UPDATE, and DELETE. The SELECT command is used to retrieve data from a database. The INSERT command is used to add new data to a database. The UPDATE command is used to modify existing data in a database. The DELETE command is used to remove data from a database.

Example:

<?php
// Retrieve data from a table
SELECT * FROM users;

// Add new data to a table
INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com');

// Modify existing data in a table
UPDATE users SET email='jane@example.com' WHERE name='Jane Doe';

// Remove data from a table
DELETE FROM users WHERE name='John Doe';
?>

Data Control Language (DCL)

DCL is used to control access to a database. It includes commands such as GRANT and REVOKE. The GRANT command is used to give users access to a database object. The REVOKE command is used to remove access to a database object.

Example:

<?php
// Give a user access to a table
GRANT SELECT, INSERT ON users TO 'john'@'localhost';

// Remove a user's access to a table
REVOKE SELECT, INSERT ON users FROM 'john'@'localhost';
?>

Transaction Control Language (TCL)

TCL is used to manage transactions in a database. It includes commands such as COMMIT and ROLLBACK. The COMMIT command is used to save changes made to a database. The ROLLBACK command is used to undo changes made to a database.

Example:

<?php
// Start a transaction
START TRANSACTION;

// Make changes to a table
UPDATE users SET email='jane@example.com' WHERE name='Jane Doe';

// Save changes
COMMIT;

// Undo changes
ROLLBACK;
?>

SQL syntax is an essential part of working with relational databases. Understanding SQL syntax is crucial for creating, modifying, and retrieving data from databases.

References:

Activity