-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.sql
More file actions
111 lines (98 loc) · 2.28 KB
/
example.sql
File metadata and controls
111 lines (98 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
---
-- @name CreateUsersTable
CREATE TABLE users (
id INTEGER PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
active BOOLEAN DEFAULT TRUE
);
---
---
-- @name CreateOrdersTable
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
user_id INTEGER,
total_amount DECIMAL(10,2),
status VARCHAR(20) DEFAULT 'pending',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
);
---
-- @name InsertSampleUsers
INSERT INTO users (username, email) VALUES
('alice', 'alice@example.com'),
('bob', 'bob@example.com'),
('charlie', 'charlie@example.com'),
('diana', 'diana@example.com');
---
-- @name InsertSampleOrders
INSERT INTO orders (user_id, total_amount, status) VALUES
(1, 29.99, 'completed'),
(1, 15.50, 'completed'),
(2, 450.00, 'pending'),
(2, 89.99, 'completed'),
(3, 1200.00, 'completed'),
(4, 25.00, 'cancelled');
---
-- @name GetAllUsers
SELECT * FROM users ORDER BY created_at;
---
-- @name GetActiveUsers
SELECT id, username, email
FROM users
WHERE active = TRUE
ORDER BY username;
---
-- @name GetLargeOrders
SELECT o.id, u.username, o.total_amount, o.status
FROM orders o
JOIN users u ON o.user_id = u.id
WHERE o.total_amount > 100
ORDER BY o.total_amount DESC;
---
-- @name GetUserOrderSummary
SELECT
u.username,
COUNT(o.id) as order_count,
COALESCE(SUM(o.total_amount), 0) as total_spent,
COALESCE(AVG(o.total_amount), 0) as avg_order_value
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.id, u.username
ORDER BY total_spent DESC;
---
-- @name GetRecentOrders
SELECT
o.id,
u.username,
o.total_amount,
o.status,
o.created_at
FROM orders o
JOIN users u ON o.user_id = u.id
WHERE o.created_at > DATE('now', '-7 days')
ORDER BY o.created_at DESC;
---
-- @name CountOrdersByStatus
SELECT status, COUNT(*) as count
FROM orders
GROUP BY status
ORDER BY count DESC;
---
-- @name CleanupTestData
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS users;
---
-- @name QueryWithVariables
SELECT *
FROM orders o, users u
WHERE u.id=@user_id
AND u.active=@active
AND o.status=@status
AND o.user_id=u.id
LIMIT @lim;
SET @user_id=2;
SET @lim=10;
SET @active=true;
SET @status="completed";