Code library

Free snippets & functions

Copy, adapt and use them in your own projects.

SQL · Filter with a subquery (IN)Beginner
SELECT name
FROM customers
WHERE id IN (SELECT customer_id FROM orders WHERE total > 200);

SELECT name FROM products
WHERE price > (SELECT AVG(price) FROM products);

The inner query returns a list. The outer query uses it.

SQL · Round and calculateBeginner
SELECT ROUND(19.987, 2)  AS two_decimals,   -- 19.99
       ROUND(1234.5, -2) AS hundreds,       -- 1200
       CEIL(4.1)         AS up,             -- 5
       FLOOR(4.9)        AS down,           -- 4
       MOD(17, 5)        AS remainder,      -- 2
       ABS(-8)           AS absolute;       -- 8

SELECT name, ROUND(price * 1.17, 2) AS price_with_tax FROM products;

ROUND, CEIL, FLOOR and MOD cover most everyday maths.

SQL · Date and time functionsBeginner
SELECT NOW(), CURDATE(),
       DATE_FORMAT(created_at, '%d %b %Y')   AS pretty,
       YEAR(created_at) AS y, MONTH(created_at) AS m,
       DATEDIFF(NOW(), created_at)           AS days_ago,
       created_at + INTERVAL 30 DAY          AS plus_30
FROM orders;

Format dates, find differences and add time with INTERVAL.

SQL · Common string functionsBeginner
SELECT CONCAT(name, ' <', email, '>')     AS contact,
       UPPER(name)                        AS shout,
       LENGTH(name)                       AS bytes,
       CHAR_LENGTH(name)                  AS letters,
       SUBSTRING(email, 1, 3)             AS start3,
       REPLACE(email, '@x.com', '@site.pk') AS new_email,
       TRIM('  padded  ')                 AS trimmed
FROM customers;

Join, change case, measure and cut text directly in SQL.

SELECT name, price,
  CASE
    WHEN price < 5   THEN 'Cheap'
    WHEN price < 25  THEN 'Medium'
    ELSE 'Expensive'
  END AS band
FROM products;

CASE turns values into labels or groups without changing the data.

SQL · Join three tablesBeginner
SELECT c.name AS customer, o.id AS order_id, p.name AS product, i.qty, i.price
FROM customers c
JOIN orders o      ON o.customer_id = c.id
JOIN order_items i ON i.order_id = o.id
JOIN products p    ON p.id = i.product_id
ORDER BY o.id, p.name;

Follow the keys: customers to orders to order_items to products.

SELECT c.name, COUNT(o.id) AS orders, COALESCE(SUM(o.total), 0) AS spent
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY spent DESC;

LEFT JOIN keeps every row from the left table, even customers with no orders.

DROP TABLE IF EXISTS temp_report;

CREATE TABLE temp_report (id INT, label VARCHAR(40));
DROP TABLE temp_report;

IF EXISTS avoids an error when the table is already gone. DROP cannot be undone.

SQL · Add or remove a columnBeginner
ALTER TABLE customers ADD COLUMN phone VARCHAR(30) NULL AFTER email;
ALTER TABLE customers ADD COLUMN country CHAR(2) NOT NULL DEFAULT 'PK';
ALTER TABLE customers DROP COLUMN country;

ALTER TABLE changes an existing table. Take a backup before changing a live table.

