SQL (Structured Query Language) databases are relational databases that store data in tables with a predefined schema. Tables are related to each other through keys, allowing for complex queries across multiple tables. They follow the ACID (Atomicity, Consistency, Isolation, Durability) properties, which ensure data integrity and reliability. For example, a traditional e - commerce application might use an SQL database to store customer information, order details, and product catalogs.
NoSQL databases, as the name suggests, do not rely on the traditional SQL query language. They are non - relational databases designed to handle large volumes of unstructured or semi - structured data. NoSQL databases come in various types, such as document - based, key - value, column - family, and graph databases. They offer high scalability, flexibility, and performance, making them suitable for big data and real - time applications. For instance, a social media platform might use a NoSQL database to store user posts, comments, and likes.
Here is a simple example of creating a table and inserting data in a MySQL database using Python:
import mysql.connector
# Connect to the database
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# Create a cursor object
mycursor = mydb.cursor()
# Create a table
mycursor.execute("CREATE TABLE IF NOT EXISTS customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")
# Insert data into the table
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John Doe", "Highway 37")
mycursor.execute(sql, val)
# Commit the changes
mydb.commit()
print(mycursor.rowcount, "record inserted.")
Let’s take MongoDB, a popular document - based NoSQL database, as an example. Here is how you can insert a document into a collection using Python:
from pymongo import MongoClient
# Connect to the MongoDB server
client = MongoClient('mongodb://localhost:27017/')
# Select a database
db = client['yourdatabase']
# Select a collection
collection = db['customers']
# Create a document
customer = {
"name": "Jane Smith",
"address": "123 Elm Street"
}
# Insert the document into the collection
result = collection.insert_one(customer)
print("Inserted document ID:", result.inserted_id)
WHERE
, JOIN
, and ORDER BY
clauses to improve query performance.The choice between SQL and NoSQL databases depends on various factors, including the nature of your data, the complexity of your queries, and the scalability requirements of your application. SQL databases are well - suited for structured data and complex queries, while NoSQL databases offer flexibility and scalability for unstructured and semi - structured data. By understanding the fundamental concepts, usage methods, common practices, and best practices of both types of databases, you can make an informed decision that meets the specific needs of your project.