Hello, World in SQL
Run your first query and get familiar with tools.
Connect to a database
- Postgres:
psql postgresql://user:pass@localhost:5432/db - MySQL:
mysql -h 127.0.0.1 -u user -p db - SQLite:
sqlite3 db.sqlite - GUI options: DBeaver, TablePlus, DataGrip, psql/pgcli
First query
-- Create a sample table
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE
);
-- Insert a row
INSERT INTO users (name, email) VALUES ('Ada', 'ada@example.com');
-- Read rows
SELECT id, name, email FROM users;
The exact DDL/DDL types vary per engine, but SELECT syntax is broadly portable.
Result set basics
- Columns have names and types
- Rows are ordered only if you specify
ORDER BY NULLmeans “unknown/missing”, not zero or empty
Tools and workflows
- Keep queries in version control (
.sqlfiles) - Use transactions when changing data (
BEGIN; ... COMMIT;) - Favor parameterized queries in application code to prevent injection
Summary
- Connect, create a table, insert, then SELECT
- Results are unordered without
ORDER BY; treatNULLcarefully