SQL · Create a tableBeginner
CREATE TABLE notes (
  id         INT UNSIGNED NOT NULL AUTO_INCREMENT,
  title      VARCHAR(120) NOT NULL,
  body       TEXT NULL,
  is_public  TINYINT(1) NOT NULL DEFAULT 0,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Pick the smallest sensible type. Use utf8mb4 so any language and emoji work.

SQL · Work with NULLBeginner
SELECT * FROM customers WHERE city IS NULL;
SELECT * FROM customers WHERE city IS NOT NULL;

SELECT name, COALESCE(city, 'Unknown') AS city FROM customers;
SELECT IFNULL(SUM(total), 0) AS revenue FROM orders WHERE status = 'refunded';

NULL means "unknown". Use IS NULL, never = NULL. COALESCE gives a fallback.

SQL · Aliases with ASBeginner
SELECT c.name AS customer,
       o.total AS amount
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
WHERE o.status = 'paid';

Aliases give columns and tables short, readable names.

SQL · Group rows and count themBeginner
SELECT status, COUNT(*) AS orders, SUM(total) AS amount
FROM orders
GROUP BY status
ORDER BY amount DESC;

SELECT category, COUNT(*) AS products FROM products GROUP BY category;

Every column in SELECT must be either grouped or inside an aggregate function.

SQL · COUNT, SUM, AVG, MIN and MAXBeginner
SELECT COUNT(*)            AS orders,
       SUM(total)          AS revenue,
       AVG(total)          AS average,
       MIN(total)          AS smallest,
       MAX(total)          AS largest
FROM orders
WHERE status = 'paid';

Aggregate functions turn many rows into one value.

SQL · Delete rows safelyBeginner
SELECT * FROM orders WHERE status = 'cancelled';

DELETE FROM orders
WHERE status = 'cancelled';

Same rule as UPDATE: test the WHERE with SELECT, then switch to DELETE.

SELECT * FROM products WHERE id = 1;          -- check first

UPDATE products
SET price = price * 1.10, stock = stock - 5
WHERE id = 1;

Without WHERE every row changes. Run a SELECT with the same WHERE first.

INSERT INTO products (name, category, price, stock) VALUES
  ('Eraser',  'Stationery', 0.50, 200),
  ('Ruler',   'Stationery', 1.20, 150),
  ('Monitor', 'Electronics', 150.00, 7);

One INSERT with several value groups is much faster than many single inserts.

SQL · Insert a rowBeginner
INSERT INTO customers (name, email, city, created_at)
VALUES ('Zara', 'zara@x.com', 'Multan', NOW());

SELECT LAST_INSERT_ID();          -- the new auto-increment id

Name the columns so the query keeps working when the table gets a new column.

SELECT DISTINCT city FROM customers;
SELECT DISTINCT category FROM products ORDER BY category;
SELECT COUNT(DISTINCT city) AS cities FROM customers;

DISTINCT returns each different value once.

SQL · Search text with LIKEBeginner
SELECT * FROM customers WHERE name LIKE 'A%';        -- starts with A
SELECT * FROM customers WHERE email LIKE '%@x.com';  -- ends with
SELECT * FROM customers WHERE name LIKE '%a%';       -- contains
SELECT * FROM customers WHERE name LIKE '_li';       -- 3 letters ending in li

% matches any number of characters, _ matches exactly one.

SELECT name, price
FROM products
ORDER BY price DESC
LIMIT 3;                          -- the 3 most expensive

SELECT * FROM customers ORDER BY city ASC, name ASC;

ORDER BY sorts (ASC is the default). LIMIT keeps only the first rows.

SQL · Filter rows with WHEREBeginner
SELECT name, city
FROM customers
WHERE city = 'Lahore' AND active = 1;

SELECT * FROM products WHERE category IN ('Stationery', 'Home');
SELECT * FROM products WHERE price BETWEEN 5 AND 20;
SELECT * FROM orders WHERE status <> 'cancelled' AND (total > 200 OR status = 'pending');

Combine conditions with AND / OR, and use IN and BETWEEN to keep queries short.

SQL · Choose the columns you needBeginner
SELECT id, name, city
FROM customers;

-- all columns (fine while learning)
SELECT * FROM customers;

SELECT lists columns. Avoid SELECT * in real code: it is slower and breaks when the table changes.

PHP · Build strings with sprintfBeginner
$s = sprintf('%s has %d items, total %.2f', 'Cart', 3, 59.5);   // Cart has 3 items, total 59.50
$id = sprintf('INV-%05d', 42);                                   // INV-00042
$pct = sprintf('%d%%', 80);                                      // 80%
$col = sprintf('#%02x%02x%02x', 255, 128, 0);                    // #ff8000
printf("%-10s|%6.1f\n", 'Left', 3.14159);                        // padded columns

sprintf() puts values into a template and returns the string. printf() prints it.

const SITE_NAME = 'My Site';                 // top level
define('MAX_UPLOAD_MB', 5);                  // also works inside if-blocks

class Role
{
    public const ADMIN  = 'admin';
    public const EDITOR = 'editor';
}

echo SITE_NAME, ' ', MAX_UPLOAD_MB, ' ', Role::ADMIN;
var_dump(defined('SITE_NAME'));              // true

Constants never change after they are set. Use them for fixed settings and magic numbers.

function divide(int $a, int $b): float
{
    if ($b === 0) {
        throw new InvalidArgumentException('Cannot divide by zero');
    }
    return $a / $b;
}

try {
    echo divide(10, 0);
} catch (InvalidArgumentException $e) {
    echo 'Problem: ' . $e->getMessage();
} catch (Throwable $e) {
    error_log($e->getMessage());       // anything else: log it, show a generic message
    echo 'Something went wrong.';
} finally {
    // runs always (close files, release locks)
}

Wrap risky code in try. Catch the specific exception you expect and always have a safe fallback.

$a = 0; $b = ''; $c = null;

var_dump(isset($a));     // true   (exists)
var_dump(isset($c));     // false  (null)
var_dump(empty($a));     // true   (0 is empty)
var_dump(empty($b));     // true
var_dump(is_null($c));   // true

$page = $_GET['page'] ?? 1;          // default when missing or null
$name ??= 'Guest';                   // assign only if missing/null (PHP 7.4+)

Know the difference: isset checks that a value exists and is not null. empty treats 0, "" and "0" as empty.

$dice  = random_int(1, 6);                    // secure random number
$token = bin2hex(random_bytes(16));           // 32 hex characters
$code  = str_pad((string)random_int(0, 999999), 6, '0', STR_PAD_LEFT);  // 6-digit code

$items = ['a', 'b', 'c'];
$pick  = $items[array_rand($items)];          // one random item
shuffle($items);                              // random order

Use random_int() and random_bytes() for anything security related. rand() and mt_rand() are not safe for that.

PHP · Format numbers and pricesBeginner
$n = 1234567.891;

echo number_format($n);                 // 1,234,568
echo number_format($n, 2);              // 1,234,567.89
echo number_format($n, 2, ',', '.');    // 1.234.567,89

echo round(3.14159, 2);                 // 3.14
echo floor(4.9);                        // 4
echo ceil(4.1);                         // 5
echo intdiv(17, 5), ' ', 17 % 5;        // 3 2

number_format() adds separators. round(), floor() and ceil() change the value itself.

$name = 'Ali';

echo <<<HTML
<h1>Hello, {$name}</h1>
<p>Today is {$_SERVER['REQUEST_METHOD']}.</p>
HTML;

echo <<<'RAW'
This is printed as is: $name and {$name}
RAW;

Heredoc expands variables like double quotes. Nowdoc keeps everything literally, like single quotes.