Structured Query Language (SQL) is a powerful programming language designed for managing and manipulating relational databases. Whether you're a budding developer, a data analyst, or an aspiring data scientist, understanding SQL is essential for working with databases. SQL is not limited to a specific DBMS and is supported by various database platforms like MySQL, Mariadb, PostgreSQL, Oracle, Microsoft SQL Server, and SQLite.
⚙️ CRUD Operations
A fundamental concept in SQL is CRUD, which stands for Create, Read, Update, and Delete.
-
Create (C): The Create operation involves adding new records or data to a database. In SQL, the
INSERT
statement is used to create new rows in a table. It allows you to specify the table name, column names, and values to be inserted. This operation is essential for adding new data into the database. -
Read (R): The Read operation involves retrieving or querying existing data from a database. In SQL, the
SELECT
statement is used to read data from one or more tables. It allows you to specify the columns to retrieve, apply filters with theWHERE
clause, perform sorting, and aggregate data. This operation enables you to extract specific information from the database. -
Update (U): The Update operation involves modifying existing data in a database. In SQL, the
UPDATE
statement is used to update one or more rows in a table. It allows you to specify the table, set new values for specific columns, and apply filters with theWHERE
clause to determine which rows to update. This operation is useful for making changes to existing data. -
Delete (D): The Delete operation involves removing existing data from a database. In SQL, the
DELETE
statement is used to delete one or more rows from a table. It allows you to specify the table and apply filters with theWHERE
clause to determine which rows to delete. This operation is essential for removing unwanted or obsolete data from the database.
Key Concepts
Database: A structured collection of data stored in a DBMS. It consists of tables, which contain rows (records) and columns (fields) representing different data attributes.
Query: A request made to a database using SQL statements to retrieve specific data or perform operations on the data.
Table: A database object that stores data in rows and columns. Each column represents a specific attribute, and each row represents a record.
SQL Statements: Commands used to perform various actions in a database. Common SQL statements include SELECT, INSERT, UPDATE, DELETE, and JOIN.
Common Use Cases
SQL is widely used in various industries and domains. Some common use cases include:
-
Data Retrieval: SQL allows you to extract specific data from large databases by using SELECT statements with appropriate filters.
-
Data Manipulation: You can modify and update existing data using SQL statements like INSERT, UPDATE, and DELETE, ensuring the integrity and consistency of the database.
-
Data Analysis: SQL enables aggregating and summarizing data using functions like COUNT, SUM, AVG, GROUP BY, and HAVING, facilitating insightful data analysis.
-
Database Administration: SQL is used to create and manage database objects, such as tables, views, indexes, and stored procedures.
SQL Commands
Command | Description |
---|---|
SELECT | Extracts data from a database |
UPDATE | Updates data in a database |
DELETE | Deletes data from a database |
INSERT INTO | Inserts new data into a database |
CREATE DATABASE | Creates a new database |
ALTER DATABASE | Modifies a database |
DROP DATABASE | Deletes a database |
CREATE TABLE | Creates a new table |
ALTER TABLE | Modifies a table |
DROP TABLE | Deletes a table |
CREATE INDEX | Creates an index (search key) |
DROP INDEX | Deletes an index |
Data Types
- Numeric Data Types:
- INT: Stores whole numbers (integers).
- DECIMAL(p, s): Accommodates fixed-point numbers with specified precision (p) and scale (s).
- FLOAT: Stores floating-point numbers with a floating decimal point.
- Character Data Types:
- CHAR(n): Stores fixed-length character strings, limited to n characters.
- VARCHAR(n): Allows for variable-length character strings, with a maximum length of n characters.
- TEXT: Facilitates storage of variable-length character strings containing large amounts of text data.
- Date and Time Data Types:
- DATE: Stores date values in the format 'YYYY-MM-DD'.
- TIME: Represents time values in the format 'HH:MM:SS'.
- DATETIME: Combines date and time values in the format 'YYYY-MM-DD HH:MM:SS'.
- Boolean Data Type:
- BOOLEAN: Represents true or false values.
- Others:
- BLOB: Enables the storage of binary large objects, such as images or files.
- ENUM: Defines an enumeration type, allowing the specification of predefined values.
CREATE DATABASE
CREATE DATABASE Company;
- Output No output is returned, but the command successfully creates a new database.
CREATE TABLE
Prior to executing the
CREATE TABLE
statement, it is vital to select the correct database using theUSE
statement. Selecting the appropriate database ensures that the table is created within the intended database, preventing potential data inconsistencies or misplacements. Verifying the selected database before creating a table is essential for maintaining an organized and structured data environment.
USE Employee;
A primary key 🔑 in a database is a unique identifier for each record in a table. It ensures that each row in a table can be uniquely identified and distinguishes it from other rows. The primary key can be composed of one or more columns that have unique values for each record.
CREATE TABLE table_name (
EmployeeId INT,
Name VARCHAR(25),
Department VARCHAR(20),
PRIMARY KEY(EmployeeID)
);
- Output No output is returned, but the command successfully creates a new database.
SELECT
Employee |EmployeeID|Name|Department| |---|---|---|---| |1|John Doe|IT| |2|Jane Smith|HR| |3|Mark Brown|Sales|
SELECT * FROM Employee;
- Output
|EmployeeID|Name|Department| |---|---|---|---| |1|John Doe|IT| |2|Jane Smith|HR| |3|Mark Brown|Sales|
SELECT Name FROM Employee;
- Output
Name |
---|
John Doe |
Jane Smith |
Mark Brown |
SELECT Name, Department FROM Employee;
- Output
Name | Department |
---|---|
John Doe | IT |
Jane Smith | HR |
Mark Brown | Sales |
WHERE
The WHERE
clause in SQL allows you to filter and retrieve specific rows from a table based on specified conditions.
SELECT Name, Department FROM Employee;
WHERE Department = "IT";
- Output
Name | Department |
---|---|
John Doe | IT |
INSERT INTO
INSERT INTO Employee (EmployeeID, Name, Department) VALUES (4, "Emily Johnson", "Marketing");
- Output No output is returned, but the command successfully inserts a new record into the table.
To retrieve the updated table after executing the SQL UPDATE
statement, we can use the SELECT
command as follows
SELECT * FROM Employee;
- Output
|EmployeeID|Name|Department| |---|---|---|---| |1|John Doe|IT| |2|Jane Smith|HR| |3|Mark Brown|Sales| |4|Emily Johnson|Marketing|
UPDATE
UPDATE Employee SET Department = "Finance" WHERE EmployeeID = 3;
- Output No output is returned, but the command successfully updates the Department of the employee with EmployeeID 3 to "Finance".
When updating a table in SQL, it is crucial to include a unique identifier, such as an ID or primary key, in the
WHERE
clause of theUPDATE
statement. This ensures that only the intended row or rows are modified. Without a unique identifier, the update operation may inadvertently affect all rows in the table, leading to unexpected changes. Always verify that yourWHERE
clause includes the appropriate unique identifier to accurately update the desired records and prevent unintended updates.
DELETE
UPDATE Employee WHERE EmployeeID = 2;
- Output No output is returned, but the command successfully deletes the record of the employee with EmployeeID 2 from the table.
When using the
DELETE
command in SQL, it is important to include a unique identifier in theWHERE
clause. By specifying a specific identifier, such as a unique ID or primary key, you ensure that only the intended row or rows are deleted. Neglecting to include a unique identifier in theWHERE
clause can result in unintentionally deleting all rows in the table, leading to irreversible data loss. Take care to double-check yourWHERE
clause to guarantee that you are targeting the desired records accurately and avoiding unintended deletions.
SQL is a vital language for managing relational databases.😎 Its ability to handle data operations like creating, retrieving, updating, and deleting makes it a versatile tool for data manipulation and analysis. Understanding key SQL concepts such as CRUD operations, data types, and primary keys is essential for effectively organizing and maintaining data integrity. With its widespread use and compatibility across different database systems, SQL is a crucial skill for data professionals, enabling them to harness the power of structured data in various industries.